From 04e26e8670f1b044be196deddfa96ed56aa19187 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sat, 27 Feb 2016 20:25:36 -0500
Subject: [PATCH 001/112] Beginning work on conversion to PHP Traits
---
.gitchange | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.gitchange b/.gitchange
index f6be8e8c..2c9e7c6c 100644
--- a/.gitchange
+++ b/.gitchange
@@ -1 +1 @@
-1450911210
+1456622716
From 007e377814a0bee893b496fa3cbb2333fe26b165 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sat, 27 Feb 2016 20:34:18 -0500
Subject: [PATCH 002/112] Convert to Traits: Update namespace.
See websharks/comet-cache#635
---
src/includes/{closures => traits}/Ac/AbortUtils.php | 2 +-
src/includes/{closures => traits}/Ac/AcPluginUtils.php | 2 +-
src/includes/{closures => traits}/Ac/BrowserUtils.php | 2 +-
src/includes/{closures => traits}/Ac/HtmlCUtils.php | 2 +-
src/includes/{closures => traits}/Ac/NcDebugConsts.php | 2 +-
src/includes/{closures => traits}/Ac/NcDebugUtils.php | 2 +-
src/includes/{closures => traits}/Ac/ObUtils.php | 2 +-
src/includes/{closures => traits}/Ac/PostloadUtils.php | 2 +-
src/includes/{closures => traits}/Ac/ShutdownUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/ActionUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/AdminBarUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/AutoCacheUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/BbPressUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/CdnUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/CleanupUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/CondUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/CronUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/DbUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/DirUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/HtaccessUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/HtmlCUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/InstallUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/MenuPageUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/NoticeUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/OptionUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/PostUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/StatsUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/UpdateUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/UrlUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/UserUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpAuthorUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpCdnUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpCommentUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpEvalUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpFeedUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpHomeBlogUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpHtmlCUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpJetpackUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpOpcacheUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpPluginUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpPostTypeUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpPostUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpS2cleanUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpSettingUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpSitemapUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpTermUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpTransientUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpUpdaterUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpUrlUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpUserUtils.php | 2 +-
src/includes/{closures => traits}/Plugin/WcpUtils.php | 2 +-
.../{closures => traits}/Plugin/WcpWooCommerceUtils.php | 2 +-
src/includes/{closures => traits}/Shared/BlogUtils.php | 2 +-
src/includes/{closures => traits}/Shared/CacheDirUtils.php | 2 +-
src/includes/{closures => traits}/Shared/CacheLockUtils.php | 2 +-
src/includes/{closures => traits}/Shared/CachePathConsts.php | 2 +-
src/includes/{closures => traits}/Shared/CachePathUtils.php | 2 +-
src/includes/{closures => traits}/Shared/ConditionalUtils.php | 2 +-
src/includes/{closures => traits}/Shared/DomainMappingUtils.php | 2 +-
src/includes/{closures => traits}/Shared/EscapeUtils.php | 2 +-
src/includes/{closures => traits}/Shared/FsUtils.php | 2 +-
src/includes/{closures => traits}/Shared/HookUtils.php | 2 +-
src/includes/{closures => traits}/Shared/HttpUtils.php | 2 +-
src/includes/{closures => traits}/Shared/I18nUtils.php | 2 +-
src/includes/{closures => traits}/Shared/IpAddrUtils.php | 2 +-
src/includes/{closures => traits}/Shared/PatternUtils.php | 2 +-
src/includes/{closures => traits}/Shared/ReplaceUtils.php | 2 +-
src/includes/{closures => traits}/Shared/ServerUtils.php | 2 +-
src/includes/{closures => traits}/Shared/StringUtils.php | 2 +-
src/includes/{closures => traits}/Shared/SysUtils.php | 2 +-
src/includes/{closures => traits}/Shared/TokenUtils.php | 2 +-
src/includes/{closures => traits}/Shared/TrimUtils.php | 2 +-
src/includes/{closures => traits}/Shared/UrlUtils.php | 2 +-
73 files changed, 73 insertions(+), 73 deletions(-)
rename src/includes/{closures => traits}/Ac/AbortUtils.php (86%)
rename src/includes/{closures => traits}/Ac/AcPluginUtils.php (94%)
rename src/includes/{closures => traits}/Ac/BrowserUtils.php (97%)
rename src/includes/{closures => traits}/Ac/HtmlCUtils.php (98%)
rename src/includes/{closures => traits}/Ac/NcDebugConsts.php (99%)
rename src/includes/{closures => traits}/Ac/NcDebugUtils.php (99%)
rename src/includes/{closures => traits}/Ac/ObUtils.php (99%)
rename src/includes/{closures => traits}/Ac/PostloadUtils.php (99%)
rename src/includes/{closures => traits}/Ac/ShutdownUtils.php (92%)
rename src/includes/{closures => traits}/Plugin/ActionUtils.php (90%)
rename src/includes/{closures => traits}/Plugin/AdminBarUtils.php (99%)
rename src/includes/{closures => traits}/Plugin/AutoCacheUtils.php (99%)
rename src/includes/{closures => traits}/Plugin/BbPressUtils.php (96%)
rename src/includes/{closures => traits}/Plugin/CdnUtils.php (89%)
rename src/includes/{closures => traits}/Plugin/CleanupUtils.php (94%)
rename src/includes/{closures => traits}/Plugin/CondUtils.php (81%)
rename src/includes/{closures => traits}/Plugin/CronUtils.php (98%)
rename src/includes/{closures => traits}/Plugin/DbUtils.php (78%)
rename src/includes/{closures => traits}/Plugin/DirUtils.php (98%)
rename src/includes/{closures => traits}/Plugin/HtaccessUtils.php (99%)
rename src/includes/{closures => traits}/Plugin/HtmlCUtils.php (87%)
rename src/includes/{closures => traits}/Plugin/InstallUtils.php (99%)
rename src/includes/{closures => traits}/Plugin/MenuPageUtils.php (99%)
rename src/includes/{closures => traits}/Plugin/NoticeUtils.php (99%)
rename src/includes/{closures => traits}/Plugin/OptionUtils.php (98%)
rename src/includes/{closures => traits}/Plugin/PostUtils.php (95%)
rename src/includes/{closures => traits}/Plugin/StatsUtils.php (96%)
rename src/includes/{closures => traits}/Plugin/UpdateUtils.php (99%)
rename src/includes/{closures => traits}/Plugin/UrlUtils.php (91%)
rename src/includes/{closures => traits}/Plugin/UserUtils.php (98%)
rename src/includes/{closures => traits}/Plugin/WcpAuthorUtils.php (98%)
rename src/includes/{closures => traits}/Plugin/WcpCdnUtils.php (96%)
rename src/includes/{closures => traits}/Plugin/WcpCommentUtils.php (98%)
rename src/includes/{closures => traits}/Plugin/WcpEvalUtils.php (96%)
rename src/includes/{closures => traits}/Plugin/WcpFeedUtils.php (99%)
rename src/includes/{closures => traits}/Plugin/WcpHomeBlogUtils.php (98%)
rename src/includes/{closures => traits}/Plugin/WcpHtmlCUtils.php (98%)
rename src/includes/{closures => traits}/Plugin/WcpJetpackUtils.php (92%)
rename src/includes/{closures => traits}/Plugin/WcpOpcacheUtils.php (97%)
rename src/includes/{closures => traits}/Plugin/WcpPluginUtils.php (94%)
rename src/includes/{closures => traits}/Plugin/WcpPostTypeUtils.php (98%)
rename src/includes/{closures => traits}/Plugin/WcpPostUtils.php (99%)
rename src/includes/{closures => traits}/Plugin/WcpS2cleanUtils.php (96%)
rename src/includes/{closures => traits}/Plugin/WcpSettingUtils.php (95%)
rename src/includes/{closures => traits}/Plugin/WcpSitemapUtils.php (97%)
rename src/includes/{closures => traits}/Plugin/WcpTermUtils.php (99%)
rename src/includes/{closures => traits}/Plugin/WcpTransientUtils.php (98%)
rename src/includes/{closures => traits}/Plugin/WcpUpdaterUtils.php (98%)
rename src/includes/{closures => traits}/Plugin/WcpUrlUtils.php (97%)
rename src/includes/{closures => traits}/Plugin/WcpUserUtils.php (98%)
rename src/includes/{closures => traits}/Plugin/WcpUtils.php (99%)
rename src/includes/{closures => traits}/Plugin/WcpWooCommerceUtils.php (93%)
rename src/includes/{closures => traits}/Shared/BlogUtils.php (94%)
rename src/includes/{closures => traits}/Shared/CacheDirUtils.php (99%)
rename src/includes/{closures => traits}/Shared/CacheLockUtils.php (98%)
rename src/includes/{closures => traits}/Shared/CachePathConsts.php (97%)
rename src/includes/{closures => traits}/Shared/CachePathUtils.php (99%)
rename src/includes/{closures => traits}/Shared/ConditionalUtils.php (99%)
rename src/includes/{closures => traits}/Shared/DomainMappingUtils.php (99%)
rename src/includes/{closures => traits}/Shared/EscapeUtils.php (90%)
rename src/includes/{closures => traits}/Shared/FsUtils.php (99%)
rename src/includes/{closures => traits}/Shared/HookUtils.php (99%)
rename src/includes/{closures => traits}/Shared/HttpUtils.php (98%)
rename src/includes/{closures => traits}/Shared/I18nUtils.php (96%)
rename src/includes/{closures => traits}/Shared/IpAddrUtils.php (98%)
rename src/includes/{closures => traits}/Shared/PatternUtils.php (96%)
rename src/includes/{closures => traits}/Shared/ReplaceUtils.php (96%)
rename src/includes/{closures => traits}/Shared/ServerUtils.php (97%)
rename src/includes/{closures => traits}/Shared/StringUtils.php (98%)
rename src/includes/{closures => traits}/Shared/SysUtils.php (98%)
rename src/includes/{closures => traits}/Shared/TokenUtils.php (99%)
rename src/includes/{closures => traits}/Shared/TrimUtils.php (95%)
rename src/includes/{closures => traits}/Shared/UrlUtils.php (98%)
diff --git a/src/includes/closures/Ac/AbortUtils.php b/src/includes/traits/Ac/AbortUtils.php
similarity index 86%
rename from src/includes/closures/Ac/AbortUtils.php
rename to src/includes/traits/Ac/AbortUtils.php
index d17875b1..c09c597f 100644
--- a/src/includes/closures/Ac/AbortUtils.php
+++ b/src/includes/traits/Ac/AbortUtils.php
@@ -1,5 +1,5 @@
Date: Sat, 27 Feb 2016 20:45:28 -0500
Subject: [PATCH 003/112] Convert to Traits: Convert $self->property = value;
See websharks/comet-cache#635
---
src/includes/traits/Ac/NcDebugUtils.php | 2 +-
src/includes/traits/Ac/PostloadUtils.php | 20 +++++++++----------
src/includes/traits/Plugin/HtaccessUtils.php | 4 ++--
src/includes/traits/Plugin/MenuPageUtils.php | 4 ++--
src/includes/traits/Plugin/WcpUtils.php | 2 +-
.../traits/Shared/ConditionalUtils.php | 2 +-
src/includes/traits/Shared/FsUtils.php | 2 +-
src/includes/traits/Shared/HookUtils.php | 2 +-
src/includes/traits/Shared/TokenUtils.php | 2 +-
9 files changed, 20 insertions(+), 20 deletions(-)
diff --git a/src/includes/traits/Ac/NcDebugUtils.php b/src/includes/traits/Ac/NcDebugUtils.php
index 75af1e50..90989084 100644
--- a/src/includes/traits/Ac/NcDebugUtils.php
+++ b/src/includes/traits/Ac/NcDebugUtils.php
@@ -8,7 +8,7 @@
*
* @type array An array of debug info; i.e. `reason_code` and `reason` (optional).
*/
-$self->debug_info = array('reason_code' => '', 'reason' => '');
+public $debug_info = ['reason_code' => '', 'reason' => ''];
/*
* Used to setup debug info (if enabled).
diff --git a/src/includes/traits/Ac/PostloadUtils.php b/src/includes/traits/Ac/PostloadUtils.php
index 5d41f88a..1485a14f 100644
--- a/src/includes/traits/Ac/PostloadUtils.php
+++ b/src/includes/traits/Ac/PostloadUtils.php
@@ -10,7 +10,7 @@
*
* @see wpMainQueryPostload()
*/
-$self->is_wp_loaded_query = false;
+public $is_wp_loaded_query = false;
/*
* Is the current request a WordPress 404 error?
@@ -21,7 +21,7 @@
*
* @see wpMainQueryPostload()
*/
-$self->is_404 = false;
+public $is_404 = false;
/*
* Last HTTP status code passed through {@link \status_header}.
@@ -32,7 +32,7 @@
*
* @see maybeFilterStatusHeaderPostload()
*/
-$self->http_status = 0;
+public $http_status = 0;
/*
* Is the current request a WordPress content type?
@@ -43,7 +43,7 @@
*
* @see wpMainQueryPostload()
*/
-$self->is_a_wp_content_type = false;
+public $is_a_wp_content_type = false;
/*
* Current WordPress {@link \content_url()}.
@@ -54,7 +54,7 @@
*
* @see wpMainQueryPostload()
*/
-$self->content_url = '';
+public $content_url = '';
/*
* Flag for {@link \is_user_loged_in()}.
@@ -65,7 +65,7 @@
*
* @see wpMainQueryPostload()
*/
-$self->is_user_logged_in = false;
+public $is_user_logged_in = false;
/*
* Flag for {@link \is_maintenance()}.
@@ -76,7 +76,7 @@
*
* @see wpMainQueryPostload()
*/
-$self->is_maintenance = false;
+public $is_maintenance = false;
/*
* Array of data targeted at the postload phase.
@@ -85,7 +85,7 @@
*
* @type array Data and/or flags that work with various postload handlers.
*/
-$self->postload = array(
+public $postload = [
/*[pro strip-from="lite"]*/
'invalidate_when_logged_in' => false,
'when_logged_in' => false,
@@ -93,7 +93,7 @@
'filter_status_header' => true,
'wp_main_query' => true,
'set_debug_info' => COMET_CACHE_DEBUGGING_ENABLE,
-);
+];
/*[pro strip-from="lite"]*/
/*
@@ -103,7 +103,7 @@
*
* @type string|int An MD5 hash token; or a specific WP user ID.
*/
-$self->user_token = '';
+public $user_token = '';
/*[/pro]*/
/*[pro strip-from="lite"]*/
diff --git a/src/includes/traits/Plugin/HtaccessUtils.php b/src/includes/traits/Plugin/HtaccessUtils.php
index 9606fccc..676135fe 100644
--- a/src/includes/traits/Plugin/HtaccessUtils.php
+++ b/src/includes/traits/Plugin/HtaccessUtils.php
@@ -8,7 +8,7 @@
*
* @return string Used in `.htaccess` parsing.
*/
-$self->htaccess_marker = 'WmVuQ2FjaGU';
+public $htaccess_marker = 'WmVuQ2FjaGU';
/*
* Plugin options that have associated htaccess rules.
@@ -19,7 +19,7 @@
*
* @note We keep track of this to avoid the issue described here: http://git.io/vEFIH
*/
-$self->options_with_htaccess_rules = array('cdn_enable');
+public $options_with_htaccess_rules = ['cdn_enable'];
/*
* Add template blocks to `/.htaccess` file.
diff --git a/src/includes/traits/Plugin/MenuPageUtils.php b/src/includes/traits/Plugin/MenuPageUtils.php
index 07bf062c..b5ab642b 100644
--- a/src/includes/traits/Plugin/MenuPageUtils.php
+++ b/src/includes/traits/Plugin/MenuPageUtils.php
@@ -203,7 +203,7 @@
* @note These must be hard-coded, because they don't become available
* in core until `admin_init`; i.e., too late for `admin_menu`.
*/
-$self->wp_admin_icon_colors = array(
+public $wp_admin_icon_colors = [
'fresh' => array('base' => '#999999', 'focus' => '#2EA2CC', 'current' => '#FFFFFF'),
'light' => array('base' => '#999999', 'focus' => '#CCCCCC', 'current' => '#CCCCCC'),
'blue' => array('base' => '#E5F8FF', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'),
@@ -212,7 +212,7 @@
'ectoplasm' => array('base' => '#ECE6F6', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'),
'ocean' => array('base' => '#F2FCFF', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'),
'coffee' => array('base' => '#F3F2F1', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'),
-);
+];
/*
* On a specific menu page?
diff --git a/src/includes/traits/Plugin/WcpUtils.php b/src/includes/traits/Plugin/WcpUtils.php
index 09991a91..035098fc 100644
--- a/src/includes/traits/Plugin/WcpUtils.php
+++ b/src/includes/traits/Plugin/WcpUtils.php
@@ -10,7 +10,7 @@
* @type array An associative array with the Post ID as the named key containing
* the post permalink before the post has been transitioned.
*/
-$self->pre_post_update_post_permalink = array();
+public $pre_post_update_post_permalink = [];
/*
* Wipes out all cache files.
diff --git a/src/includes/traits/Shared/ConditionalUtils.php b/src/includes/traits/Shared/ConditionalUtils.php
index 1892c7d4..30d28400 100644
--- a/src/includes/traits/Shared/ConditionalUtils.php
+++ b/src/includes/traits/Shared/ConditionalUtils.php
@@ -9,7 +9,7 @@
*
* @since 160222 First documented version.
*/
-$self->php_constructs = [
+public $php_constructs = [
'die' => 'die',
'echo' => 'echo',
'empty' => 'empty',
diff --git a/src/includes/traits/Shared/FsUtils.php b/src/includes/traits/Shared/FsUtils.php
index aea848f2..880013f9 100644
--- a/src/includes/traits/Shared/FsUtils.php
+++ b/src/includes/traits/Shared/FsUtils.php
@@ -320,4 +320,4 @@
*
* @var string `.htaccess` fules.
*/
-$self->htaccess_deny = "\n\tRequire all denied\n\n\n\tdeny from all\n";
+public $htaccess_deny = "\n\tRequire all denied\n\n\n\tdeny from all\n";
diff --git a/src/includes/traits/Shared/HookUtils.php b/src/includes/traits/Shared/HookUtils.php
index a004bfcf..d54cb62e 100644
--- a/src/includes/traits/Shared/HookUtils.php
+++ b/src/includes/traits/Shared/HookUtils.php
@@ -8,7 +8,7 @@
*
* @type array An array of hooks.
*/
-$self->hooks = array();
+public $hooks = [];
/*
* Assigns an ID to each callable attached to a hook/filter.
diff --git a/src/includes/traits/Shared/TokenUtils.php b/src/includes/traits/Shared/TokenUtils.php
index 51678326..46e057cd 100644
--- a/src/includes/traits/Shared/TokenUtils.php
+++ b/src/includes/traits/Shared/TokenUtils.php
@@ -9,7 +9,7 @@
*
* @type bool `TRUE` if expired or invalid.
*/
-$self->user_login_cookie_expired_or_invalid = false;
+public $user_login_cookie_expired_or_invalid = false;
/*[/pro]*/
/*
From 67591b93ceb7237ba65ad85ca3e4e97bcb2d3864 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sat, 27 Feb 2016 22:18:08 -0500
Subject: [PATCH 004/112] Convert to Traits: Change Closures to Traits
See websharks/comet-cache#635
---
src/includes/traits/Ac/AbortUtils.php | 25 +-
src/includes/traits/Ac/AcPluginUtils.php | 43 +-
src/includes/traits/Ac/BrowserUtils.php | 55 +-
src/includes/traits/Ac/HtmlCUtils.php | 127 +-
src/includes/traits/Ac/NcDebugConsts.php | 1 +
src/includes/traits/Ac/NcDebugUtils.php | 409 +++----
src/includes/traits/Ac/ObUtils.php | 640 +++++-----
src/includes/traits/Ac/PostloadUtils.php | 522 +++++----
src/includes/traits/Ac/ShutdownUtils.php | 35 +-
src/includes/traits/Plugin/ActionUtils.php | 42 +-
src/includes/traits/Plugin/AdminBarUtils.php | 635 +++++-----
src/includes/traits/Plugin/AutoCacheUtils.php | 289 ++---
src/includes/traits/Plugin/BbPressUtils.php | 107 +-
src/includes/traits/Plugin/CdnUtils.php | 32 +-
src/includes/traits/Plugin/CleanupUtils.php | 51 +-
src/includes/traits/Plugin/CondUtils.php | 23 +-
src/includes/traits/Plugin/CronUtils.php | 163 +--
src/includes/traits/Plugin/DbUtils.php | 23 +-
src/includes/traits/Plugin/DirUtils.php | 139 +--
src/includes/traits/Plugin/HtaccessUtils.php | 486 ++++----
src/includes/traits/Plugin/HtmlCUtils.php | 27 +-
src/includes/traits/Plugin/InstallUtils.php | 1035 +++++++++--------
src/includes/traits/Plugin/MenuPageUtils.php | 464 ++++----
src/includes/traits/Plugin/NoticeUtils.php | 554 ++++-----
src/includes/traits/Plugin/OptionUtils.php | 124 +-
src/includes/traits/Plugin/PostUtils.php | 72 +-
src/includes/traits/Plugin/StatsUtils.php | 75 +-
src/includes/traits/Plugin/UpdateUtils.php | 324 +++---
src/includes/traits/Plugin/UrlUtils.php | 37 +-
src/includes/traits/Plugin/UserUtils.php | 237 ++--
src/includes/traits/Plugin/WcpAuthorUtils.php | 165 +--
src/includes/traits/Plugin/WcpCdnUtils.php | 82 +-
.../traits/Plugin/WcpCommentUtils.php | 170 +--
src/includes/traits/Plugin/WcpEvalUtils.php | 81 +-
src/includes/traits/Plugin/WcpFeedUtils.php | 197 ++--
.../traits/Plugin/WcpHomeBlogUtils.php | 182 +--
src/includes/traits/Plugin/WcpHtmlCUtils.php | 148 +--
.../traits/Plugin/WcpJetpackUtils.php | 39 +-
.../traits/Plugin/WcpOpcacheUtils.php | 127 +-
src/includes/traits/Plugin/WcpPluginUtils.php | 41 +-
.../traits/Plugin/WcpPostTypeUtils.php | 123 +-
src/includes/traits/Plugin/WcpPostUtils.php | 318 ++---
.../traits/Plugin/WcpS2cleanUtils.php | 76 +-
.../traits/Plugin/WcpSettingUtils.php | 53 +-
.../traits/Plugin/WcpSitemapUtils.php | 86 +-
src/includes/traits/Plugin/WcpTermUtils.php | 243 ++--
.../traits/Plugin/WcpTransientUtils.php | 143 +--
.../traits/Plugin/WcpUpdaterUtils.php | 155 +--
src/includes/traits/Plugin/WcpUrlUtils.php | 80 +-
src/includes/traits/Plugin/WcpUserUtils.php | 226 ++--
src/includes/traits/Plugin/WcpUtils.php | 775 ++++++------
.../traits/Plugin/WcpWooCommerceUtils.php | 39 +-
src/includes/traits/Shared/BlogUtils.php | 57 +-
src/includes/traits/Shared/CacheDirUtils.php | 1031 ++++++++--------
src/includes/traits/Shared/CacheLockUtils.php | 143 +--
src/includes/traits/Shared/CachePathUtils.php | 644 +++++-----
.../traits/Shared/ConditionalUtils.php | 668 +++++------
.../traits/Shared/DomainMappingUtils.php | 485 ++++----
src/includes/traits/Shared/EscapeUtils.php | 31 +-
src/includes/traits/Shared/FsUtils.php | 596 +++++-----
src/includes/traits/Shared/HookUtils.php | 467 ++++----
src/includes/traits/Shared/HttpUtils.php | 305 ++---
src/includes/traits/Shared/I18nUtils.php | 83 +-
src/includes/traits/Shared/IpAddrUtils.php | 146 +--
src/includes/traits/Shared/PatternUtils.php | 88 +-
src/includes/traits/Shared/ReplaceUtils.php | 78 +-
src/includes/traits/Shared/ServerUtils.php | 109 +-
src/includes/traits/Shared/StringUtils.php | 150 +--
src/includes/traits/Shared/SysUtils.php | 173 +--
src/includes/traits/Shared/TokenUtils.php | 624 +++++-----
src/includes/traits/Shared/TrimUtils.php | 63 +-
src/includes/traits/Shared/UrlUtils.php | 234 ++--
72 files changed, 8481 insertions(+), 8039 deletions(-)
diff --git a/src/includes/traits/Ac/AbortUtils.php b/src/includes/traits/Ac/AbortUtils.php
index c09c597f..e25d533e 100644
--- a/src/includes/traits/Ac/AbortUtils.php
+++ b/src/includes/traits/Ac/AbortUtils.php
@@ -1,15 +1,18 @@
maybeIgnoreUserAbort = function () use ($self) {
- /*[pro strip-from="lite"]*/
- if ($self->isAutoCacheEngine()) {
- ignore_user_abort(true);
+trait AbortUtils {
+ /*
+ * Ignores user aborts; when/if the Auto-Cache Engine is running.
+ *
+ * @since 150422 Rewrite.
+ */
+ public function maybeIgnoreUserAbort()
+ {
+ /*[pro strip-from="lite"]*/
+ if ($this->isAutoCacheEngine()) {
+ ignore_user_abort(true);
+ }
+ /*[/pro]*/
}
- /*[/pro]*/
-};
+}
diff --git a/src/includes/traits/Ac/AcPluginUtils.php b/src/includes/traits/Ac/AcPluginUtils.php
index 96d0a4bd..532ba66e 100644
--- a/src/includes/traits/Ac/AcPluginUtils.php
+++ b/src/includes/traits/Ac/AcPluginUtils.php
@@ -1,25 +1,28 @@
loadAcPlugins = function () use ($self) {
- if (!is_dir(WP_CONTENT_DIR.'/ac-plugins')) {
- return; // Nothing to do here.
- }
- $GLOBALS[GLOBAL_NS.'_advanced_cache'] = $self; // Self reference.
- $GLOBALS[GLOBAL_NS.'__advanced_cache'] = &$GLOBALS[GLOBAL_NS.'_advanced_cache'];
- if (!isset($GLOBALS['zencache__advanced_cache'])) {
- $GLOBALS['zencache_advanced_cache'] = &$GLOBALS[GLOBAL_NS.'_advanced_cache'];
- $GLOBALS['zencache__advanced_cache'] = &$GLOBALS[GLOBAL_NS.'_advanced_cache'];
- }
- foreach ((array) glob(WP_CONTENT_DIR.'/ac-plugins/*.php') as $_ac_plugin) {
- if (is_file($_ac_plugin)) {
- include_once $_ac_plugin;
+trait AcPluginUtils {
+ /*
+ * Loads any advanced cache plugin files found inside `/wp-content/ac-plugins`.
+ *
+ * @since 150422 Rewrite.
+ */
+ public function loadAcPlugins()
+ {
+ if (!is_dir(WP_CONTENT_DIR.'/ac-plugins')) {
+ return; // Nothing to do here.
+ }
+ $GLOBALS[GLOBAL_NS.'_advanced_cache'] = $self; // Self reference.
+ $GLOBALS[GLOBAL_NS.'__advanced_cache'] = &$GLOBALS[GLOBAL_NS.'_advanced_cache'];
+ if (!isset($GLOBALS['zencache__advanced_cache'])) {
+ $GLOBALS['zencache_advanced_cache'] = &$GLOBALS[GLOBAL_NS.'_advanced_cache'];
+ $GLOBALS['zencache__advanced_cache'] = &$GLOBALS[GLOBAL_NS.'_advanced_cache'];
+ }
+ foreach ((array) glob(WP_CONTENT_DIR.'/ac-plugins/*.php') as $_ac_plugin) {
+ if (is_file($_ac_plugin)) {
+ include_once $_ac_plugin;
+ }
}
+ unset($_ac_plugin); // Houskeeping.
}
- unset($_ac_plugin); // Houskeeping.
-};
+}
diff --git a/src/includes/traits/Ac/BrowserUtils.php b/src/includes/traits/Ac/BrowserUtils.php
index e6281e1f..a97de2c0 100644
--- a/src/includes/traits/Ac/BrowserUtils.php
+++ b/src/includes/traits/Ac/BrowserUtils.php
@@ -1,34 +1,37 @@
maybeStopBrowserCaching = function () use ($self) {
- switch ((bool) COMET_CACHE_ALLOW_BROWSER_CACHE) {
+trait BrowserUtils {
+ /*
+ * Sends no-cache headers (if applicable).
+ *
+ * @since 150422 Rewrite. Enhanced/altered 151220.
+ */
+ public function maybeStopBrowserCaching()
+ {
+ switch ((bool) COMET_CACHE_ALLOW_BROWSER_CACHE) {
- case true: // If global config allows, check exclusions.
+ case true: // If global config allows, check exclusions.
- if (isset($_GET[strtolower(SHORT_NAME).'ABC'])) {
- if (!filter_var($_GET[strtolower(SHORT_NAME).'ABC'], FILTER_VALIDATE_BOOLEAN)) {
- return $self->sendNoCacheHeaders(); // Disallow.
- } // Else, allow client-side caching; because `ABC` is a true-ish value.
- // ↑ Note that exclusion patterns are ignored in this case, in favor of `ABC`.
- } elseif (COMET_CACHE_EXCLUDE_CLIENT_SIDE_URIS && preg_match(COMET_CACHE_EXCLUDE_CLIENT_SIDE_URIS, $_SERVER['REQUEST_URI'])) {
- return $self->sendNoCacheHeaders(); // Disallow.
- }
- return; // Allow browser caching; default behavior in this mode.
+ if (isset($_GET[strtolower(SHORT_NAME).'ABC'])) {
+ if (!filter_var($_GET[strtolower(SHORT_NAME).'ABC'], FILTER_VALIDATE_BOOLEAN)) {
+ return $this->sendNoCacheHeaders(); // Disallow.
+ } // Else, allow client-side caching; because `ABC` is a true-ish value.
+ // ↑ Note that exclusion patterns are ignored in this case, in favor of `ABC`.
+ } elseif (COMET_CACHE_EXCLUDE_CLIENT_SIDE_URIS && preg_match(COMET_CACHE_EXCLUDE_CLIENT_SIDE_URIS, $_SERVER['REQUEST_URI'])) {
+ return $this->sendNoCacheHeaders(); // Disallow.
+ }
+ return; // Allow browser caching; default behavior in this mode.
- case false: // Global config disallows; check inclusions.
+ case false: // Global config disallows; check inclusions.
- if (isset($_GET[strtolower(SHORT_NAME).'ABC'])) {
- if (filter_var($_GET[strtolower(SHORT_NAME).'ABC'], FILTER_VALIDATE_BOOLEAN)) {
- return; // Allow, because `ABC` is a false-ish value.
- } // Else, disallow client-side caching; because `ABC` is a true-ish value.
- // ↑ Note that inclusion patterns are ignored in this case, in favor of `ABC`.
- }
- return $self->sendNoCacheHeaders(); // Disallow; default behavior in this mode.
+ if (isset($_GET[strtolower(SHORT_NAME).'ABC'])) {
+ if (filter_var($_GET[strtolower(SHORT_NAME).'ABC'], FILTER_VALIDATE_BOOLEAN)) {
+ return; // Allow, because `ABC` is a false-ish value.
+ } // Else, disallow client-side caching; because `ABC` is a true-ish value.
+ // ↑ Note that inclusion patterns are ignored in this case, in favor of `ABC`.
+ }
+ return $this->sendNoCacheHeaders(); // Disallow; default behavior in this mode.
+ }
}
-};
+}
diff --git a/src/includes/traits/Ac/HtmlCUtils.php b/src/includes/traits/Ac/HtmlCUtils.php
index 54f406e9..81a69e1e 100644
--- a/src/includes/traits/Ac/HtmlCUtils.php
+++ b/src/includes/traits/Ac/HtmlCUtils.php
@@ -2,77 +2,80 @@
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Traits\Ac;
-/*
- * Runs HTML Compressor (if applicable).
- *
- * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
- *
- * @param string $cache Input cache file we want to compress.
- *
- * @return string The `$cache` with HTML compression applied (if applicable).
- *
- * @see https://github.com/websharks/html-compressor
- */
-$self->maybeCompressHtml = function ($cache) use ($self) {
- if (!$self->content_url) {
- return $cache; // Not possible.
- }
- if (!COMET_CACHE_HTMLC_ENABLE) {
- return $cache; // Nothing to do here.
- }
- if ($self->is_user_logged_in && !COMET_CACHE_HTMLC_WHEN_LOGGED_IN) {
- return $cache; // Nothing to do here.
- }
- // Deals with multisite base & sub-directory installs.
- // e.g. `htmlc/cache/public/www-example-com` (standard WP installation).
- // e.g. `htmlc/cache/public/[[/base]/child1]/www-example-com` (multisite network).
- // Note that `www-example-com` (current host slug) is appended by the HTML compressor.
+trait HtmlCUtils {
+ /*
+ * Runs HTML Compressor (if applicable).
+ *
+ * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
+ *
+ * @param string $cache Input cache file we want to compress.
+ *
+ * @return string The `$cache` with HTML compression applied (if applicable).
+ *
+ * @see https://github.com/websharks/html-compressor
+ */
+ public function maybeCompressHtml($cache)
+ {
+ if (!$this->content_url) {
+ return $cache; // Not possible.
+ }
+ if (!COMET_CACHE_HTMLC_ENABLE) {
+ return $cache; // Nothing to do here.
+ }
+ if ($this->is_user_logged_in && !COMET_CACHE_HTMLC_WHEN_LOGGED_IN) {
+ return $cache; // Nothing to do here.
+ }
+ // Deals with multisite base & sub-directory installs.
+ // e.g. `htmlc/cache/public/www-example-com` (standard WP installation).
+ // e.g. `htmlc/cache/public/[[/base]/child1]/www-example-com` (multisite network).
+ // Note that `www-example-com` (current host slug) is appended by the HTML compressor.
- $host_base_dir_tokens = $self->hostBaseDirTokens(true); // Dashify this.
+ $host_base_dir_tokens = $this->hostBaseDirTokens(true); // Dashify this.
- $cache_dir_public = COMET_CACHE_HTMLC_CACHE_DIR_PUBLIC.rtrim($host_base_dir_tokens, '/');
- $cache_dir_url_public = $self->content_url.str_replace(WP_CONTENT_DIR, '', $cache_dir_public);
+ $cache_dir_public = COMET_CACHE_HTMLC_CACHE_DIR_PUBLIC.rtrim($host_base_dir_tokens, '/');
+ $cache_dir_url_public = $this->content_url.str_replace(WP_CONTENT_DIR, '', $cache_dir_public);
- $cache_dir_private = COMET_CACHE_HTMLC_CACHE_DIR_PRIVATE.rtrim($host_base_dir_tokens, '/');
- $cache_dir_url_private = $self->content_url.str_replace(WP_CONTENT_DIR, '', $cache_dir_private);
+ $cache_dir_private = COMET_CACHE_HTMLC_CACHE_DIR_PRIVATE.rtrim($host_base_dir_tokens, '/');
+ $cache_dir_url_private = $this->content_url.str_replace(WP_CONTENT_DIR, '', $cache_dir_private);
- $benchmark = COMET_CACHE_DEBUGGING_ENABLE >= 2 ? 'details' : COMET_CACHE_DEBUGGING_ENABLE;
- $product_title = sprintf(__('%1$s HTML Compressor', SLUG_TD), NAME);
+ $benchmark = COMET_CACHE_DEBUGGING_ENABLE >= 2 ? 'details' : COMET_CACHE_DEBUGGING_ENABLE;
+ $product_title = sprintf(__('%1$s HTML Compressor', SLUG_TD), NAME);
- $html_compressor_options = array(
- 'benchmark' => $benchmark,
- 'product_title' => $product_title,
+ $html_compressor_options = [
+ 'benchmark' => $benchmark,
+ 'product_title' => $product_title,
- 'cache_dir_public' => $cache_dir_public,
- 'cache_dir_url_public' => $cache_dir_url_public,
+ 'cache_dir_public' => $cache_dir_public,
+ 'cache_dir_url_public' => $cache_dir_url_public,
- 'cache_dir_private' => $cache_dir_private,
- 'cache_dir_url_private' => $cache_dir_url_private,
+ 'cache_dir_private' => $cache_dir_private,
+ 'cache_dir_url_private' => $cache_dir_url_private,
- 'regex_css_exclusions' => COMET_CACHE_HTMLC_CSS_EXCLUSIONS,
- 'regex_js_exclusions' => COMET_CACHE_HTMLC_JS_EXCLUSIONS,
- 'regex_uri_exclusions' => COMET_CACHE_HTMLC_URI_EXCLUSIONS,
+ 'regex_css_exclusions' => COMET_CACHE_HTMLC_CSS_EXCLUSIONS,
+ 'regex_js_exclusions' => COMET_CACHE_HTMLC_JS_EXCLUSIONS,
+ 'regex_uri_exclusions' => COMET_CACHE_HTMLC_URI_EXCLUSIONS,
- 'cache_expiration_time' => COMET_CACHE_HTMLC_CACHE_EXPIRATION_TIME,
+ 'cache_expiration_time' => COMET_CACHE_HTMLC_CACHE_EXPIRATION_TIME,
- 'compress_combine_head_body_css' => COMET_CACHE_HTMLC_COMPRESS_COMBINE_HEAD_BODY_CSS,
- 'compress_combine_head_js' => COMET_CACHE_HTMLC_COMPRESS_COMBINE_HEAD_JS,
- 'compress_combine_footer_js' => COMET_CACHE_HTMLC_COMPRESS_COMBINE_FOOTER_JS,
- 'compress_combine_remote_css_js' => COMET_CACHE_HTMLC_COMPRESS_COMBINE_REMOTE_CSS_JS,
- 'compress_inline_js_code' => COMET_CACHE_HTMLC_COMPRESS_INLINE_JS_CODE,
- 'compress_css_code' => COMET_CACHE_HTMLC_COMPRESS_CSS_CODE,
- 'compress_js_code' => COMET_CACHE_HTMLC_COMPRESS_JS_CODE,
- 'compress_html_code' => COMET_CACHE_HTMLC_COMPRESS_HTML_CODE,
- );
- try {
- $html_compressor = new \WebSharks\HtmlCompressor\Core($html_compressor_options);
- $compressed_cache = $html_compressor->compress($cache);
- } catch (\Exception $exception) {
- $compressed_cache = $cache; // Fail softly.
- if (COMET_CACHE_DEBUGGING_ENABLE >= 2) { // Leave a note in the source code?
- $compressed_cache .= "\n".'';
+ 'compress_combine_head_body_css' => COMET_CACHE_HTMLC_COMPRESS_COMBINE_HEAD_BODY_CSS,
+ 'compress_combine_head_js' => COMET_CACHE_HTMLC_COMPRESS_COMBINE_HEAD_JS,
+ 'compress_combine_footer_js' => COMET_CACHE_HTMLC_COMPRESS_COMBINE_FOOTER_JS,
+ 'compress_combine_remote_css_js' => COMET_CACHE_HTMLC_COMPRESS_COMBINE_REMOTE_CSS_JS,
+ 'compress_inline_js_code' => COMET_CACHE_HTMLC_COMPRESS_INLINE_JS_CODE,
+ 'compress_css_code' => COMET_CACHE_HTMLC_COMPRESS_CSS_CODE,
+ 'compress_js_code' => COMET_CACHE_HTMLC_COMPRESS_JS_CODE,
+ 'compress_html_code' => COMET_CACHE_HTMLC_COMPRESS_HTML_CODE,
+ ];
+ try {
+ $html_compressor = new \WebSharks\HtmlCompressor\Core($html_compressor_options);
+ $compressed_cache = $html_compressor->compress($cache);
+ } catch (\Exception $exception) {
+ $compressed_cache = $cache; // Fail softly.
+ if (COMET_CACHE_DEBUGGING_ENABLE >= 2) { // Leave a note in the source code?
+ $compressed_cache .= "\n".'';
+ }
}
+ return $compressed_cache;
}
- return $compressed_cache;
-};
-/*[/pro]*/
+ /*[/pro]*/
+}
diff --git a/src/includes/traits/Ac/NcDebugConsts.php b/src/includes/traits/Ac/NcDebugConsts.php
index 264025bb..69af3213 100644
--- a/src/includes/traits/Ac/NcDebugConsts.php
+++ b/src/includes/traits/Ac/NcDebugConsts.php
@@ -4,6 +4,7 @@
if (defined(__NAMESPACE__.'\\NC_DEBUG_PHP_SAPI_CLI')) {
return; // Already defined these.
}
+
/**
* No-cache because of the current {@link \PHP_SAPI}.
*
diff --git a/src/includes/traits/Ac/NcDebugUtils.php b/src/includes/traits/Ac/NcDebugUtils.php
index 90989084..c52614a2 100644
--- a/src/includes/traits/Ac/NcDebugUtils.php
+++ b/src/includes/traits/Ac/NcDebugUtils.php
@@ -1,209 +1,214 @@
'', 'reason' => ''];
-
-/*
- * Used to setup debug info (if enabled).
- *
- * @since 150422 Rewrite.
- *
- * @param string $reason_code One of the `NC_DEBUG_` constants.
- * @param string $reason Optionally override the built-in description with a custom message.
- */
-$self->maybeSetDebugInfo = function ($reason_code, $reason = '') use ($self) {
- if (!COMET_CACHE_DEBUGGING_ENABLE) {
- return; // Nothing to do.
- }
- $reason = (string) $reason;
- if (!($reason_code = (string) $reason_code)) {
- return; // Not applicable.
- }
- $self->debug_info = array('reason_code' => $reason_code, 'reason' => $reason);
-};
-
-/*
- * Echoes `NC_DEBUG_` info in the WordPress `shutdown` phase (if applicable).
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `shutdown` hook in WordPress w/ a late priority.
- */
-$self->maybeEchoNcDebugInfo = function () use ($self) {
- if (!COMET_CACHE_DEBUGGING_ENABLE) {
- return; // Nothing to do.
- }
- if (is_admin()) {
- return; // Not applicable.
- }
- if (strcasecmp(PHP_SAPI, 'cli') === 0) {
- return; // Let's not run the risk here.
- }
- if ($self->debug_info && $self->hasACacheableContentType() && $self->is_a_wp_content_type) {
- echo (string) $self->maybeGetNcDebugInfo($self->debug_info['reason_code'], $self->debug_info['reason']);
- }
-};
-
-/*
- * Gets `NC_DEBUG_` info (if applicable).
- *
- * @since 150422 Rewrite.
- *
- * @param string $reason_code One of the `NC_DEBUG_` constants.
- * @param string $reason Optional; to override the default description with a custom message.
- *
- * @return string The debug info; i.e. full description (if applicable).
- */
-$self->maybeGetNcDebugInfo = function ($reason_code = '', $reason = '') use ($self) {
- if (!COMET_CACHE_DEBUGGING_ENABLE) {
- return ''; // Not applicable.
+trait NcDebugUtils {
+ /*
+ * An array of debug info.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @type array An array of debug info; i.e. `reason_code` and `reason` (optional).
+ */
+ public $debug_info = ['reason_code' => '', 'reason' => ''];
+
+ /*
+ * Used to setup debug info (if enabled).
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $reason_code One of the `NC_DEBUG_` constants.
+ * @param string $reason Optionally override the built-in description with a custom message.
+ */
+ public function maybeSetDebugInfo($reason_code, $reason = '')
+ {
+ if (!COMET_CACHE_DEBUGGING_ENABLE) {
+ return; // Nothing to do.
+ }
+ $reason = (string) $reason;
+ if (!($reason_code = (string) $reason_code)) {
+ return; // Not applicable.
+ }
+ $this->debug_info = ['reason_code' => $reason_code, 'reason' => $reason];
}
- $reason = (string) $reason;
- if (!($reason_code = (string) $reason_code)) {
- return ''; // Not applicable.
+
+ /*
+ * Echoes `NC_DEBUG_` info in the WordPress `shutdown` phase (if applicable).
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `shutdown` hook in WordPress w/ a late priority.
+ */
+ public function maybeEchoNcDebugInfo()
+ {
+ if (!COMET_CACHE_DEBUGGING_ENABLE) {
+ return; // Nothing to do.
+ }
+ if (is_admin()) {
+ return; // Not applicable.
+ }
+ if (strcasecmp(PHP_SAPI, 'cli') === 0) {
+ return; // Let's not run the risk here.
+ }
+ if ($this->debug_info && $this->hasACacheableContentType() && $this->is_a_wp_content_type) {
+ echo (string) $this->maybeGetNcDebugInfo($this->debug_info['reason_code'], $this->debug_info['reason']);
+ }
}
- if (!$reason) {
- switch ($reason_code) {
- case NC_DEBUG_PHP_SAPI_CLI:
- $reason = __('because `PHP_SAPI` reports that you are currently running from the command line.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_NO_SERVER_HTTP_HOST:
- $reason = __('because `$_SERVER[\'HTTP_HOST\']` is missing from your server configuration.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_NO_SERVER_REQUEST_URI:
- $reason = __('because `$_SERVER[\'REQUEST_URI\']` is missing from your server configuration.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_COMET_CACHE_ALLOWED_CONSTANT:
- if ($self->functionIsPossible('did_action') && did_action('ws_plugin__s2member_during_no_cache_constants')) {
- $reason = __('because the s2Member plugin set the PHP constant `COMET_CACHE_ALLOWED` to a boolean-ish `FALSE` value at runtime. The s2Member plugin is serving content that must remain dynamic on this particular page, and therefore this page was intentionally not cached for a very good reason.', SLUG_TD);
- } else {
- $reason = __('because the PHP constant `COMET_CACHE_ALLOWED` has been set to a boolean-ish `FALSE` value at runtime. Perhaps by WordPress itself, or by one of your themes/plugins. This usually means that you have a theme/plugin intentionally disabling the cache on this page; and it\'s usually for a very good reason.', SLUG_TD);
- }
- break; // Break switch handler.
-
- case NC_DEBUG_COMET_CACHE_ALLOWED_SERVER_VAR:
- $reason = __('because the environment variable `$_SERVER[\'COMET_CACHE_ALLOWED\']` has been set to a boolean-ish `FALSE` value at runtime. Perhaps by WordPress itself, or by one of your themes/plugins. This usually means that you have a theme/plugin intentionally disabling the cache on this page; and it\'s usually for a very good reason.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_DONOTCACHEPAGE_CONSTANT:
- $reason = __('because the PHP constant `DONOTCACHEPAGE` has been set at runtime. Perhaps by WordPress itself, or by one of your themes/plugins. This usually means that you have a theme/plugin intentionally disabling the cache on this page; and it\'s usually for a very good reason.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_DONOTCACHEPAGE_SERVER_VAR:
- $reason = __('because the environment variable `$_SERVER[\'DONOTCACHEPAGE\']` has been set at runtime. Perhaps by WordPress itself, or by one of your themes/plugins. This usually means that you have a theme/plugin intentionally disabling the cache on this page; and it\'s usually for a very good reason.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_AC_GET_VAR:
- $reason = sprintf(__('because `$_GET[\'%1$sAC\']` is set to a boolean-ish FALSE value.', SLUG_TD), strtolower(SHORT_NAME));
- break; // Break switch handler.
-
- case NC_DEBUG_UNCACHEABLE_REQUEST:
- $reason = __('because `$_SERVER[\'REQUEST_METHOD\']` is `POST`, `PUT`, `DELETE`, `HEAD`, `OPTIONS`, `TRACE` or `CONNECT`. These request methods should never (ever) be cached in any way.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_SELF_SERVE_REQUEST:
- $reason = __('because `[current IP address]` === `$_SERVER[\'SERVER_ADDR\']`; i.e. a self-serve request. DEVELOPER TIP: if you are testing on a localhost installation, please add `define(\'LOCALHOST\', TRUE);` to your `/wp-config.php` file while you run tests :-) Remove it (or set it to a `FALSE` value) once you go live on the web.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_FEED_REQUEST:
- $reason = __('because `$_SERVER[\'REQUEST_URI\']` indicates this is a `/feed`; and the configuration of this site says not to cache XML-based feeds.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_WP_SYSTEMATICS:
- $reason = __('because `$_SERVER[\'REQUEST_URI\']` indicates this is a `wp-` or `xmlrpc` file; i.e. a WordPress systematic file. WordPress systematics are never (ever) cached in any way.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_WP_ADMIN:
- $reason = __('because `$_SERVER[\'REQUEST_URI\']` or the `is_admin()` function indicates this is an administrative area of the site.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_MS_FILES:
- $reason = __('because `$_SERVER[\'REQUEST_URI\']` indicates this is a Multisite Network; and this was a request for `/files/*`, not a page.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_IS_LOGGED_IN_USER:
- case NC_DEBUG_IS_LIKE_LOGGED_IN_USER:
- $reason = __('because the current user visiting this page (usually YOU), appears to be logged-in. The current configuration says NOT to cache pages for logged-in visitors. This message may also appear if you have an active PHP session on this site, or if you\'ve left (or replied to) a comment recently. If this message continues, please clear your cookies and try again.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_IS_LOGGED_IN_USER_NONCE:
- $reason = __('because the current page contains `_wpnonce` or `akismet_comment_nonce`. While your current configuration states that pages SHOULD be cache for logged-in visitors, `*nonce*` values in the markup are not cache-compatible. See http://wsharks.com/1O1Kudy for further details.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_PAGE_CONTAINS_NONCE:
- $reason = __('because the current page contains `_wpnonce` or `akismet_comment_nonce`. Note that `*nonce*` values in the markup are not cache-compatible. See http://wsharks.com/1O1Kudy for further details.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_NO_USER_TOKEN:
- $reason = sprintf(__('because the current user appeared to be logged into the site (in one way or another); but %1$s was unable to formulate a User Token for them. Please report this as a possible bug.', SLUG_TD), NAME);
- break; // Break switch handler.
-
- case NC_DEBUG_GET_REQUEST_QUERIES:
- $reason = __('because `$_GET` contains query string data. The current configuration says NOT to cache GET requests with a query string.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_PREVIEW:
- $reason = __('because `$_REQUEST` indicates this is simply a preview of something to come.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_EXCLUDED_URIS:
- $reason = __('because `$_SERVER[\'REQUEST_URI\']` matches a configured URI Exclusion Pattern on this installation.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_EXCLUDED_AGENTS:
- $reason = __('because `$_SERVER[\'HTTP_USER_AGENT\']` matches a configured User-Agent Exclusion Pattern on this installation.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_EXCLUDED_REFS:
- $reason = __('because `$_SERVER[\'HTTP_REFERER\']` and/or `$_GET[\'_wp_http_referer\']` matches a configured HTTP Referrer Exclusion Pattern on this installation.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_404_REQUEST:
- $reason = __('because the WordPress `is_404()` Conditional Tag says the current page is a 404 error. The current configuration says NOT to cache 404 errors.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_MAINTENANCE_PLUGIN:
- $reason = __('because a plugin running on this installation says this page is in Maintenance Mode; i.e. is not available publicly at this time.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_OB_ZLIB_CODING_TYPE:
- $reason = sprintf(__('because %1$s is unable to cache already-compressed output. Please use `mod_deflate` w/ Apache; or use `zlib.output_compression` in your `php.ini` file. %1$s is NOT compatible with `ob_gzhandler()` and others like this.', SLUG_TD), NAME);
- break; // Break switch handler.
-
- case NC_DEBUG_WP_ERROR_PAGE:
- $reason = __('because the contents of this document contain ``, which indicates this is an auto-generated WordPress error message.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_UNCACHEABLE_CONTENT_TYPE:
- $reason = __('because a `Content-Type:` header was set via PHP at runtime. The header contains a MIME type which is NOT a variation of HTML or XML. This header might have been set by your hosting company, by WordPress itself; or by one of your themes/plugins.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_UNCACHEABLE_STATUS:
- $reason = __('because a `Status:` header (or an `HTTP/` header) was set via PHP at runtime. The header contains a non-`2xx` status code. This indicates the current page was not loaded successfully. This header might have been set by your hosting company, by WordPress itself; or by one of your themes/plugins.', SLUG_TD);
- break; // Break switch handler.
-
- case NC_DEBUG_1ST_TIME_404_SYMLINK:
- $reason = sprintf(__('because the WordPress `is_404()` Conditional Tag says the current page is a 404 error; and this is the first time it\'s happened on this page. Your current configuration says that 404 errors SHOULD be cached, so %1$s built a cached symlink which points future requests for this location to your already-cached 404 error document. If you reload this page (assuming you don\'t clear the cache before you do so); you should get a cached version of your 404 error document. This message occurs ONCE for each new/unique 404 error request.', SLUG_TD), NAME);
- break; // Break switch handler.
-
- case NC_DEBUG_EARLY_BUFFER_TERMINATION:
- $reason = sprintf(__('because %1$s detected an early output buffer termination. This may happen when a theme/plugin ends, cleans, or flushes all output buffers before reaching the PHP shutdown phase. It\'s not always a bad thing. Sometimes it is necessary for a theme/plugin to do this. However, in this scenario it is NOT possible to cache the output; since %1$s is effectively disabled at runtime when this occurs.', SLUG_TD), NAME);
- break; // Break switch handler.
-
- default: // Default case handler.
- $reason = __('due to an unexpected behavior in the application. Please report this as a bug!', SLUG_TD);
- break; // Break switch handler.
+
+ /*
+ * Gets `NC_DEBUG_` info (if applicable).
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $reason_code One of the `NC_DEBUG_` constants.
+ * @param string $reason Optional; to override the default description with a custom message.
+ *
+ * @return string The debug info; i.e. full description (if applicable).
+ */
+ public function maybeGetNcDebugInfo($reason_code = '', $reason = '')
+ {
+ if (!COMET_CACHE_DEBUGGING_ENABLE) {
+ return ''; // Not applicable.
+ }
+ $reason = (string) $reason;
+ if (!($reason_code = (string) $reason_code)) {
+ return ''; // Not applicable.
+ }
+ if (!$reason) {
+ switch ($reason_code) {
+ case NC_DEBUG_PHP_SAPI_CLI:
+ $reason = __('because `PHP_SAPI` reports that you are currently running from the command line.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_NO_SERVER_HTTP_HOST:
+ $reason = __('because `$_SERVER[\'HTTP_HOST\']` is missing from your server configuration.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_NO_SERVER_REQUEST_URI:
+ $reason = __('because `$_SERVER[\'REQUEST_URI\']` is missing from your server configuration.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_COMET_CACHE_ALLOWED_CONSTANT:
+ if ($this->functionIsPossible('did_action') && did_action('ws_plugin__s2member_during_no_cache_constants')) {
+ $reason = __('because the s2Member plugin set the PHP constant `COMET_CACHE_ALLOWED` to a boolean-ish `FALSE` value at runtime. The s2Member plugin is serving content that must remain dynamic on this particular page, and therefore this page was intentionally not cached for a very good reason.', SLUG_TD);
+ } else {
+ $reason = __('because the PHP constant `COMET_CACHE_ALLOWED` has been set to a boolean-ish `FALSE` value at runtime. Perhaps by WordPress itself, or by one of your themes/plugins. This usually means that you have a theme/plugin intentionally disabling the cache on this page; and it\'s usually for a very good reason.', SLUG_TD);
+ }
+ break; // Break switch handler.
+
+ case NC_DEBUG_COMET_CACHE_ALLOWED_SERVER_VAR:
+ $reason = __('because the environment variable `$_SERVER[\'COMET_CACHE_ALLOWED\']` has been set to a boolean-ish `FALSE` value at runtime. Perhaps by WordPress itself, or by one of your themes/plugins. This usually means that you have a theme/plugin intentionally disabling the cache on this page; and it\'s usually for a very good reason.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_DONOTCACHEPAGE_CONSTANT:
+ $reason = __('because the PHP constant `DONOTCACHEPAGE` has been set at runtime. Perhaps by WordPress itself, or by one of your themes/plugins. This usually means that you have a theme/plugin intentionally disabling the cache on this page; and it\'s usually for a very good reason.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_DONOTCACHEPAGE_SERVER_VAR:
+ $reason = __('because the environment variable `$_SERVER[\'DONOTCACHEPAGE\']` has been set at runtime. Perhaps by WordPress itself, or by one of your themes/plugins. This usually means that you have a theme/plugin intentionally disabling the cache on this page; and it\'s usually for a very good reason.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_AC_GET_VAR:
+ $reason = sprintf(__('because `$_GET[\'%1$sAC\']` is set to a boolean-ish FALSE value.', SLUG_TD), strtolower(SHORT_NAME));
+ break; // Break switch handler.
+
+ case NC_DEBUG_UNCACHEABLE_REQUEST:
+ $reason = __('because `$_SERVER[\'REQUEST_METHOD\']` is `POST`, `PUT`, `DELETE`, `HEAD`, `OPTIONS`, `TRACE` or `CONNECT`. These request methods should never (ever) be cached in any way.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_SELF_SERVE_REQUEST:
+ $reason = __('because `[current IP address]` === `$_SERVER[\'SERVER_ADDR\']`; i.e. a self-serve request. DEVELOPER TIP: if you are testing on a localhost installation, please add `define(\'LOCALHOST\', TRUE);` to your `/wp-config.php` file while you run tests :-) Remove it (or set it to a `FALSE` value) once you go live on the web.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_FEED_REQUEST:
+ $reason = __('because `$_SERVER[\'REQUEST_URI\']` indicates this is a `/feed`; and the configuration of this site says not to cache XML-based feeds.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_WP_SYSTEMATICS:
+ $reason = __('because `$_SERVER[\'REQUEST_URI\']` indicates this is a `wp-` or `xmlrpc` file; i.e. a WordPress systematic file. WordPress systematics are never (ever) cached in any way.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_WP_ADMIN:
+ $reason = __('because `$_SERVER[\'REQUEST_URI\']` or the `is_admin()` function indicates this is an administrative area of the site.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_MS_FILES:
+ $reason = __('because `$_SERVER[\'REQUEST_URI\']` indicates this is a Multisite Network; and this was a request for `/files/*`, not a page.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_IS_LOGGED_IN_USER:
+ case NC_DEBUG_IS_LIKE_LOGGED_IN_USER:
+ $reason = __('because the current user visiting this page (usually YOU), appears to be logged-in. The current configuration says NOT to cache pages for logged-in visitors. This message may also appear if you have an active PHP session on this site, or if you\'ve left (or replied to) a comment recently. If this message continues, please clear your cookies and try again.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_IS_LOGGED_IN_USER_NONCE:
+ $reason = __('because the current page contains `_wpnonce` or `akismet_comment_nonce`. While your current configuration states that pages SHOULD be cache for logged-in visitors, `*nonce*` values in the markup are not cache-compatible. See http://wsharks.com/1O1Kudy for further details.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_PAGE_CONTAINS_NONCE:
+ $reason = __('because the current page contains `_wpnonce` or `akismet_comment_nonce`. Note that `*nonce*` values in the markup are not cache-compatible. See http://wsharks.com/1O1Kudy for further details.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_NO_USER_TOKEN:
+ $reason = sprintf(__('because the current user appeared to be logged into the site (in one way or another); but %1$s was unable to formulate a User Token for them. Please report this as a possible bug.', SLUG_TD), NAME);
+ break; // Break switch handler.
+
+ case NC_DEBUG_GET_REQUEST_QUERIES:
+ $reason = __('because `$_GET` contains query string data. The current configuration says NOT to cache GET requests with a query string.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_PREVIEW:
+ $reason = __('because `$_REQUEST` indicates this is simply a preview of something to come.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_EXCLUDED_URIS:
+ $reason = __('because `$_SERVER[\'REQUEST_URI\']` matches a configured URI Exclusion Pattern on this installation.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_EXCLUDED_AGENTS:
+ $reason = __('because `$_SERVER[\'HTTP_USER_AGENT\']` matches a configured User-Agent Exclusion Pattern on this installation.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_EXCLUDED_REFS:
+ $reason = __('because `$_SERVER[\'HTTP_REFERER\']` and/or `$_GET[\'_wp_http_referer\']` matches a configured HTTP Referrer Exclusion Pattern on this installation.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_404_REQUEST:
+ $reason = __('because the WordPress `is_404()` Conditional Tag says the current page is a 404 error. The current configuration says NOT to cache 404 errors.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_MAINTENANCE_PLUGIN:
+ $reason = __('because a plugin running on this installation says this page is in Maintenance Mode; i.e. is not available publicly at this time.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_OB_ZLIB_CODING_TYPE:
+ $reason = sprintf(__('because %1$s is unable to cache already-compressed output. Please use `mod_deflate` w/ Apache; or use `zlib.output_compression` in your `php.ini` file. %1$s is NOT compatible with `ob_gzhandler()` and others like this.', SLUG_TD), NAME);
+ break; // Break switch handler.
+
+ case NC_DEBUG_WP_ERROR_PAGE:
+ $reason = __('because the contents of this document contain ``, which indicates this is an auto-generated WordPress error message.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_UNCACHEABLE_CONTENT_TYPE:
+ $reason = __('because a `Content-Type:` header was set via PHP at runtime. The header contains a MIME type which is NOT a variation of HTML or XML. This header might have been set by your hosting company, by WordPress itself; or by one of your themes/plugins.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_UNCACHEABLE_STATUS:
+ $reason = __('because a `Status:` header (or an `HTTP/` header) was set via PHP at runtime. The header contains a non-`2xx` status code. This indicates the current page was not loaded successfully. This header might have been set by your hosting company, by WordPress itself; or by one of your themes/plugins.', SLUG_TD);
+ break; // Break switch handler.
+
+ case NC_DEBUG_1ST_TIME_404_SYMLINK:
+ $reason = sprintf(__('because the WordPress `is_404()` Conditional Tag says the current page is a 404 error; and this is the first time it\'s happened on this page. Your current configuration says that 404 errors SHOULD be cached, so %1$s built a cached symlink which points future requests for this location to your already-cached 404 error document. If you reload this page (assuming you don\'t clear the cache before you do so); you should get a cached version of your 404 error document. This message occurs ONCE for each new/unique 404 error request.', SLUG_TD), NAME);
+ break; // Break switch handler.
+
+ case NC_DEBUG_EARLY_BUFFER_TERMINATION:
+ $reason = sprintf(__('because %1$s detected an early output buffer termination. This may happen when a theme/plugin ends, cleans, or flushes all output buffers before reaching the PHP shutdown phase. It\'s not always a bad thing. Sometimes it is necessary for a theme/plugin to do this. However, in this scenario it is NOT possible to cache the output; since %1$s is effectively disabled at runtime when this occurs.', SLUG_TD), NAME);
+ break; // Break switch handler.
+
+ default: // Default case handler.
+ $reason = __('due to an unexpected behavior in the application. Please report this as a bug!', SLUG_TD);
+ break; // Break switch handler.
+ }
}
+ return "\n".'';
}
- return "\n".'';
-};
+}
diff --git a/src/includes/traits/Ac/ObUtils.php b/src/includes/traits/Ac/ObUtils.php
index ee023c07..7c5c92ab 100644
--- a/src/includes/traits/Ac/ObUtils.php
+++ b/src/includes/traits/Ac/ObUtils.php
@@ -1,361 +1,367 @@
protocol = '';
+trait ObUtils {
-/*
- * Host token for this request.
- *
- * @since 150821 Improving multisite compat.
- *
- * @type string Host token for this request.
- */
-$self->host_token = '';
+ /*
+ * Calculated protocol; one of `http://` or `https://`.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @type float One of `http://` or `https://`.
+ */
+ public $rotocol = '';
-/*
- * Host base/dir tokens for this request.
- *
- * @since 150821 Improving multisite compat.
- *
- * @type string Host base/dir tokens for this request.
- */
-$self->host_base_dir_tokens = '';
+ /*
+ * Host token for this request.
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @type string Host token for this request.
+ */
+ public $host_token = '';
-/*
- * Calculated version salt; set by site configuration data.
- *
- * @since 150422 Rewrite.
- *
- * @type string|mixed Any scalar value does fine.
- */
-$self->version_salt = '';
+ /*
+ * Host base/dir tokens for this request.
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @type string Host base/dir tokens for this request.
+ */
+ public $host_base_dir_tokens = '';
-/*
- * Relative cache path for the current request.
- *
- * @since 150422 Rewrite.
- *
- * @type string Cache path for the current request.
- */
-$self->cache_path = '';
+ /*
+ * Calculated version salt; set by site configuration data.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @type string|mixed Any scalar value does fine.
+ */
+ public $version_salt = '';
-/*
- * Absolute cache file path for the current request.
- *
- * @since 150422 Rewrite.
- *
- * @type string Absolute cache file path for the current request.
- */
-$self->cache_file = '';
+ /*
+ * Relative cache path for the current request.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @type string Cache path for the current request.
+ */
+ public $cache_path = '';
-/*
- * Relative 404 cache path for the current request.
- *
- * @since 150422 Rewrite.
- *
- * @type string 404 cache path for the current request.
- */
-$self->cache_path_404 = '';
+ /*
+ * Absolute cache file path for the current request.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @type string Absolute cache file path for the current request.
+ */
+ public $cache_file = '';
-/*
- * Absolute 404 cache file path for the current request.
- *
- * @since 150422 Rewrite.
- *
- * @type string Absolute 404 cache file path for the current request.
- */
-$self->cache_file_404 = '';
+ /*
+ * Relative 404 cache path for the current request.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @type string 404 cache path for the current request.
+ */
+ public $cache_path_404 = '';
-/*
- * Version salt followed by the current request location.
- *
- * @since 150422 Rewrite.
- *
- * @type string Version salt followed by the current request location.
- */
-$self->salt_location = '';
+ /*
+ * Absolute 404 cache file path for the current request.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @type string Absolute 404 cache file path for the current request.
+ */
+ public $cache_file_404 = '';
-/*
- * Calculated max age; i.e., before expiration.
- *
- * @since 151002 Load average checks in pro version.
- *
- * @type integer Calculated max age; i.e., before expiration.
- */
-$self->cache_max_age = 0;
+ /*
+ * Version salt followed by the current request location.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @type string Version salt followed by the current request location.
+ */
+ public $salt_location = '';
-/*
- * Start output buffering (if applicable); or serve a cache file (if possible).
- *
- * @since 150422 Rewrite.
- *
- * @note This is a vital part of Comet Cache. This method serves existing (fresh) cache files.
- * It is also responsible for beginning the process of collecting the output buffer.
- */
-$self->maybeStartOutputBuffering = function () use ($self) {
- if (strcasecmp(PHP_SAPI, 'cli') === 0) {
- return $self->maybeSetDebugInfo(NC_DEBUG_PHP_SAPI_CLI);
- }
- if (empty($_SERVER['HTTP_HOST']) || !$self->hostToken()) {
- return $self->maybeSetDebugInfo(NC_DEBUG_NO_SERVER_HTTP_HOST);
- }
- if (empty($_SERVER['REQUEST_URI'])) {
- return $self->maybeSetDebugInfo(NC_DEBUG_NO_SERVER_REQUEST_URI);
- }
- if (defined('COMET_CACHE_ALLOWED') && !COMET_CACHE_ALLOWED) {
- return $self->maybeSetDebugInfo(NC_DEBUG_COMET_CACHE_ALLOWED_CONSTANT);
- }
- if (isset($_SERVER['COMET_CACHE_ALLOWED']) && !$_SERVER['COMET_CACHE_ALLOWED']) {
- return $self->maybeSetDebugInfo(NC_DEBUG_COMET_CACHE_ALLOWED_SERVER_VAR);
- }
- if (defined('DONOTCACHEPAGE')) {
- return $self->maybeSetDebugInfo(NC_DEBUG_DONOTCACHEPAGE_CONSTANT);
- }
- if (isset($_SERVER['DONOTCACHEPAGE'])) {
- return $self->maybeSetDebugInfo(NC_DEBUG_DONOTCACHEPAGE_SERVER_VAR);
- }
- if (isset($_GET[strtolower(SHORT_NAME).'AC']) && !filter_var($_GET[strtolower(SHORT_NAME).'AC'], FILTER_VALIDATE_BOOLEAN)) {
- return $self->maybeSetDebugInfo(NC_DEBUG_AC_GET_VAR);
- }
- if ($self->isUncacheableRequestMethod()) {
- return $self->maybeSetDebugInfo(NC_DEBUG_UNCACHEABLE_REQUEST);
- }
- if (isset($_SERVER['SERVER_ADDR']) && $self->currentIp() === $_SERVER['SERVER_ADDR']) {
- if ((!IS_PRO || !$self->isAutoCacheEngine()) && !$self->isLocalhost()) {
- return $self->maybeSetDebugInfo(NC_DEBUG_SELF_SERVE_REQUEST);
+ /*
+ * Calculated max age; i.e., before expiration.
+ *
+ * @since 151002 Load average checks in pro version.
+ *
+ * @type integer Calculated max age; i.e., before expiration.
+ */
+ public $cache_max_age = 0;
+
+ /*
+ * Start output buffering (if applicable); or serve a cache file (if possible).
+ *
+ * @since 150422 Rewrite.
+ *
+ * @note This is a vital part of Comet Cache. This method serves existing (fresh) cache files.
+ * It is also responsible for beginning the process of collecting the output buffer.
+ */
+ public function maybeStartOutputBuffering()
+ {
+ if (strcasecmp(PHP_SAPI, 'cli') === 0) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_PHP_SAPI_CLI);
}
- }
- if (!COMET_CACHE_FEEDS_ENABLE && $self->isFeed()) {
- return $self->maybeSetDebugInfo(NC_DEBUG_FEED_REQUEST);
- }
- if (preg_match('/\/(?:wp\-[^\/]+|xmlrpc)\.php(?:[?]|$)/i', $_SERVER['REQUEST_URI'])) {
- return $self->maybeSetDebugInfo(NC_DEBUG_WP_SYSTEMATICS);
- }
- if (is_admin() || preg_match('/\/wp-admin(?:[\/?]|$)/i', $_SERVER['REQUEST_URI'])) {
- return $self->maybeSetDebugInfo(NC_DEBUG_WP_ADMIN);
- }
- if (is_multisite() && preg_match('/\/files(?:[\/?]|$)/i', $_SERVER['REQUEST_URI'])) {
- return $self->maybeSetDebugInfo(NC_DEBUG_MS_FILES);
- }
- if ((!IS_PRO || !COMET_CACHE_WHEN_LOGGED_IN) && $self->isLikeUserLoggedIn()) {
- return $self->maybeSetDebugInfo(NC_DEBUG_IS_LIKE_LOGGED_IN_USER);
- }
- if (!COMET_CACHE_GET_REQUESTS && $self->requestContainsUncacheableQueryVars()) {
- return $self->maybeSetDebugInfo(NC_DEBUG_GET_REQUEST_QUERIES);
- }
- if (!empty($_REQUEST['preview'])) {
- return $self->maybeSetDebugInfo(NC_DEBUG_PREVIEW);
- }
- if (COMET_CACHE_EXCLUDE_URIS && preg_match(COMET_CACHE_EXCLUDE_URIS, $_SERVER['REQUEST_URI'])) {
- return $self->maybeSetDebugInfo(NC_DEBUG_EXCLUDED_URIS);
- }
- if (COMET_CACHE_EXCLUDE_AGENTS && !empty($_SERVER['HTTP_USER_AGENT']) && (!IS_PRO || !$self->isAutoCacheEngine())) {
- if (preg_match(COMET_CACHE_EXCLUDE_AGENTS, $_SERVER['HTTP_USER_AGENT'])) {
- return $self->maybeSetDebugInfo(NC_DEBUG_EXCLUDED_AGENTS);
+ if (empty($_SERVER['HTTP_HOST']) || !$this->hostToken()) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_NO_SERVER_HTTP_HOST);
}
- }
- if (COMET_CACHE_EXCLUDE_REFS && !empty($_REQUEST['_wp_http_referer'])) {
- if (preg_match(COMET_CACHE_EXCLUDE_REFS, stripslashes($_REQUEST['_wp_http_referer']))) {
- return $self->maybeSetDebugInfo(NC_DEBUG_EXCLUDED_REFS);
+ if (empty($_SERVER['REQUEST_URI'])) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_NO_SERVER_REQUEST_URI);
}
- }
- if (COMET_CACHE_EXCLUDE_REFS && !empty($_SERVER['HTTP_REFERER'])) {
- if (preg_match(COMET_CACHE_EXCLUDE_REFS, $_SERVER['HTTP_REFERER'])) {
- return $self->maybeSetDebugInfo(NC_DEBUG_EXCLUDED_REFS);
+ if (defined('COMET_CACHE_ALLOWED') && !COMET_CACHE_ALLOWED) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_COMET_CACHE_ALLOWED_CONSTANT);
}
- }
- $self->protocol = $self->isSsl() ? 'https://' : 'http://';
- $self->host_token = $self->hostToken();
- $self->host_base_dir_tokens = $self->hostBaseDirTokens();
+ if (isset($_SERVER['COMET_CACHE_ALLOWED']) && !$_SERVER['COMET_CACHE_ALLOWED']) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_COMET_CACHE_ALLOWED_SERVER_VAR);
+ }
+ if (defined('DONOTCACHEPAGE')) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_DONOTCACHEPAGE_CONSTANT);
+ }
+ if (isset($_SERVER['DONOTCACHEPAGE'])) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_DONOTCACHEPAGE_SERVER_VAR);
+ }
+ if (isset($_GET[strtolower(SHORT_NAME).'AC']) && !filter_var($_GET[strtolower(SHORT_NAME).'AC'], FILTER_VALIDATE_BOOLEAN)) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_AC_GET_VAR);
+ }
+ if ($this->isUncacheableRequestMethod()) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_UNCACHEABLE_REQUEST);
+ }
+ if (isset($_SERVER['SERVER_ADDR']) && $this->currentIp() === $_SERVER['SERVER_ADDR']) {
+ if ((!IS_PRO || !$this->isAutoCacheEngine()) && !$this->isLocalhost()) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_SELF_SERVE_REQUEST);
+ }
+ }
+ if (!COMET_CACHE_FEEDS_ENABLE && $this->isFeed()) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_FEED_REQUEST);
+ }
+ if (preg_match('/\/(?:wp\-[^\/]+|xmlrpc)\.php(?:[?]|$)/i', $_SERVER['REQUEST_URI'])) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_WP_SYSTEMATICS);
+ }
+ if (is_admin() || preg_match('/\/wp-admin(?:[\/?]|$)/i', $_SERVER['REQUEST_URI'])) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_WP_ADMIN);
+ }
+ if (is_multisite() && preg_match('/\/files(?:[\/?]|$)/i', $_SERVER['REQUEST_URI'])) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_MS_FILES);
+ }
+ if ((!IS_PRO || !COMET_CACHE_WHEN_LOGGED_IN) && $this->isLikeUserLoggedIn()) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_IS_LIKE_LOGGED_IN_USER);
+ }
+ if (!COMET_CACHE_GET_REQUESTS && $this->requestContainsUncacheableQueryVars()) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_GET_REQUEST_QUERIES);
+ }
+ if (!empty($_REQUEST['preview'])) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_PREVIEW);
+ }
+ if (COMET_CACHE_EXCLUDE_URIS && preg_match(COMET_CACHE_EXCLUDE_URIS, $_SERVER['REQUEST_URI'])) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_EXCLUDED_URIS);
+ }
+ if (COMET_CACHE_EXCLUDE_AGENTS && !empty($_SERVER['HTTP_USER_AGENT']) && (!IS_PRO || !$this->isAutoCacheEngine())) {
+ if (preg_match(COMET_CACHE_EXCLUDE_AGENTS, $_SERVER['HTTP_USER_AGENT'])) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_EXCLUDED_AGENTS);
+ }
+ }
+ if (COMET_CACHE_EXCLUDE_REFS && !empty($_REQUEST['_wp_http_referer'])) {
+ if (preg_match(COMET_CACHE_EXCLUDE_REFS, stripslashes($_REQUEST['_wp_http_referer']))) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_EXCLUDED_REFS);
+ }
+ }
+ if (COMET_CACHE_EXCLUDE_REFS && !empty($_SERVER['HTTP_REFERER'])) {
+ if (preg_match(COMET_CACHE_EXCLUDE_REFS, $_SERVER['HTTP_REFERER'])) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_EXCLUDED_REFS);
+ }
+ }
+ $this->protocol = $this->isSsl() ? 'https://' : 'http://';
+ $this->host_token = $this->hostToken();
+ $this->host_base_dir_tokens = $this->hostBaseDirTokens();
- $self->version_salt = ''; // Initialize the version salt.
- /*[pro strip-from="lite"]*/ // Fill the version salt in pro version.
- $self->version_salt = COMET_CACHE_VERSION_SALT; // Initialize the version salt. /*[/pro]*/
- $self->version_salt = $self->applyFilters(get_class($self).'__version_salt', $self->version_salt);
- $self->version_salt = $self->applyFilters(GLOBAL_NS.'_version_salt', $self->version_salt);
+ $this->version_salt = ''; // Initialize the version salt.
+ /*[pro strip-from="lite"]*/ // Fill the version salt in pro version.
+ $this->version_salt = COMET_CACHE_VERSION_SALT; // Initialize the version salt. /*[/pro]*/
+ $this->version_salt = $this->applyFilters(get_class($self).'__version_salt', $this->version_salt);
+ $this->version_salt = $this->applyFilters(GLOBAL_NS.'_version_salt', $this->version_salt);
- $self->cache_path = $self->buildCachePath($self->protocol.$self->host_token.$_SERVER['REQUEST_URI'], '', $self->version_salt);
- $self->cache_file = COMET_CACHE_DIR.'/'.$self->cache_path; // Not considering a user cache. That's done in the postload phase.
+ $this->cache_path = $this->buildCachePath($this->protocol.$this->host_token.$_SERVER['REQUEST_URI'], '', $this->version_salt);
+ $this->cache_file = COMET_CACHE_DIR.'/'.$this->cache_path; // Not considering a user cache. That's done in the postload phase.
- $self->cache_path_404 = $self->buildCachePath($self->protocol.$self->host_token.rtrim($self->host_base_dir_tokens, '/').'/'.COMET_CACHE_404_CACHE_FILENAME);
- $self->cache_file_404 = COMET_CACHE_DIR.'/'.$self->cache_path_404; // Not considering a user cache at all here--ever.
+ $this->cache_path_404 = $this->buildCachePath($this->protocol.$this->host_token.rtrim($this->host_base_dir_tokens, '/').'/'.COMET_CACHE_404_CACHE_FILENAME);
+ $this->cache_file_404 = COMET_CACHE_DIR.'/'.$this->cache_path_404; // Not considering a user cache at all here--ever.
- $self->salt_location = ltrim($self->version_salt.' '.$self->protocol.$self->host_token.$_SERVER['REQUEST_URI']);
+ $this->salt_location = ltrim($this->version_salt.' '.$this->protocol.$this->host_token.$_SERVER['REQUEST_URI']);
- $self->cache_max_age = strtotime('-'.COMET_CACHE_MAX_AGE);
- /*[pro strip-from="lite"]*/ // Pro version allows for load average checks.
- if (COMET_CACHE_MAX_AGE_DISABLE_IF_LOAD_AVERAGE_IS_GTE && ($load_averages = $self->sysLoadAverages())) {
- if (max($load_averages) >= COMET_CACHE_MAX_AGE_DISABLE_IF_LOAD_AVERAGE_IS_GTE) {
- $self->cache_max_age = 0; // No expiration time.
- }
- } /*[/pro]*/
- if (IS_PRO && COMET_CACHE_WHEN_LOGGED_IN === 'postload' && $self->isLikeUserLoggedIn()) {
- $self->postload['when_logged_in'] = true; // Enable postload check.
- } elseif (is_file($self->cache_file) && (!$self->cache_max_age || filemtime($self->cache_file) >= $self->cache_max_age)) {
- list($headers, $cache) = explode('', file_get_contents($self->cache_file), 2);
+ $this->cache_max_age = strtotime('-'.COMET_CACHE_MAX_AGE);
+ /*[pro strip-from="lite"]*/ // Pro version allows for load average checks.
+ if (COMET_CACHE_MAX_AGE_DISABLE_IF_LOAD_AVERAGE_IS_GTE && ($load_averages = $this->sysLoadAverages())) {
+ if (max($load_averages) >= COMET_CACHE_MAX_AGE_DISABLE_IF_LOAD_AVERAGE_IS_GTE) {
+ $this->cache_max_age = 0; // No expiration time.
+ }
+ } /*[/pro]*/
+ if (IS_PRO && COMET_CACHE_WHEN_LOGGED_IN === 'postload' && $this->isLikeUserLoggedIn()) {
+ $this->postload['when_logged_in'] = true; // Enable postload check.
+ } elseif (is_file($this->cache_file) && (!$this->cache_max_age || filemtime($this->cache_file) >= $this->cache_max_age)) {
+ list($headers, $cache) = explode('', file_get_contents($this->cache_file), 2);
- $headers_list = $self->headersList();
- foreach (unserialize($headers) as $_header) {
- if (!in_array($_header, $headers_list, true) && stripos($_header, 'Last-Modified:') !== 0) {
- header($_header); // Only cacheable/safe headers are stored in the cache.
+ $headers_list = $this->headersList();
+ foreach (unserialize($headers) as $_header) {
+ if (!in_array($_header, $headers_list, true) && stripos($_header, 'Last-Modified:') !== 0) {
+ header($_header); // Only cacheable/safe headers are stored in the cache.
+ }
}
- }
- unset($_header); // Just a little housekeeping.
+ unset($_header); // Just a little housekeeping.
- if (COMET_CACHE_DEBUGGING_ENABLE && $self->isHtmlXmlDoc($cache)) {
- $total_time = number_format(microtime(true) - $self->timer, 5, '.', '');
- $cache .= "\n".'';
- // translators: This string is actually NOT translatable because the `__()` function is not available at this point in the processing.
- $cache .= "\n".'';
- }
- exit($cache); // Exit with cache contents.
- } else {
- ob_start(array($self, 'outputBufferCallbackHandler'));
+ if (COMET_CACHE_DEBUGGING_ENABLE && $this->isHtmlXmlDoc($cache)) {
+ $total_time = number_format(microtime(true) - $this->timer, 5, '.', '');
+ $cache .= "\n".'';
+ // translators: This string is actually NOT translatable because the `__()` function is not available at this point in the processing.
+ $cache .= "\n".'';
+ }
+ exit($cache); // Exit with cache contents.
+ } else {
+ ob_start([$self, 'outputBufferCallbackHandler']);
+ }
+ return; // Return value not applicable.
}
- return; // Return value not applicable.
-};
-/*
- * Output buffer handler; i.e. the cache file generator.
- *
- * @note We CANNOT depend on any WP functionality here; it will cause problems.
- * Anything we need from WP should be saved in the postload phase as a scalar value.
- *
- * @since 150422 Rewrite.
- *
- * @param string $buffer The buffer from {@link \ob_start()}.
- * @param int $phase A set of bitmask flags.
- *
- * @throws \Exception If unable to handle output buffering for any reason.
- *
- * @return string|bool The output buffer, or `FALSE` to indicate no change.
- *
- * @attaches-to {@link \ob_start()}
- */
-$self->outputBufferCallbackHandler = function ($buffer, $phase) use ($self) {
- if (!($phase & PHP_OUTPUT_HANDLER_END)) {
- throw new \Exception(sprintf(__('Unexpected OB phase: `%1$s`.', SLUG_TD), $phase));
- }
- AdvCacheBackCompat::zenCacheConstants();
+ /*
+ * Output buffer handler; i.e. the cache file generator.
+ *
+ * @note We CANNOT depend on any WP functionality here; it will cause problems.
+ * Anything we need from WP should be saved in the postload phase as a scalar value.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $buffer The buffer from {@link \ob_start()}.
+ * @param int $phase A set of bitmask flags.
+ *
+ * @throws \Exception If unable to handle output buffering for any reason.
+ *
+ * @return string|bool The output buffer, or `FALSE` to indicate no change.
+ *
+ * @attaches-to {@link \ob_start()}
+ */
+ public function outputBufferCallbackHandler($buffer, $phase)
+ {
+ if (!($phase & PHP_OUTPUT_HANDLER_END)) {
+ throw new \Exception(sprintf(__('Unexpected OB phase: `%1$s`.', SLUG_TD), $phase));
+ }
+ AdvCacheBackCompat::zenCacheConstants();
- $cache = trim((string) $buffer);
+ $cache = trim((string) $buffer);
- if (!isset($cache[0])) {
- return false; // Don't cache an empty buffer.
- }
- if (!isset($GLOBALS[GLOBAL_NS.'_shutdown_flag'])) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_EARLY_BUFFER_TERMINATION);
- }
- if (defined('COMET_CACHE_ALLOWED') && !COMET_CACHE_ALLOWED) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_COMET_CACHE_ALLOWED_CONSTANT);
- }
- if (isset($_SERVER['COMET_CACHE_ALLOWED']) && !$_SERVER['COMET_CACHE_ALLOWED']) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_COMET_CACHE_ALLOWED_SERVER_VAR);
- }
- if (defined('DONOTCACHEPAGE')) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_DONOTCACHEPAGE_CONSTANT);
- }
- if (isset($_SERVER['DONOTCACHEPAGE'])) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_DONOTCACHEPAGE_SERVER_VAR);
- }
- if ((!IS_PRO || !COMET_CACHE_WHEN_LOGGED_IN) && $self->is_user_logged_in) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_IS_LOGGED_IN_USER);
- }
- if ((!IS_PRO || !COMET_CACHE_WHEN_LOGGED_IN) && $self->isLikeUserLoggedIn()) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_IS_LIKE_LOGGED_IN_USER);
- }
- if (!COMET_CACHE_CACHE_NONCE_VALUES && preg_match('/\b(?:_wpnonce|akismet_comment_nonce)\b/', $cache)) {
- if (IS_PRO && COMET_CACHE_WHEN_LOGGED_IN && $self->isLikeUserLoggedIn()) {
- if (!COMET_CACHE_CACHE_NONCE_VALUES_WHEN_LOGGED_IN) {
- return (boolean)$self->maybeSetDebugInfo(NC_DEBUG_IS_LOGGED_IN_USER_NONCE);
+ if (!isset($cache[0])) {
+ return false; // Don't cache an empty buffer.
+ }
+ if (!isset($GLOBALS[GLOBAL_NS.'_shutdown_flag'])) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_EARLY_BUFFER_TERMINATION);
+ }
+ if (defined('COMET_CACHE_ALLOWED') && !COMET_CACHE_ALLOWED) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_COMET_CACHE_ALLOWED_CONSTANT);
+ }
+ if (isset($_SERVER['COMET_CACHE_ALLOWED']) && !$_SERVER['COMET_CACHE_ALLOWED']) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_COMET_CACHE_ALLOWED_SERVER_VAR);
+ }
+ if (defined('DONOTCACHEPAGE')) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_DONOTCACHEPAGE_CONSTANT);
+ }
+ if (isset($_SERVER['DONOTCACHEPAGE'])) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_DONOTCACHEPAGE_SERVER_VAR);
+ }
+ if ((!IS_PRO || !COMET_CACHE_WHEN_LOGGED_IN) && $this->is_user_logged_in) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_IS_LOGGED_IN_USER);
+ }
+ if ((!IS_PRO || !COMET_CACHE_WHEN_LOGGED_IN) && $this->isLikeUserLoggedIn()) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_IS_LIKE_LOGGED_IN_USER);
+ }
+ if (!COMET_CACHE_CACHE_NONCE_VALUES && preg_match('/\b(?:_wpnonce|akismet_comment_nonce)\b/', $cache)) {
+ if (IS_PRO && COMET_CACHE_WHEN_LOGGED_IN && $this->isLikeUserLoggedIn()) {
+ if (!COMET_CACHE_CACHE_NONCE_VALUES_WHEN_LOGGED_IN) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_IS_LOGGED_IN_USER_NONCE);
+ }
+ } else { // Use the default debug notice for nonce conflicts.
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_PAGE_CONTAINS_NONCE);
+ } // An nonce makes the page dynamic; i.e., NOT cache compatible.
+ }
+ if ($this->is_404 && !COMET_CACHE_CACHE_404_REQUESTS) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_404_REQUEST);
+ }
+ if (stripos($cache, '') !== false) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_WP_ERROR_PAGE);
+ }
+ if (!$this->functionIsPossible('http_response_code')) {
+ if (stripos($cache, 'database error') !== false) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_WP_ERROR_PAGE);
}
- } else { // Use the default debug notice for nonce conflicts.
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_PAGE_CONTAINS_NONCE);
- } // An nonce makes the page dynamic; i.e., NOT cache compatible.
- }
- if ($self->is_404 && !COMET_CACHE_CACHE_404_REQUESTS) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_404_REQUEST);
- }
- if (stripos($cache, '') !== false) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_WP_ERROR_PAGE);
- }
- if (!$self->functionIsPossible('http_response_code')) {
- if (stripos($cache, 'database error') !== false) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_WP_ERROR_PAGE);
}
- }
- if (!$self->hasACacheableContentType()) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_UNCACHEABLE_CONTENT_TYPE);
- }
- if (!$self->hasACacheableStatus()) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_UNCACHEABLE_STATUS);
- }
- if ($self->is_maintenance) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_MAINTENANCE_PLUGIN);
- }
- if ($self->functionIsPossible('zlib_get_coding_type') && zlib_get_coding_type()
- && (!($zlib_oc = ini_get('zlib.output_compression')) || !filter_var($zlib_oc, FILTER_VALIDATE_BOOLEAN))) {
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_OB_ZLIB_CODING_TYPE);
- }
- # Lock the cache directory while writes take place here.
+ if (!$this->hasACacheableContentType()) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_UNCACHEABLE_CONTENT_TYPE);
+ }
+ if (!$this->hasACacheableStatus()) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_UNCACHEABLE_STATUS);
+ }
+ if ($this->is_maintenance) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_MAINTENANCE_PLUGIN);
+ }
+ if ($this->functionIsPossible('zlib_get_coding_type') && zlib_get_coding_type()
+ && (!($zlib_oc = ini_get('zlib.output_compression')) || !filter_var($zlib_oc, FILTER_VALIDATE_BOOLEAN))
+ ) {
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_OB_ZLIB_CODING_TYPE);
+ }
+ # Lock the cache directory while writes take place here.
- $cache_lock = $self->cacheLock(); // Lock cache directory.
+ $cache_lock = $this->cacheLock(); // Lock cache directory.
- # Construct a temp file for atomic cache writes.
+ # Construct a temp file for atomic cache writes.
- $cache_file_tmp = $self->addTmpSuffix($self->cache_file);
+ $cache_file_tmp = $this->addTmpSuffix($this->cache_file);
- # Cache directory checks. The cache file directory is created here if necessary.
+ # Cache directory checks. The cache file directory is created here if necessary.
- if (!is_dir(COMET_CACHE_DIR) && mkdir(COMET_CACHE_DIR, 0775, true) && !is_file(COMET_CACHE_DIR.'/.htaccess')) {
- file_put_contents(COMET_CACHE_DIR.'/.htaccess', $self->htaccess_deny);
- }
- if (!is_dir($cache_file_dir = dirname($self->cache_file))) {
- $cache_file_dir_writable = mkdir($cache_file_dir, 0775, true);
- }
- if (empty($cache_file_dir_writable) && !is_writable($cache_file_dir)) {
- throw new \Exception(sprintf(__('Cache directory not writable. %1$s needs this directory please: `%2$s`. Set permissions to `755` or higher; `777` might be needed in some cases.', SLUG_TD), NAME, $cache_file_dir));
- }
- # This is where a new 404 request might be detected for the first time.
+ if (!is_dir(COMET_CACHE_DIR) && mkdir(COMET_CACHE_DIR, 0775, true) && !is_file(COMET_CACHE_DIR.'/.htaccess')) {
+ file_put_contents(COMET_CACHE_DIR.'/.htaccess', $this->htaccess_deny);
+ }
+ if (!is_dir($cache_file_dir = dirname($this->cache_file))) {
+ $cache_file_dir_writable = mkdir($cache_file_dir, 0775, true);
+ }
+ if (empty($cache_file_dir_writable) && !is_writable($cache_file_dir)) {
+ throw new \Exception(sprintf(__('Cache directory not writable. %1$s needs this directory please: `%2$s`. Set permissions to `755` or higher; `777` might be needed in some cases.', SLUG_TD), NAME, $cache_file_dir));
+ }
+ # This is where a new 404 request might be detected for the first time.
- if ($self->is_404 && is_file($self->cache_file_404)) {
- if (!(symlink($self->cache_file_404, $cache_file_tmp) && rename($cache_file_tmp, $self->cache_file))) {
- throw new \Exception(sprintf(__('Unable to create symlink: `%1$s` » `%2$s`. Possible permissions issue (or race condition), please check your cache directory: `%3$s`.', SLUG_TD), $self->cache_file, $self->cache_file_404, COMET_CACHE_DIR));
+ if ($this->is_404 && is_file($this->cache_file_404)) {
+ if (!(symlink($this->cache_file_404, $cache_file_tmp) && rename($cache_file_tmp, $this->cache_file))) {
+ throw new \Exception(sprintf(__('Unable to create symlink: `%1$s` » `%2$s`. Possible permissions issue (or race condition), please check your cache directory: `%3$s`.', SLUG_TD), $this->cache_file, $this->cache_file_404, COMET_CACHE_DIR));
+ }
+ $this->cacheUnlock($cache_lock); // Release.
+ return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_1ST_TIME_404_SYMLINK);
}
- $self->cacheUnlock($cache_lock); // Release.
- return (boolean) $self->maybeSetDebugInfo(NC_DEBUG_1ST_TIME_404_SYMLINK);
- }
- /* ------- Otherwise, we need to construct & store a new cache file. ----------------------------------------------- */
+ /* ------- Otherwise, we need to construct & store a new cache file. ----------------------------------------------- */
- /*[pro strip-from="lite"]*/
- $cache = $self->maybeCompressHtml($cache); // Possible HTML compression.
- /*[/pro]*/
+ /*[pro strip-from="lite"]*/
+ $cache = $this->maybeCompressHtml($cache); // Possible HTML compression.
+ /*[/pro]*/
- if (COMET_CACHE_DEBUGGING_ENABLE && $self->isHtmlXmlDoc($cache)) {
- $total_time = number_format(microtime(true) - $self->timer, 5, '.', ''); // Based on the original timer.
- $cache .= "\n".'';
- $cache .= "\n".'';
- $cache .= "\n".'';
- }
- if ($self->is_404) {
- if (file_put_contents($cache_file_tmp, serialize($self->cacheableHeadersList()).''.$cache) && rename($cache_file_tmp, $self->cache_file_404)) {
- if (!(symlink($self->cache_file_404, $cache_file_tmp) && rename($cache_file_tmp, $self->cache_file))) {
- throw new \Exception(sprintf(__('Unable to create symlink: `%1$s` » `%2$s`. Possible permissions issue (or race condition), please check your cache directory: `%3$s`.', SLUG_TD), $self->cache_file, $self->cache_file_404, COMET_CACHE_DIR));
+ if (COMET_CACHE_DEBUGGING_ENABLE && $this->isHtmlXmlDoc($cache)) {
+ $total_time = number_format(microtime(true) - $this->timer, 5, '.', ''); // Based on the original timer.
+ $cache .= "\n".'';
+ $cache .= "\n".'';
+ $cache .= "\n".'';
+ }
+ if ($this->is_404) {
+ if (file_put_contents($cache_file_tmp, serialize($this->cacheableHeadersList()).''.$cache) && rename($cache_file_tmp, $this->cache_file_404)) {
+ if (!(symlink($this->cache_file_404, $cache_file_tmp) && rename($cache_file_tmp, $this->cache_file))) {
+ throw new \Exception(sprintf(__('Unable to create symlink: `%1$s` » `%2$s`. Possible permissions issue (or race condition), please check your cache directory: `%3$s`.', SLUG_TD), $this->cache_file, $this->cache_file_404, COMET_CACHE_DIR));
+ }
+ $this->cacheUnlock($cache_lock); // Release.
+ return $cache; // Return the newly built cache; with possible debug information also.
}
- $self->cacheUnlock($cache_lock); // Release.
+ } elseif (file_put_contents($cache_file_tmp, serialize($this->cacheableHeadersList()).''.$cache) && rename($cache_file_tmp, $this->cache_file)) {
+ $this->cacheUnlock($cache_lock); // Release.
return $cache; // Return the newly built cache; with possible debug information also.
}
- } elseif (file_put_contents($cache_file_tmp, serialize($self->cacheableHeadersList()).''.$cache) && rename($cache_file_tmp, $self->cache_file)) {
- $self->cacheUnlock($cache_lock); // Release.
- return $cache; // Return the newly built cache; with possible debug information also.
+ @unlink($cache_file_tmp); // Clean this up (if it exists); and throw an exception with information for the site owner.
+ throw new \Exception(sprintf(__('%1$s: failed to write cache file for: `%2$s`; possible permissions issue (or race condition), please check your cache directory: `%3$s`.', SLUG_TD), NAME, $_SERVER['REQUEST_URI'], COMET_CACHE_DIR));
}
- @unlink($cache_file_tmp); // Clean this up (if it exists); and throw an exception with information for the site owner.
- throw new \Exception(sprintf(__('%1$s: failed to write cache file for: `%2$s`; possible permissions issue (or race condition), please check your cache directory: `%3$s`.', SLUG_TD), NAME, $_SERVER['REQUEST_URI'], COMET_CACHE_DIR));
-};
+}
diff --git a/src/includes/traits/Ac/PostloadUtils.php b/src/includes/traits/Ac/PostloadUtils.php
index 1485a14f..6f4bc875 100644
--- a/src/includes/traits/Ac/PostloadUtils.php
+++ b/src/includes/traits/Ac/PostloadUtils.php
@@ -1,287 +1,295 @@
false,
+ 'when_logged_in' => false,
+ /*[/pro]*/
+ 'filter_status_header' => true,
+ 'wp_main_query' => true,
+ 'set_debug_info' => COMET_CACHE_DEBUGGING_ENABLE,
+ ];
-/*
- * Array of data targeted at the postload phase.
- *
- * @since 150422 Rewrite.
- *
- * @type array Data and/or flags that work with various postload handlers.
- */
-public $postload = [
/*[pro strip-from="lite"]*/
- 'invalidate_when_logged_in' => false,
- 'when_logged_in' => false,
+ /*
+ * Calculated user token; applicable w/ user postload enabled.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @type string|int An MD5 hash token; or a specific WP user ID.
+ */
+ public $user_token = '';
/*[/pro]*/
- 'filter_status_header' => true,
- 'wp_main_query' => true,
- 'set_debug_info' => COMET_CACHE_DEBUGGING_ENABLE,
-];
-
-/*[pro strip-from="lite"]*/
-/*
- * Calculated user token; applicable w/ user postload enabled.
- *
- * @since 150422 Rewrite.
- *
- * @type string|int An MD5 hash token; or a specific WP user ID.
- */
-public $user_token = '';
-/*[/pro]*/
-/*[pro strip-from="lite"]*/
-/*
- * Sets a flag for possible invalidation upon certain actions in the postload phase.
- *
- * @since 150422 Rewrite.
- */
-$self->maybePostloadInvalidateWhenLoggedIn = function () use ($self) {
- if (COMET_CACHE_WHEN_LOGGED_IN !== 'postload') {
- return; // Nothing to do in this case.
- }
- if (is_admin()) {
- return; // No invalidations.
- }
- if (!$self->isLikeUserLoggedIn()) {
- return; // Nothing to do.
- }
- if (!empty($_REQUEST[GLOBAL_NS])) {
- return; // Plugin action.
- }
- if ($self->isPostPutDeleteRequest() || $self->isUncacheableRequestMethod()) {
- $self->postload['invalidate_when_logged_in'] = true;
- } elseif (!COMET_CACHE_GET_REQUESTS && $self->requestContainsUncacheableQueryVars()) {
- $self->postload['invalidate_when_logged_in'] = true;
+ /*[pro strip-from="lite"]*/
+ /*
+ * Sets a flag for possible invalidation upon certain actions in the postload phase.
+ *
+ * @since 150422 Rewrite.
+ */
+ public function maybePostloadInvalidateWhenLoggedIn()
+ {
+ if (COMET_CACHE_WHEN_LOGGED_IN !== 'postload') {
+ return; // Nothing to do in this case.
+ }
+ if (is_admin()) {
+ return; // No invalidations.
+ }
+ if (!$this->isLikeUserLoggedIn()) {
+ return; // Nothing to do.
+ }
+ if (!empty($_REQUEST[GLOBAL_NS])) {
+ return; // Plugin action.
+ }
+ if ($this->isPostPutDeleteRequest() || $this->isUncacheableRequestMethod()) {
+ $this->postload['invalidate_when_logged_in'] = true;
+ } elseif (!COMET_CACHE_GET_REQUESTS && $this->requestContainsUncacheableQueryVars()) {
+ $this->postload['invalidate_when_logged_in'] = true;
+ }
}
-};
-/*[/pro]*/
+ /*[/pro]*/
-/*[pro strip-from="lite"]*/
-/*
- * Invalidates cache files for a user (if applicable).
- *
- * @since 150422 Rewrite.
- */
-$self->maybeInvalidateWhenLoggedInPostload = function () use ($self) {
- if (COMET_CACHE_WHEN_LOGGED_IN !== 'postload') {
- return; // Nothing to do in this case.
- }
- if (empty($self->postload['invalidate_when_logged_in'])) {
- return; // Nothing to do in this case.
- }
- if (!($self->user_token = $self->userToken())) {
- return; // Nothing to do in this case.
+ /*[pro strip-from="lite"]*/
+ /*
+ * Invalidates cache files for a user (if applicable).
+ *
+ * @since 150422 Rewrite.
+ */
+ public function maybeInvalidateWhenLoggedInPostload()
+ {
+ if (COMET_CACHE_WHEN_LOGGED_IN !== 'postload') {
+ return; // Nothing to do in this case.
+ }
+ if (empty($this->postload['invalidate_when_logged_in'])) {
+ return; // Nothing to do in this case.
+ }
+ if (!($this->user_token = $this->userToken())) {
+ return; // Nothing to do in this case.
+ }
+ $regex = $this->assembleCachePathRegex('', '.*?\.u\/'.preg_quote($this->user_token, '/').'[.\/]');
+ $this->wipeFilesFromCacheDir($regex); // Wipe matching files.
}
- $regex = $self->assembleCachePathRegex('', '.*?\.u\/'.preg_quote($self->user_token, '/').'[.\/]');
- $self->wipeFilesFromCacheDir($regex); // Wipe matching files.
-};
-/*[/pro]*/
+ /*[/pro]*/
-/*[pro strip-from="lite"]*/
-/*
- * Starts output buffering in the postload phase (i.e. a bit later);
- * when/if user caching is enabled; and if applicable.
- *
- * @since 150422 Rewrite.
- */
-$self->maybeStartObWhenLoggedInPostload = function () use ($self) {
- if (COMET_CACHE_WHEN_LOGGED_IN !== 'postload') {
- return; // Nothing to do in this case.
- }
- if (empty($self->postload['when_logged_in'])) {
- return; // Nothing to do in this case.
- }
- if (!($self->user_token = $self->userToken())) {
- if (!$self->user_login_cookie_expired_or_invalid) {
- return $self->maybeSetDebugInfo(NC_DEBUG_NO_USER_TOKEN);
+ /*[pro strip-from="lite"]*/
+ /*
+ * Starts output buffering in the postload phase (i.e. a bit later);
+ * when/if user caching is enabled; and if applicable.
+ *
+ * @since 150422 Rewrite.
+ */
+ public function maybeStartObWhenLoggedInPostload()
+ {
+ if (COMET_CACHE_WHEN_LOGGED_IN !== 'postload') {
+ return; // Nothing to do in this case.
}
- }
- $self->cache_path = $self->buildCachePath($self->protocol.$self->host_token.$_SERVER['REQUEST_URI'], $self->user_token, $self->version_salt);
- $self->cache_file = COMET_CACHE_DIR.'/'.$self->cache_path; // Now considering a user token.
+ if (empty($this->postload['when_logged_in'])) {
+ return; // Nothing to do in this case.
+ }
+ if (!($this->user_token = $this->userToken())) {
+ if (!$this->user_login_cookie_expired_or_invalid) {
+ return $this->maybeSetDebugInfo(NC_DEBUG_NO_USER_TOKEN);
+ }
+ }
+ $this->cache_path = $this->buildCachePath($this->protocol.$this->host_token.$_SERVER['REQUEST_URI'], $this->user_token, $this->version_salt);
+ $this->cache_file = COMET_CACHE_DIR.'/'.$this->cache_path; // Now considering a user token.
- if (is_file($self->cache_file) && (!$self->cache_max_age || filemtime($self->cache_file) >= $self->cache_max_age)) {
- list($headers, $cache) = explode('', file_get_contents($self->cache_file), 2);
+ if (is_file($this->cache_file) && (!$this->cache_max_age || filemtime($this->cache_file) >= $this->cache_max_age)) {
+ list($headers, $cache) = explode('', file_get_contents($this->cache_file), 2);
- $headers_list = $self->headersList();
- foreach (unserialize($headers) as $_header) {
- if (!in_array($_header, $headers_list, true) && stripos($_header, 'Last-Modified:') !== 0) {
- header($_header); // Only cacheable/safe headers are stored in the cache.
+ $headers_list = $this->headersList();
+ foreach (unserialize($headers) as $_header) {
+ if (!in_array($_header, $headers_list, true) && stripos($_header, 'Last-Modified:') !== 0) {
+ header($_header); // Only cacheable/safe headers are stored in the cache.
+ }
}
- }
- unset($_header); // Just a little housekeeping.
+ unset($_header); // Just a little housekeeping.
- if (COMET_CACHE_DEBUGGING_ENABLE && $self->isHtmlXmlDoc($cache)) {
- $total_time = number_format(microtime(true) - $self->timer, 5, '.', '');
- $cache .= "\n".'';
- $cache .= "\n".'';
+ if (COMET_CACHE_DEBUGGING_ENABLE && $this->isHtmlXmlDoc($cache)) {
+ $total_time = number_format(microtime(true) - $this->timer, 5, '.', '');
+ $cache .= "\n".'';
+ $cache .= "\n".'';
+ }
+ exit($cache); // Exit with cache contents.
+ } else {
+ ob_start([$self, 'outputBufferCallbackHandler']);
}
- exit($cache); // Exit with cache contents.
- } else {
- ob_start(array($self, 'outputBufferCallbackHandler'));
- }
- return; // Only for IDEs not to complain here.
-};
-/*[/pro]*/
-
-/*
- * Filters WP {@link \status_header()} (if applicable).
- *
- * @since 150422 Rewrite.
- */
-$self->maybeFilterStatusHeaderPostload = function () use ($self) {
- if (empty($self->postload['filter_status_header'])) {
- return; // Nothing to do in this case.
+ return; // Only for IDEs not to complain here.
}
- $_self = $self; // Reference needed below.
+ /*[/pro]*/
- add_filter(
- 'status_header',
- function ($status_header, $status_code) use ($_self) {
- if ($status_code > 0) {
- $_self->http_status = (integer) $status_code;
- }
- return $status_header;
- },
- PHP_INT_MAX,
- 2
- );
-};
+ /*
+ * Filters WP {@link \status_header()} (if applicable).
+ *
+ * @since 150422 Rewrite.
+ */
+ public function maybeFilterStatusHeaderPostload()
+ {
+ if (empty($this->postload['filter_status_header'])) {
+ return; // Nothing to do in this case.
+ }
+ $_self = $self; // Reference needed below.
-/*
- * Hooks `NC_DEBUG_` info into the WordPress `shutdown` phase (if applicable).
- *
- * @since 150422 Rewrite.
- */
-$self->maybeSetDebugInfoPostload = function () use ($self) {
- if (!COMET_CACHE_DEBUGGING_ENABLE) {
- return; // Nothing to do.
- }
- if (empty($self->postload['set_debug_info'])) {
- return; // Nothing to do in this case.
- }
- if (is_admin()) {
- return; // Not applicable.
+ add_filter(
+ 'status_header',
+ function ($status_header, $status_code) use ($_self) {
+ if ($status_code > 0) {
+ $_self->http_status = (integer) $status_code;
+ }
+ return $status_header;
+ },
+ PHP_INT_MAX,
+ 2
+ );
}
- if (strcasecmp(PHP_SAPI, 'cli') === 0) {
- return; // Let's not run the risk here.
- }
- add_action('shutdown', array($self, 'maybeEchoNcDebugInfo'), PHP_INT_MAX - 10);
-};
-/*
- * Grab details from WP and the Comet Cache plugin itself,
- * after the main query is loaded (if at all possible).
- *
- * This is where we have a chance to grab any values we need from WordPress; or from the CC plugin.
- * It is EXTREMEMLY important that we NOT attempt to grab any object references here.
- * Anything acquired in this phase should be stored as a scalar value.
- * See {@link outputBufferCallbackHandler()} for further details.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `wp` hook.
- */
-$self->wpMainQueryPostload = function () use ($self) {
- if (empty($self->postload['wp_main_query'])) {
- return; // Nothing to do in this case.
- }
- if ($self->is_wp_loaded_query || is_admin()) {
- return; // Nothing to do.
- }
- if (!is_main_query()) {
- return; // Not main query.
+ /*
+ * Hooks `NC_DEBUG_` info into the WordPress `shutdown` phase (if applicable).
+ *
+ * @since 150422 Rewrite.
+ */
+ public function maybeSetDebugInfoPostload()
+ {
+ if (!COMET_CACHE_DEBUGGING_ENABLE) {
+ return; // Nothing to do.
+ }
+ if (empty($this->postload['set_debug_info'])) {
+ return; // Nothing to do in this case.
+ }
+ if (is_admin()) {
+ return; // Not applicable.
+ }
+ if (strcasecmp(PHP_SAPI, 'cli') === 0) {
+ return; // Let's not run the risk here.
+ }
+ add_action('shutdown', [$self, 'maybeEchoNcDebugInfo'], PHP_INT_MAX - 10);
}
- $self->is_wp_loaded_query = true;
- $self->is_404 = is_404();
- $self->is_user_logged_in = is_user_logged_in();
- $self->content_url = rtrim(content_url(), '/');
- $self->is_maintenance = $self->functionIsPossible('is_maintenance') && is_maintenance();
- $_self = $self; // Reference for the closure below.
- add_action(
- 'template_redirect',
- function () use ($_self) {
- $_self->is_a_wp_content_type = $_self->is_404 || $_self->is_maintenance
- || is_front_page() // See
- || is_home() || is_singular() || is_archive() || is_post_type_archive() || is_tax() || is_search() || is_feed();
- },
- 11
- );
-};
+ /*
+ * Grab details from WP and the Comet Cache plugin itself,
+ * after the main query is loaded (if at all possible).
+ *
+ * This is where we have a chance to grab any values we need from WordPress; or from the CC plugin.
+ * It is EXTREMEMLY important that we NOT attempt to grab any object references here.
+ * Anything acquired in this phase should be stored as a scalar value.
+ * See {@link outputBufferCallbackHandler()} for further details.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `wp` hook.
+ */
+ public function wpMainQueryPostload()
+ {
+ if (empty($this->postload['wp_main_query'])) {
+ return; // Nothing to do in this case.
+ }
+ if ($this->is_wp_loaded_query || is_admin()) {
+ return; // Nothing to do.
+ }
+ if (!is_main_query()) {
+ return; // Not main query.
+ }
+ $this->is_wp_loaded_query = true;
+ $this->is_404 = is_404();
+ $this->is_user_logged_in = is_user_logged_in();
+ $this->content_url = rtrim(content_url(), '/');
+ $this->is_maintenance = $this->functionIsPossible('is_maintenance') && is_maintenance();
+ $_self = $self; // Reference for the closure below.
+
+ add_action(
+ 'template_redirect',
+ function () use ($_self) {
+ $_self->is_a_wp_content_type = $_self->is_404 || $_self->is_maintenance
+ || is_front_page() // See
+ || is_home() || is_singular() || is_archive() || is_post_type_archive() || is_tax() || is_search() || is_feed();
+ },
+ 11
+ );
+ }
+}
diff --git a/src/includes/traits/Ac/ShutdownUtils.php b/src/includes/traits/Ac/ShutdownUtils.php
index 7212d1b9..7510a61a 100644
--- a/src/includes/traits/Ac/ShutdownUtils.php
+++ b/src/includes/traits/Ac/ShutdownUtils.php
@@ -1,18 +1,23 @@
registerShutdownFlag = function () use ($self) {
- register_shutdown_function(function () {
- $GLOBALS[GLOBAL_NS.'_shutdown_flag'] = -1;
- });
-};
+trait ShutdownUtils {
+ /*
+ * Registers a shutdown flag.
+ *
+ * @since 140605 Improving output buffer.
+ *
+ * @note In `/wp-settings.php`, Comet Cache is loaded before WP registers its own shutdown function.
+ * Therefore, this flag is set before {@link shutdown_action_hook()} fires, and thus before {@link wp_ob_end_flush_all()}.
+ *
+ * @see http://www.php.net/manual/en/function.register-shutdown-function.php
+ */
+ public function registerShutdownFlag()
+ {
+ register_shutdown_function(
+ function () {
+ $GLOBALS[GLOBAL_NS.'_shutdown_flag'] = -1;
+ }
+ );
+ }
+}
diff --git a/src/includes/traits/Plugin/ActionUtils.php b/src/includes/traits/Plugin/ActionUtils.php
index ccd54efc..1d7bb95b 100644
--- a/src/includes/traits/Plugin/ActionUtils.php
+++ b/src/includes/traits/Plugin/ActionUtils.php
@@ -1,23 +1,27 @@
actions = function () use ($self) {
- if (!empty($_REQUEST[GLOBAL_NS])) {
- new Actions();
+trait ActionUtils {
+ /*
+ * Plugin action handler.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `wp_loaded` hook.
+ */
+ public function actions()
+ {
+ if (!empty($_REQUEST[GLOBAL_NS])) {
+ new Actions();
+ }
+ /*[pro strip-from="lite"]*/
+ if (!empty($_REQUEST[GLOBAL_NS.'_auto_cache_cron'])
+ // Back compat. Allow for the older `__` variation also.
+ || !empty($_REQUEST[GLOBAL_NS.'__auto_cache_cron'])
+ ) {
+ $this->autoCache();
+ exit();
+ }
+ /*[/pro]*/
}
- /*[pro strip-from="lite"]*/
- if (!empty($_REQUEST[GLOBAL_NS.'_auto_cache_cron'])
- // Back compat. Allow for the older `__` variation also.
- || !empty($_REQUEST[GLOBAL_NS.'__auto_cache_cron'])) {
- $self->autoCache();
- exit();
- }
- /*[/pro]*/
-};
+}
diff --git a/src/includes/traits/Plugin/AdminBarUtils.php b/src/includes/traits/Plugin/AdminBarUtils.php
index 6d340c66..02a54cae 100644
--- a/src/includes/traits/Plugin/AdminBarUtils.php
+++ b/src/includes/traits/Plugin/AdminBarUtils.php
@@ -2,356 +2,363 @@
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Traits\Plugin;
-/*
- * Showing admin bar.
- *
- * @since 151002 Improving admin bar.
- *
- * @param boolean $feature Check something specific?
- *
- * @return boolean True if showing.
- */
-$self->adminBarShowing = function ($feature = '') use ($self) {
- $feature = trim(strtolower((string) $feature));
- if (!is_null($showing = &$self->cacheKey('adminBarShowing', $feature))) {
- return $showing; // Already cached this.
- }
- $is_multisite = is_multisite(); // Call this once only.
-
- if (($showing = $self->options['enable'] && is_admin_bar_showing())) {
- switch ($feature) {
- case 'cache_wipe':
- $showing = $self->options['cache_clear_admin_bar_enable'] && $is_multisite;
- break;
-
- case 'cache_clear':
- case 'cache_clear_options':
- $showing = $self->options['cache_clear_admin_bar_enable'] && (!$is_multisite || !is_network_admin() || $self->isMenuPage(GLOBAL_NS.'*'));
- // `$self->isMenuPage(GLOBAL_NS.'*')` shows "Cache Clear" button in Network Admin when configuring options; i.e., avoids confusion.
- if ($feature === 'cache_clear_options') {
- $showing = $showing && $self->options['cache_clear_admin_bar_options_enable'];
- }
- break;
-
- case 'stats':
- $showing = $self->options['stats_enable'] && $self->options['stats_admin_bar_enable'];
- break;
-
- default: // Default case handler.
- $showing = ($self->options['cache_clear_admin_bar_enable'] && $is_multisite)
- || ($self->options['cache_clear_admin_bar_enable'] && (!$is_multisite || !is_network_admin() || $self->isMenuPage(GLOBAL_NS.'*')))
- || ($self->options['stats_enable'] && $self->options['stats_admin_bar_enable']);
- break;
+trait AdminBarUtils {
+ /*
+ * Showing admin bar.
+ *
+ * @since 151002 Improving admin bar.
+ *
+ * @param boolean $feature Check something specific?
+ *
+ * @return boolean True if showing.
+ */
+ public function adminBarShowing($feature = '')
+ {
+ $feature = trim(strtolower((string) $feature));
+ if (!is_null($showing = &$this->cacheKey('adminBarShowing', $feature))) {
+ return $showing; // Already cached this.
}
- }
- if ($showing) {
- $current_user_can_wipe_cache = $is_multisite && current_user_can($self->network_cap);
- $current_user_can_clear_cache = $self->currentUserCanClearCache();
- $current_user_can_see_stats = $self->currentUserCanSeeStats();
-
- switch ($feature) {
- case 'cache_wipe':
- $showing = $current_user_can_wipe_cache;
- break;
-
- case 'cache_clear':
- case 'cache_clear_options':
- $showing = $current_user_can_clear_cache;
- break;
-
- case 'stats':
- $showing = $current_user_can_see_stats;
- break;
-
- default: // Default case handler.
- $showing = $current_user_can_wipe_cache
- || $current_user_can_clear_cache
- || $current_user_can_see_stats;
- break;
+ $is_multisite = is_multisite(); // Call this once only.
+
+ if (($showing = $this->options['enable'] && is_admin_bar_showing())) {
+ switch ($feature) {
+ case 'cache_wipe':
+ $showing = $this->options['cache_clear_admin_bar_enable'] && $is_multisite;
+ break;
+
+ case 'cache_clear':
+ case 'cache_clear_options':
+ $showing = $this->options['cache_clear_admin_bar_enable'] && (!$is_multisite || !is_network_admin() || $this->isMenuPage(GLOBAL_NS.'*'));
+ // `$this->isMenuPage(GLOBAL_NS.'*')` shows "Cache Clear" button in Network Admin when configuring options; i.e., avoids confusion.
+ if ($feature === 'cache_clear_options') {
+ $showing = $showing && $this->options['cache_clear_admin_bar_options_enable'];
+ }
+ break;
+
+ case 'stats':
+ $showing = $this->options['stats_enable'] && $this->options['stats_admin_bar_enable'];
+ break;
+
+ default: // Default case handler.
+ $showing = ($this->options['cache_clear_admin_bar_enable'] && $is_multisite)
+ || ($this->options['cache_clear_admin_bar_enable'] && (!$is_multisite || !is_network_admin() || $this->isMenuPage(GLOBAL_NS.'*')))
+ || ($this->options['stats_enable'] && $this->options['stats_admin_bar_enable']);
+ break;
+ }
}
+ if ($showing) {
+ $current_user_can_wipe_cache = $is_multisite && current_user_can($this->network_cap);
+ $current_user_can_clear_cache = $this->currentUserCanClearCache();
+ $current_user_can_see_stats = $this->currentUserCanSeeStats();
+
+ switch ($feature) {
+ case 'cache_wipe':
+ $showing = $current_user_can_wipe_cache;
+ break;
+
+ case 'cache_clear':
+ case 'cache_clear_options':
+ $showing = $current_user_can_clear_cache;
+ break;
+
+ case 'stats':
+ $showing = $current_user_can_see_stats;
+ break;
+
+ default: // Default case handler.
+ $showing = $current_user_can_wipe_cache
+ || $current_user_can_clear_cache
+ || $current_user_can_see_stats;
+ break;
+ }
+ }
+ return $showing;
}
- return $showing;
-};
-
-/*
- * Filter WordPress admin bar.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `admin_bar_menu` hook.
- *
- * @param $wp_admin_bar \WP_Admin_Bar
- */
-$self->adminBarMenu = function (\WP_Admin_Bar &$wp_admin_bar) use ($self) {
- if (!$self->adminBarShowing()) {
- return; // Nothing to do.
- }
- if ($self->adminBarShowing('cache_wipe')) {
- $wp_admin_bar->add_menu(
- array(
- 'parent' => 'top-secondary',
- 'id' => GLOBAL_NS.'-wipe',
- 'title' => __('Wipe', SLUG_TD),
- 'href' => '#',
+ /*
+ * Filter WordPress admin bar.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `admin_bar_menu` hook.
+ *
+ * @param $wp_admin_bar \WP_Admin_Bar
+ */
+ public function adminBarMenu(\WP_Admin_Bar &$wp_admin_bar)
+ {
+ if (!$this->adminBarShowing()) {
+ return; // Nothing to do.
+ }
+ if ($this->adminBarShowing('cache_wipe')) {
+ $wp_admin_bar->add_menu(
+ [
+ 'parent' => 'top-secondary',
+ 'id' => GLOBAL_NS.'-wipe',
- 'meta' => array(
+ 'title' => __('Wipe', SLUG_TD),
+ 'href' => '#',
+
+ 'meta' => [
'title' => __('Wipe Cache (Start Fresh). Clears the cache for all sites in this network at once!', SLUG_TD),
'class' => '-wipe',
'tabindex' => -1,
- ),
- )
- );
- }
- if ($self->adminBarShowing('cache_clear')) {
- if (($cache_clear_options_showing = $self->adminBarShowing('cache_clear_options'))) {
- $cache_clear_options = ''.__('Home Page', SLUG_TD).'';
+ ],
+ ]
+ );
+ }
+ if ($this->adminBarShowing('cache_clear')) {
+ if (($cache_clear_options_showing = $this->adminBarShowing('cache_clear_options'))) {
+ $cache_clear_options = ''.__('Home Page', SLUG_TD).'';
- if (!is_admin()) {
- $cache_clear_options .= ''.__('Current URL', SLUG_TD).'';
- }
- $cache_clear_options .= ''.__('Specific URL', SLUG_TD).'';
+ if (!is_admin()) {
+ $cache_clear_options .= ''.__('Current URL', SLUG_TD).'';
+ }
+ $cache_clear_options .= ''.__('Specific URL', SLUG_TD).'';
- if ($self->functionIsPossible('opcache_reset') && $self->currentUserCanClearOpCache()) {
- $cache_clear_options .= ''.__('OPcache', SLUG_TD).'';
+ if ($this->functionIsPossible('opcache_reset') && $this->currentUserCanClearOpCache()) {
+ $cache_clear_options .= ''.__('OPcache', SLUG_TD).'';
+ }
+ if ($this->options['cdn_enable'] && $this->currentUserCanClearCdnCache()) {
+ $cache_clear_options .= ''.__('CDN Cache', SLUG_TD).'';
+ }
+ if ($this->currentUserCanClearExpiredTransients()) {
+ $cache_clear_options .= ''.__('Expired Transients', SLUG_TD).'';
+ }
+ } else {
+ $cache_clear_options = ''; // Empty in this default case.
}
- if ($self->options['cdn_enable'] && $self->currentUserCanClearCdnCache()) {
- $cache_clear_options .= ''.__('CDN Cache', SLUG_TD).'';
+ if ($cache_clear_options && $this->options['cache_clear_admin_bar_options_enable'] === '2') {
+ $wp_admin_bar->add_menu(
+ [
+ 'parent' => 'top-secondary',
+ 'id' => GLOBAL_NS.'-clear-options',
+
+ 'title' => '',
+ 'href' => '#',
+ 'meta' => [
+ 'title' => __('Clear Options', SLUG_TD),
+ 'class' => '-clear-options',
+ 'tabindex' => -1,
+ ],
+ ]
+ );
+ $wp_admin_bar->add_group(
+ [
+ 'parent' => GLOBAL_NS.'-clear-options',
+ 'id' => GLOBAL_NS.'-clear-options-wrapper',
+
+ 'meta' => [
+ 'class' => '-wrapper',
+ ],
+ ]
+ );
+ $wp_admin_bar->add_menu(
+ [
+ 'parent' => GLOBAL_NS.'-clear-options-wrapper',
+ 'id' => GLOBAL_NS.'-clear-options-container',
+
+ 'title' => ''.
+ ' '.__('Clear Cache', SLUG_TD).''.
+ '
'.
+
+ ''.
+ ' '.$cache_clear_options.
+ '
'.
+
+ '',
+
+ 'meta' => [
+ 'class' => '-container',
+ 'tabindex' => -1,
+ ],
+ ]
+ );
}
- if ($self->currentUserCanClearExpiredTransients()) {
- $cache_clear_options .= ''.__('Expired Transients', SLUG_TD).'';
+ $wp_admin_bar->add_menu(
+ [
+ 'parent' => 'top-secondary',
+ 'id' => GLOBAL_NS.'-clear',
+
+ 'title' => __('Clear Cache', SLUG_TD),
+ 'href' => '#',
+ 'meta' => [
+ 'title' => is_multisite() && current_user_can($this->network_cap)
+ ? __('Clear Cache (Start Fresh). Affects the current site only.', SLUG_TD)
+ : '',
+ 'class' => '-clear',
+ 'tabindex' => -1,
+ ],
+ ]
+ );
+ if ($cache_clear_options && $this->options['cache_clear_admin_bar_options_enable'] === '1') {
+ $wp_admin_bar->add_group(
+ [
+ 'parent' => GLOBAL_NS.'-clear',
+ 'id' => GLOBAL_NS.'-clear-options-wrapper',
+
+ 'meta' => [
+ 'class' => '-wrapper',
+ ],
+ ]
+ );
+ $wp_admin_bar->add_menu(
+ [
+ 'parent' => GLOBAL_NS.'-clear-options-wrapper',
+ 'id' => GLOBAL_NS.'-clear-options-container',
+
+ 'title' => ''.
+ ' '.$cache_clear_options.
+ '
'.
+
+ '',
+
+ 'meta' => [
+ 'class' => '-container',
+ 'tabindex' => -1,
+ ],
+ ]
+ );
}
- } else {
- $cache_clear_options = ''; // Empty in this default case.
}
- if ($cache_clear_options && $self->options['cache_clear_admin_bar_options_enable'] === '2') {
+ if ($this->adminBarShowing('stats')) {
$wp_admin_bar->add_menu(
- array(
+ [
'parent' => 'top-secondary',
- 'id' => GLOBAL_NS.'-clear-options',
+ 'id' => GLOBAL_NS.'-stats',
- 'title' => '',
+ 'title' => __('Cache Stats', SLUG_TD),
'href' => '#',
- 'meta' => array(
- 'title' => __('Clear Options', SLUG_TD),
- 'class' => '-clear-options',
- 'tabindex' => -1,
- ),
- )
+
+ 'meta' => [
+ 'class' => '-stats',
+ 'tabindex' => -1,
+ ],
+ ]
);
$wp_admin_bar->add_group(
- array(
- 'parent' => GLOBAL_NS.'-clear-options',
- 'id' => GLOBAL_NS.'-clear-options-wrapper',
+ [
+ 'parent' => GLOBAL_NS.'-stats',
+ 'id' => GLOBAL_NS.'-stats-wrapper',
- 'meta' => array(
+ 'meta' => [
'class' => '-wrapper',
- ),
- )
+ ],
+ ]
);
$wp_admin_bar->add_menu(
- array(
- 'parent' => GLOBAL_NS.'-clear-options-wrapper',
- 'id' => GLOBAL_NS.'-clear-options-container',
+ [
+ 'parent' => GLOBAL_NS.'-stats-wrapper',
+ 'id' => GLOBAL_NS.'-stats-container',
- 'title' => ''.
- ' '.__('Clear Cache', SLUG_TD).''.
- '
'.
+ 'title' => ''.
- ''.
- ' '.$cache_clear_options.
- '
'.
+ ''.
+ // ''.
- '',
+ ''.
+ '
'.__('Current Cache Totals', SLUG_TD).'
'.
+ '
'.
+ '
'.
+ '
'.esc_html(basename(WP_CONTENT_DIR).'/'.$this->options['base_dir'].'/*').'
'.
+ '
'.
- 'meta' => array(
- 'class' => '-container',
- 'tabindex' => -1,
- ),
- )
- );
- }
- $wp_admin_bar->add_menu(
- array(
- 'parent' => 'top-secondary',
- 'id' => GLOBAL_NS.'-clear',
-
- 'title' => __('Clear Cache', SLUG_TD),
- 'href' => '#',
- 'meta' => array(
- 'title' => is_multisite() && current_user_can($self->network_cap)
- ? __('Clear Cache (Start Fresh). Affects the current site only.', SLUG_TD)
- : '',
- 'class' => '-clear',
- 'tabindex' => -1,
- ),
- )
- );
- if ($cache_clear_options && $self->options['cache_clear_admin_bar_options_enable'] === '1') {
- $wp_admin_bar->add_group(
- array(
- 'parent' => GLOBAL_NS.'-clear',
- 'id' => GLOBAL_NS.'-clear-options-wrapper',
-
- 'meta' => array(
- 'class' => '-wrapper',
- ),
- )
- );
- $wp_admin_bar->add_menu(
- array(
- 'parent' => GLOBAL_NS.'-clear-options-wrapper',
- 'id' => GLOBAL_NS.'-clear-options-container',
+ ''.
+ '
'.__('Current Disk Health', SLUG_TD).'
'.
+ '
'.__('total capacity', SLUG_TD).'
'.
+ '
'.__('available', SLUG_TD).'
'.
+ '
'.
- 'title' => ''.
- ' '.$cache_clear_options.
- '
'.
+ (current_user_can($this->cap) ?
+ ''
+ : '').
- '',
+ '',
- 'meta' => array(
- 'class' => '-container',
- 'tabindex' => -1,
- ),
- )
+ 'meta' => [
+ 'class' => '-container',
+ 'tabindex' => -1,
+ ],
+ ]
);
}
}
- if ($self->adminBarShowing('stats')) {
- $wp_admin_bar->add_menu(
- array(
- 'parent' => 'top-secondary',
- 'id' => GLOBAL_NS.'-stats',
-
- 'title' => __('Cache Stats', SLUG_TD),
- 'href' => '#',
- 'meta' => array(
- 'class' => '-stats',
- 'tabindex' => -1,
- ),
- )
- );
- $wp_admin_bar->add_group(
- array(
- 'parent' => GLOBAL_NS.'-stats',
- 'id' => GLOBAL_NS.'-stats-wrapper',
-
- 'meta' => array(
- 'class' => '-wrapper',
- ),
- )
- );
- $wp_admin_bar->add_menu(
- array(
- 'parent' => GLOBAL_NS.'-stats-wrapper',
- 'id' => GLOBAL_NS.'-stats-container',
-
- 'title' => ''.
-
- ''.
- // ''.
-
- ''.
- '
'.__('Current Cache Totals', SLUG_TD).'
'.
- '
'.
- '
'.
- '
'.esc_html(basename(WP_CONTENT_DIR).'/'.$self->options['base_dir'].'/*').'
'.
- '
'.
-
- ''.
- '
'.__('Current Disk Health', SLUG_TD).'
'.
- '
'.__('total capacity', SLUG_TD).'
'.
- '
'.__('available', SLUG_TD).'
'.
- '
'.
-
- (current_user_can($self->cap) ?
- ''
- : '').
-
- '',
-
- 'meta' => array(
- 'class' => '-container',
- 'tabindex' => -1,
- ),
- )
- );
- }
-};
-
-/*
- * Injects `` tag w/ JSON-encoded data.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `admin_head` hook.
- */
-$self->adminBarMetaTags = function () use ($self) {
- if (!$self->adminBarShowing()) {
- return; // Nothing to do.
- }
- $vars = array(
- '_wpnonce' => wp_create_nonce(),
- 'isMultisite' => is_multisite(),
- 'currentUserHasCap' => current_user_can($self->cap),
- 'currentUserHasNetworkCap' => current_user_can($self->network_cap),
- 'htmlCompressorEnabled' => (boolean) $self->options['htmlc_enable'],
- 'ajaxURL' => site_url('/wp-load.php', is_ssl() ? 'https' : 'http'),
- 'i18n' => array(
- 'name' => NAME,
- 'perSymbol' => __('%', SLUG_TD),
- 'file' => __('file', SLUG_TD),
- 'files' => __('files', SLUG_TD),
- 'pageCache' => __('Page Cache', SLUG_TD),
- 'htmlCompressor' => __('HTML Compressor', SLUG_TD),
- 'currentTotal' => __('Current Total', SLUG_TD),
- 'currentSite' => __('Current Site', SLUG_TD),
- 'xDayHigh' => __('%s Day High', SLUG_TD),
- 'enterSpecificUrl' => __('Enter a specific URL to clear the cache for that page:', SLUG_TD),
- ),
- );
- echo ''."\n";
-};
-
-/*
- * Adds CSS for WordPress admin bar.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `wp_enqueue_scripts` hook.
- * @attaches-to `admin_enqueue_scripts` hook.
- */
-$self->adminBarStyles = function () use ($self) {
- if (!$self->adminBarShowing()) {
- return; // Nothing to do.
+ /*
+ * Injects `` tag w/ JSON-encoded data.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `admin_head` hook.
+ */
+ public function adminBarMetaTags()
+ {
+ if (!$this->adminBarShowing()) {
+ return; // Nothing to do.
+ }
+ $vars = [
+ '_wpnonce' => wp_create_nonce(),
+ 'isMultisite' => is_multisite(),
+ 'currentUserHasCap' => current_user_can($this->cap),
+ 'currentUserHasNetworkCap' => current_user_can($this->network_cap),
+ 'htmlCompressorEnabled' => (boolean) $this->options['htmlc_enable'],
+ 'ajaxURL' => site_url('/wp-load.php', is_ssl() ? 'https' : 'http'),
+ 'i18n' => [
+ 'name' => NAME,
+ 'perSymbol' => __('%', SLUG_TD),
+ 'file' => __('file', SLUG_TD),
+ 'files' => __('files', SLUG_TD),
+ 'pageCache' => __('Page Cache', SLUG_TD),
+ 'htmlCompressor' => __('HTML Compressor', SLUG_TD),
+ 'currentTotal' => __('Current Total', SLUG_TD),
+ 'currentSite' => __('Current Site', SLUG_TD),
+ 'xDayHigh' => __('%s Day High', SLUG_TD),
+ 'enterSpecificUrl' => __('Enter a specific URL to clear the cache for that page:', SLUG_TD),
+ ],
+ ];
+ echo ''."\n";
}
- $deps = array(); // Plugin dependencies.
-
- wp_enqueue_style(GLOBAL_NS.'-admin-bar', $self->url('/src/client-s/css/admin-bar.min.css'), $deps, VERSION, 'all');
-};
-
-/*
- * Adds JS for WordPress admin bar.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `wp_enqueue_scripts` hook.
- * @attaches-to `admin_enqueue_scripts` hook.
- */
-$self->adminBarScripts = function () use ($self) {
- if (!$self->adminBarShowing()) {
- return; // Nothing to do.
+
+ /*
+ * Adds CSS for WordPress admin bar.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `wp_enqueue_scripts` hook.
+ * @attaches-to `admin_enqueue_scripts` hook.
+ */
+ public function adminBarStyles()
+ {
+ if (!$this->adminBarShowing()) {
+ return; // Nothing to do.
+ }
+ $deps = []; // Plugin dependencies.
+
+ wp_enqueue_style(GLOBAL_NS.'-admin-bar', $this->url('/src/client-s/css/admin-bar.min.css'), $deps, VERSION, 'all');
}
- $deps = array('jquery', 'admin-bar'); // Plugin dependencies.
- if ($self->adminBarShowing('stats')) {
- $deps[] = 'chartjs'; // Add ChartJS dependency.
- wp_enqueue_script('chartjs', set_url_scheme('//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'), array(), null, true);
+ /*
+ * Adds JS for WordPress admin bar.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `wp_enqueue_scripts` hook.
+ * @attaches-to `admin_enqueue_scripts` hook.
+ */
+ public function adminBarScripts()
+ {
+ if (!$this->adminBarShowing()) {
+ return; // Nothing to do.
+ }
+ $deps = ['jquery', 'admin-bar']; // Plugin dependencies.
+
+ if ($this->adminBarShowing('stats')) {
+ $deps[] = 'chartjs'; // Add ChartJS dependency.
+ wp_enqueue_script('chartjs', set_url_scheme('//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'), [], null, true);
+ }
+ wp_enqueue_script(GLOBAL_NS.'-admin-bar', $this->url('/src/client-s/js/admin-bar.min.js'), $deps, VERSION, true);
}
- wp_enqueue_script(GLOBAL_NS.'-admin-bar', $self->url('/src/client-s/js/admin-bar.min.js'), $deps, VERSION, true);
-};
-/*[/pro]*/
+ /*[/pro]*/
+}
diff --git a/src/includes/traits/Plugin/AutoCacheUtils.php b/src/includes/traits/Plugin/AutoCacheUtils.php
index 9e377626..af0b3247 100644
--- a/src/includes/traits/Plugin/AutoCacheUtils.php
+++ b/src/includes/traits/Plugin/AutoCacheUtils.php
@@ -2,162 +2,169 @@
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Traits\Plugin;
-/*
- * Runs the auto-cache engine via CRON job.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `_cron_'.__GLOBAL_NS__.'_auto_cache`
- */
-$self->autoCache = function () use ($self) {
- if (!$self->options['enable']) {
- return; // Nothing to do.
- }
- if (!$self->options['auto_cache_enable']) {
- return; // Nothing to do.
- }
- if (!$self->options['auto_cache_sitemap_url']) {
- if (!$self->options['auto_cache_other_urls']) {
+trait AutoCacheUtils {
+ /*
+ * Runs the auto-cache engine via CRON job.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `_cron_'.__GLOBAL_NS__.'_auto_cache`
+ */
+ public function autoCache()
+ {
+ if (!$this->options['enable']) {
return; // Nothing to do.
}
+ if (!$this->options['auto_cache_enable']) {
+ return; // Nothing to do.
+ }
+ if (!$this->options['auto_cache_sitemap_url']) {
+ if (!$this->options['auto_cache_other_urls']) {
+ return; // Nothing to do.
+ }
+ }
+ if (!$this->autoCacheCheckPhpIni()) {
+ return; // Server does not meet minimum requirements.
+ }
+ new AutoCache();
}
- if (!$self->autoCacheCheckPhpIni()) {
- return; // Server does not meet minimum requirements.
- }
- new AutoCache();
-};
-/**
- * Check if PHP configuration meets minimum requirements for Auto-Cache Engine and remove old notice if necessary.
- *
- * @since 160103 Improving Auto-Cache Engine minimum PHP requirements reporting.
- *
- * @attaches-to `admin_init`
- */
-$self->autoCacheMaybeClearPhpIniError = function () use ($self) {
- if (!is_null($done = &$self->cacheKey('autoCacheMaybeClearPhpIniError'))) {
- return; // Already did this.
- }
- $done = true; // Flag as having been done.
+ /**
+ * Check if PHP configuration meets minimum requirements for Auto-Cache Engine and remove old notice if necessary.
+ *
+ * @since 160103 Improving Auto-Cache Engine minimum PHP requirements reporting.
+ *
+ * @attaches-to `admin_init`
+ */
+ public function autoCacheMaybeClearPhpIniError()
+ {
+ if (!is_null($done = &$this->cacheKey('autoCacheMaybeClearPhpIniError'))) {
+ return; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- if (!$self->options['enable']) {
- return; // Nothing to do.
- }
- if (!$self->options['auto_cache_enable']) {
- return; // Nothing to do.
+ if (!$this->options['enable']) {
+ return; // Nothing to do.
+ }
+ if (!$this->options['auto_cache_enable']) {
+ return; // Nothing to do.
+ }
+ $this->autoCacheCheckPhpIni();
}
- $self->autoCacheCheckPhpIni();
-};
-/**
- * Check if PHP configuration meets minimum requirements for Auto-Cache Engine and display a notice if necessary.
- *
- * @since 160103 Improving Auto-Cache Engine minimum PHP requirements reporting.
- *
- * @return bool `TRUE` if all required PHP configuration is present, else `FALSE`. This also creates a dashboard notice in some cases.
- *
- * @note Unlike `autoCacheCheckXmlSitemap()`, this routine is NOT used by the Auto-Cache Engine class when the Auto-Cache Engine is running.
- * However, this routine is called prior to running the Auto-Cache Engine, so caching here should be avoided (this gets called during
- * `admin_init` and prior to running the Auto-Cache Engine).
- */
-$self->autoCacheCheckPhpIni = function () use ($self) {
- if (!filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN)) { // Is allow_url_fopen=1?
- $self->dismissMainNotice('allow_url_fopen_disabled'); // Clear any previous allow_url_fopen notice.
- $self->enqueueMainNotice(
- sprintf(__('%1$s says... The Auto-Cache Engine requires PHP URL-aware fopen wrappers (allow_url_fopen=1
), however this option has been disabled by your php.ini
runtime configuration. Please contact your web hosting company to resolve this issue or disable the Auto-Cache Engine in the settings.', SLUG_TD), esc_html(NAME)),
- array('class' => 'error', 'persistent_key' => 'allow_url_fopen_disabled', 'dismissable' => false)
- );
- return false; // Nothing more we can do in this case.
+ /**
+ * Check if PHP configuration meets minimum requirements for Auto-Cache Engine and display a notice if necessary.
+ *
+ * @since 160103 Improving Auto-Cache Engine minimum PHP requirements reporting.
+ *
+ * @return bool `TRUE` if all required PHP configuration is present, else `FALSE`. This also creates a dashboard notice in some cases.
+ *
+ * @note Unlike `autoCacheCheckXmlSitemap()`, this routine is NOT used by the Auto-Cache Engine class when the Auto-Cache Engine is running.
+ * However, this routine is called prior to running the Auto-Cache Engine, so caching here should be avoided (this gets called during
+ * `admin_init` and prior to running the Auto-Cache Engine).
+ */
+ public function autoCacheCheckPhpIni()
+ {
+ if (!filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN)) { // Is allow_url_fopen=1?
+ $this->dismissMainNotice('allow_url_fopen_disabled'); // Clear any previous allow_url_fopen notice.
+ $this->enqueueMainNotice(
+ sprintf(__('%1$s says... The Auto-Cache Engine requires PHP URL-aware fopen wrappers (allow_url_fopen=1
), however this option has been disabled by your php.ini
runtime configuration. Please contact your web hosting company to resolve this issue or disable the Auto-Cache Engine in the settings.', SLUG_TD), esc_html(NAME)),
+ ['class' => 'error', 'persistent_key' => 'allow_url_fopen_disabled', 'dismissable' => false]
+ );
+ return false; // Nothing more we can do in this case.
+ }
+ $this->dismissMainNotice('allow_url_fopen_disabled'); // Any previous problems have been fixed; dismiss any existing failure notice
+
+ return true;
}
- $self->dismissMainNotice('allow_url_fopen_disabled'); // Any previous problems have been fixed; dismiss any existing failure notice
- return true;
-};
+ /**
+ * Check if Auto-Cache Engine XML Sitemap is valid and remove old notice if necessary.
+ *
+ * @since 151220 Improving XML Sitemap error checking.
+ *
+ * @attaches-to `admin_init`
+ */
+ public function autoCacheMaybeClearPrimaryXmlSitemapError()
+ {
+ if (!is_null($done = &$this->cacheKey('autoCacheMaybeClearPrimaryXmlSitemapError'))) {
+ return; // Already did this.
+ }
+ $done = true; // Flag as having been done.
-/**
- * Check if Auto-Cache Engine XML Sitemap is valid and remove old notice if necessary.
- *
- * @since 151220 Improving XML Sitemap error checking.
- *
- * @attaches-to `admin_init`
- */
-$self->autoCacheMaybeClearPrimaryXmlSitemapError = function () use ($self) {
- if (!is_null($done = &$self->cacheKey('autoCacheMaybeClearPrimaryXmlSitemapError'))) {
- return; // Already did this.
- }
- $done = true; // Flag as having been done.
+ if (!$this->options['enable']) {
+ return; // Nothing to do.
+ }
+ if (!$this->options['auto_cache_enable']) {
+ return; // Nothing to do.
+ }
+ if (!$this->options['auto_cache_sitemap_url']) {
+ return; // Nothing to do.
+ }
+ if (($last_checked = get_transient(GLOBAL_NS.'-'.md5($this->options['auto_cache_sitemap_url']))) && (time() <= ((int) $last_checked + HOUR_IN_SECONDS))) {
+ $this->dismissMainNotice('xml_sitemap_missing'); // Previous error was fixed; we only create transient when Sitemap passes validation
+ return; // Nothing to do; already checked within the last hour.
+ }
+ $is_multisite = is_multisite(); // Multisite network?
+ $can_consider_domain_mapping = $is_multisite && $this->canConsiderDomainMapping();
+ $blog_url = rtrim(network_home_url(''), '/');
- if (!$self->options['enable']) {
- return; // Nothing to do.
- }
- if (!$self->options['auto_cache_enable']) {
- return; // Nothing to do.
- }
- if (!$self->options['auto_cache_sitemap_url']) {
- return; // Nothing to do.
- }
- if(($last_checked = get_transient(GLOBAL_NS.'-'.md5($self->options['auto_cache_sitemap_url']))) && (time() <= ((int)$last_checked + HOUR_IN_SECONDS))) {
- $self->dismissMainNotice('xml_sitemap_missing'); // Previous error was fixed; we only create transient when Sitemap passes validation
- return; // Nothing to do; already checked within the last hour.
+ if ($is_multisite && $can_consider_domain_mapping) {
+ $blog_url = $this->domainMappingUrlFilter($blog_url);
+ }
+ if ($blog_url && ($blog_sitemap_path = ltrim($this->options['auto_cache_sitemap_url'], '/'))) {
+ $this->autoCacheCheckXmlSitemap($blog_url.'/'.$blog_sitemap_path, false, false);
+ }
}
- $is_multisite = is_multisite(); // Multisite network?
- $can_consider_domain_mapping = $is_multisite && $self->canConsiderDomainMapping();
- $blog_url = rtrim(network_home_url(''), '/');
- if ($is_multisite && $can_consider_domain_mapping) {
- $blog_url = $self->domainMappingUrlFilter($blog_url);
- }
- if ($blog_url && ($blog_sitemap_path = ltrim($self->options['auto_cache_sitemap_url'], '/'))) {
- $self->autoCacheCheckXmlSitemap($blog_url.'/'.$blog_sitemap_path, false, false);
- }
-};
+ /**
+ * Check if Auto-Cache Engine XML Sitemap is valid and display a notice if necessary.
+ *
+ * @since 151220 Improving XML Sitemap error checking.
+ *
+ * @param string $sitemap A URL to an XML sitemap file.
+ * This supports nested XML sitemap index files too; i.e. ``.
+ * Note that GZIP files are NOT supported at this time.
+ * @param bool $is_nested_sitemap Are we traversing a primary sitemap and now dealing with a nested sitemap?
+ * @param bool|null $is_child_blog Is this routine being called from a child blog?
+ *
+ * @return bool `TRUE` if there was no failure fetching XML Sitemap, else `FALSE`. This also creates a dashboard notice in some cases.
+ *
+ * @note This routine is also used by the AutoCache class when the Auto-Cache Engine is running.
+ */
+ public function autoCacheCheckXmlSitemap($sitemap, $is_nested_sitemap = false, $is_child_blog = null)
+ {
+ $failure = ''; // Initialize.
-/**
- * Check if Auto-Cache Engine XML Sitemap is valid and display a notice if necessary.
- *
- * @since 151220 Improving XML Sitemap error checking.
- *
- * @param string $sitemap A URL to an XML sitemap file.
- * This supports nested XML sitemap index files too; i.e. ``.
- * Note that GZIP files are NOT supported at this time.
- * @param bool $is_nested_sitemap Are we traversing a primary sitemap and now dealing with a nested sitemap?
- * @param bool|null $is_child_blog Is this routine being called from a child blog?
- *
- * @return bool `TRUE` if there was no failure fetching XML Sitemap, else `FALSE`. This also creates a dashboard notice in some cases.
- *
- * @note This routine is also used by the AutoCache class when the Auto-Cache Engine is running.
- */
-$self->autoCacheCheckXmlSitemap = function ($sitemap, $is_nested_sitemap = false, $is_child_blog = null) use ($self) {
- $failure = ''; // Initialize.
+ if (is_wp_error($head = wp_remote_head($sitemap, ['redirection' => 5]))) {
+ $failure = 'WP_Http says: '.$head->get_error_message().'.';
+ if (stripos($head->get_error_message(), 'timed out') !== false || stripos($head->get_error_message(), 'timeout') !== false) { // $head->get_error_code() only returns generic `http_request_failed`
+ $failure .= '
'.__('Note: Most timeout errors are resolved by refreshing the page and trying again. If timeout errors persist, please see this article.', SLUG_TD).'';
+ }
+ } elseif (empty($head['response']['code']) || (int) $head['response']['code'] >= 400) {
+ $failure = sprintf(__('HEAD response code (%1$s
) indicates an error.', SLUG_TD), esc_html((int) @$head['response']['code']));
+ } elseif (empty($head['headers']['content-type']) || stripos($head['headers']['content-type'], 'xml') === false) {
+ $failure = sprintf(__('Content-Type (%1$s
) indicates an error.', SLUG_TD), esc_html((string) @$head['headers']['content-type']));
+ }
+ if ($failure) { // Failure encountered above?
+ if (!$is_child_blog && !$is_nested_sitemap && $this->options['auto_cache_sitemap_url']) { // If this is a primary sitemap location.
+ $this->dismissMainNotice('xml_sitemap_missing'); // Clear any previous XML Sitemap notice, which may reference an old URL; see http://wsharks.com/1SAofhP
+ $this->enqueueMainNotice(
+ sprintf(__('%1$s says... The Auto-Cache Engine is currently configured with an XML Sitemap location that could not be found. We suggest that you install the Google XML Sitemaps plugin. Or, empty the XML Sitemap field and only use the list of URLs instead. See: Dashboard → %1$s → Auto-Cache Engine → XML Sitemap URL', SLUG_TD), esc_html(NAME)).'
'.
+ sprintf(__('Problematic Sitemap URL: %1$s / Diagnostic Report: %2$s', SLUG_TD), esc_html($sitemap), $failure),
+ ['class' => 'error', 'persistent_key' => 'xml_sitemap_missing', 'dismissable' => false]
+ );
+ delete_transient(GLOBAL_NS.'-'.md5($this->options['auto_cache_sitemap_url'])); // Ensures that we check the XML Sitemap URL again immediately until the issue is fixed
+ }
+ return false; // Nothing more we can do in this case.
+ }
- if (is_wp_error($head = wp_remote_head($sitemap, array('redirection' => 5)))) {
- $failure = 'WP_Http says: '.$head->get_error_message().'.';
- if(stripos($head->get_error_message(), 'timed out') !== false || stripos($head->get_error_message(), 'timeout') !== false) { // $head->get_error_code() only returns generic `http_request_failed`
- $failure .= '
'.__('Note: Most timeout errors are resolved by refreshing the page and trying again. If timeout errors persist, please see this article.', SLUG_TD).'';
- }
- } elseif (empty($head['response']['code']) || (int)$head['response']['code'] >= 400) {
- $failure = sprintf(__('HEAD response code (%1$s
) indicates an error.', SLUG_TD), esc_html((int)@$head['response']['code']));
- } elseif (empty($head['headers']['content-type']) || stripos($head['headers']['content-type'], 'xml') === false) {
- $failure = sprintf(__('Content-Type (%1$s
) indicates an error.', SLUG_TD), esc_html((string)@$head['headers']['content-type']));
- }
- if ($failure) { // Failure encountered above?
- if (!$is_child_blog && !$is_nested_sitemap && $self->options['auto_cache_sitemap_url']) { // If this is a primary sitemap location.
- $self->dismissMainNotice('xml_sitemap_missing'); // Clear any previous XML Sitemap notice, which may reference an old URL; see http://wsharks.com/1SAofhP
- $self->enqueueMainNotice(
- sprintf(__('%1$s says... The Auto-Cache Engine is currently configured with an XML Sitemap location that could not be found. We suggest that you install the Google XML Sitemaps plugin. Or, empty the XML Sitemap field and only use the list of URLs instead. See: Dashboard → %1$s → Auto-Cache Engine → XML Sitemap URL', SLUG_TD), esc_html(NAME)).'
'.
- sprintf(__('Problematic Sitemap URL: %1$s / Diagnostic Report: %2$s', SLUG_TD), esc_html($sitemap), $failure),
- array('class' => 'error', 'persistent_key' => 'xml_sitemap_missing', 'dismissable' => false)
- );
- delete_transient(GLOBAL_NS.'-'.md5($self->options['auto_cache_sitemap_url'])); // Ensures that we check the XML Sitemap URL again immediately until the issue is fixed
+ if (!$is_child_blog && !$is_nested_sitemap) { // Any previous problems have been fixed; dismiss any existing failure notice
+ $this->dismissMainNotice('xml_sitemap_missing');
+ set_transient(GLOBAL_NS.'-'.md5($this->options['auto_cache_sitemap_url']), time(), WEEK_IN_SECONDS); // Reduce repeated validation attempts.
}
- return false; // Nothing more we can do in this case.
- }
- if (!$is_child_blog && !$is_nested_sitemap) { // Any previous problems have been fixed; dismiss any existing failure notice
- $self->dismissMainNotice('xml_sitemap_missing');
- set_transient(GLOBAL_NS.'-'.md5($self->options['auto_cache_sitemap_url']), time(), WEEK_IN_SECONDS); // Reduce repeated validation attempts.
+ return true;
}
-
- return true;
-};
-/*[/pro]*/
+ /*[/pro]*/
+}
diff --git a/src/includes/traits/Plugin/BbPressUtils.php b/src/includes/traits/Plugin/BbPressUtils.php
index 70526ed9..92aa59d0 100644
--- a/src/includes/traits/Plugin/BbPressUtils.php
+++ b/src/includes/traits/Plugin/BbPressUtils.php
@@ -1,61 +1,66 @@
isBbPressActive = function () use ($self) {
- return class_exists('bbPress');
-};
-
-/*
- * bbPress post types.
- *
- * @since 150821 Improving bbPress support.
- *
- * @return array All bbPress post types.
- */
-$self->bbPressPostTypes = function () use ($self) {
- if (!$self->isBbPressActive()) {
- return array();
- }
- if (!is_null($types = &$self->cacheKey('bbPressPostTypes'))) {
- return $types; // Already did this.
+trait BbPressUtils {
+ /*
+ * Is bbPress active?
+ *
+ * @since 150821 Improving bbPress support.
+ *
+ * @return bool `TRUE` if bbPress is active.
+ */
+ public function isBbPressActive()
+ {
+ return class_exists('bbPress');
}
- $types = array(); // Initialize.
- $types[] = bbp_get_forum_post_type();
- $types[] = bbp_get_topic_post_type();
- $types[] = bbp_get_reply_post_type();
- return $types;
-};
+ /*
+ * bbPress post types.
+ *
+ * @since 150821 Improving bbPress support.
+ *
+ * @return array All bbPress post types.
+ */
+ public function bbPressPostTypes()
+ {
+ if (!$this->isBbPressActive()) {
+ return [];
+ }
+ if (!is_null($types = &$this->cacheKey('bbPressPostTypes'))) {
+ return $types; // Already did this.
+ }
+ $types = []; // Initialize.
+ $types[] = bbp_get_forum_post_type();
+ $types[] = bbp_get_topic_post_type();
+ $types[] = bbp_get_reply_post_type();
-/*
- * bbPress post statuses.
- *
- * @since 150821 Improving bbPress support.
- *
- * @return array All bbPress post statuses.
- */
-$self->bbPressStatuses = function () use ($self) {
- if (!$self->isBbPressActive()) {
- return array();
- }
- if (!is_null($statuses = &$self->cacheKey('bbPressStatuses'))) {
- return $statuses; // Already did this.
+ return $types;
}
- $statuses = array(); // Initialize.
- foreach (get_post_stati(array(), 'objects') as $_key => $_status) {
- if (isset($_status->label_count['domain']) && $_status->label_count['domain'] === 'bbpress') {
- $statuses[] = $_status->name;
+ /*
+ * bbPress post statuses.
+ *
+ * @since 150821 Improving bbPress support.
+ *
+ * @return array All bbPress post statuses.
+ */
+ public function bbPressStatuses()
+ {
+ if (!$this->isBbPressActive()) {
+ return [];
}
- }
- unset($_key, $_status); // Housekeeping.
+ if (!is_null($statuses = &$this->cacheKey('bbPressStatuses'))) {
+ return $statuses; // Already did this.
+ }
+ $statuses = []; // Initialize.
- return $statuses;
-};
+ foreach (get_post_stati([], 'objects') as $_key => $_status) {
+ if (isset($_status->label_count['domain']) && $_status->label_count['domain'] === 'bbpress') {
+ $statuses[] = $_status->name;
+ }
+ }
+ unset($_key, $_status); // Housekeeping.
+
+ return $statuses;
+ }
+}
diff --git a/src/includes/traits/Plugin/CdnUtils.php b/src/includes/traits/Plugin/CdnUtils.php
index dfba836c..0e3d54f3 100644
--- a/src/includes/traits/Plugin/CdnUtils.php
+++ b/src/includes/traits/Plugin/CdnUtils.php
@@ -2,18 +2,22 @@
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Traits\Plugin;
-/*
- * Bumps CDN invalidation counter.
- *
- * @since 150422 Rewrite.
- */
-$self->bumpCdnInvalidationCounter = function () use ($self) {
- if (!$self->options['enable']) {
- return; // Nothing to do.
- }
- if (!$self->options['cdn_enable']) {
- return; // Nothing to do.
+trait CdnUtils {
+
+ /*
+ * Bumps CDN invalidation counter.
+ *
+ * @since 150422 Rewrite.
+ */
+ public function bumpCdnInvalidationCounter()
+ {
+ if (!$this->options['enable']) {
+ return; // Nothing to do.
+ }
+ if (!$this->options['cdn_enable']) {
+ return; // Nothing to do.
+ }
+ $this->updateOptions(['cdn_invalidation_counter' => ++$this->options['cdn_invalidation_counter']]);
}
- $self->updateOptions(array('cdn_invalidation_counter' => ++$self->options['cdn_invalidation_counter']));
-};
-/*[/pro]*/
+ /*[/pro]*/
+}
diff --git a/src/includes/traits/Plugin/CleanupUtils.php b/src/includes/traits/Plugin/CleanupUtils.php
index 5ffa7085..3f73d153 100644
--- a/src/includes/traits/Plugin/CleanupUtils.php
+++ b/src/includes/traits/Plugin/CleanupUtils.php
@@ -1,30 +1,33 @@
cleanupCache = function () use ($self) {
- if (!$self->options['enable']) {
- return; // Nothing to do.
- }
- /*[pro strip-from="lite"]*/
- if ($self->options['cache_max_age_disable_if_load_average_is_gte'] && ($load_averages = $self->sysLoadAverages())) {
- if (max($load_averages) >= $self->options['cache_max_age_disable_if_load_average_is_gte']) {
- return; // Don't expire the cache when load average is high.
+trait CleanupUtils {
+ /*
+ * Runs cleanup routine via CRON job.
+ *
+ * @since 151002 While working on directory stats.
+ *
+ * @attaches-to `'_cron_'.__GLOBAL_NS__.'_cleanup'`
+ */
+ public function cleanupCache()
+ {
+ if (!$this->options['enable']) {
+ return; // Nothing to do.
}
- }
- /*[/pro]*/
+ /*[pro strip-from="lite"]*/
+ if ($this->options['cache_max_age_disable_if_load_average_is_gte'] && ($load_averages = $this->sysLoadAverages())) {
+ if (max($load_averages) >= $this->options['cache_max_age_disable_if_load_average_is_gte']) {
+ return; // Don't expire the cache when load average is high.
+ }
+ }
+ /*[/pro]*/
- /*[pro strip-from="lite"]*/
- if ($self->options['stats_enable']) {
- $dir_stats = DirStats::instance();
- $dir_stats->forCache(true);
+ /*[pro strip-from="lite"]*/
+ if ($this->options['stats_enable']) {
+ $dir_stats = DirStats::instance();
+ $dir_stats->forCache(true);
+ }
+ /*[/pro]*/
+ $this->wurgeCache(); // Purge now.
}
- /*[/pro]*/
- $self->wurgeCache(); // Purge now.
-};
+}
diff --git a/src/includes/traits/Plugin/CondUtils.php b/src/includes/traits/Plugin/CondUtils.php
index d5e3bcd9..888b21f3 100644
--- a/src/includes/traits/Plugin/CondUtils.php
+++ b/src/includes/traits/Plugin/CondUtils.php
@@ -1,13 +1,16 @@
isProPreview = function () use ($self) {
- return !empty($_REQUEST[GLOBAL_NS.'_pro_preview']);
-};
+trait CondUtils {
+ /*
+ * Is pro preview?
+ *
+ * @since 150511 Rewrite.
+ *
+ * @return bool `TRUE` if it's a pro preview.
+ */
+ public function isProPreview()
+ {
+ return !empty($_REQUEST[GLOBAL_NS.'_pro_preview']);
+ }
+}
diff --git a/src/includes/traits/Plugin/CronUtils.php b/src/includes/traits/Plugin/CronUtils.php
index cacdd3d4..476383e2 100644
--- a/src/includes/traits/Plugin/CronUtils.php
+++ b/src/includes/traits/Plugin/CronUtils.php
@@ -1,89 +1,94 @@
extendCronSchedules = function ($schedules) use ($self) {
- $schedules['every15m'] = array(
- 'interval' => 900,
- 'display' => __('Every 15 Minutes', SLUG_TD),
- );
- return $schedules;
-};
+trait CronUtils {
+ /*
+ * Extends WP-Cron schedules.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `cron_schedules` filter.
+ *
+ * @param array $schedules An array of the current schedules.
+ *
+ * @return array Revised array of WP-Cron schedules.
+ */
+ public function extendCronSchedules($schedules)
+ {
+ $schedules['every15m'] = [
+ 'interval' => 900,
+ 'display' => __('Every 15 Minutes', SLUG_TD),
+ ];
+ return $schedules;
+ }
-/*
- * Checks Cron setup, validates schedules, and reschedules events if necessary.
- *
- * @attaches-to `init` hook.
- *
- * @since 151220 Improving WP Cron setup and validation of schedules
- */
-$self->checkCronSetup = function () use ($self) {
- if ($self->options['crons_setup'] < 1439005906
- || $self->options['crons_setup_on_namespace'] !== __NAMESPACE__
- || $self->options['crons_setup_with_cache_cleanup_schedule'] !== $self->options['cache_cleanup_schedule']
- || $self->options['crons_setup_on_wp_with_schedules'] !== sha1(serialize(wp_get_schedules()))
- || !wp_next_scheduled('_cron_'.GLOBAL_NS.'_cleanup')
- /*[pro strip-from="lite"]*/ // Auto-cache engine.
- || !wp_next_scheduled('_cron_'.GLOBAL_NS.'_auto_cache')
- /*[/pro]*/
- ) {
+ /*
+ * Checks Cron setup, validates schedules, and reschedules events if necessary.
+ *
+ * @attaches-to `init` hook.
+ *
+ * @since 151220 Improving WP Cron setup and validation of schedules
+ */
+ public function checkCronSetup()
+ {
+ if ($this->options['crons_setup'] < 1439005906
+ || $this->options['crons_setup_on_namespace'] !== __NAMESPACE__
+ || $this->options['crons_setup_with_cache_cleanup_schedule'] !== $this->options['cache_cleanup_schedule']
+ || $this->options['crons_setup_on_wp_with_schedules'] !== sha1(serialize(wp_get_schedules()))
+ || !wp_next_scheduled('_cron_'.GLOBAL_NS.'_cleanup')
+ /*[pro strip-from="lite"]*/ // Auto-cache engine.
+ || !wp_next_scheduled('_cron_'.GLOBAL_NS.'_auto_cache')
+ /*[/pro]*/
+ ) {
- wp_clear_scheduled_hook('_cron_'.GLOBAL_NS.'_cleanup');
- wp_schedule_event(time() + 60, $self->options['cache_cleanup_schedule'], '_cron_'.GLOBAL_NS.'_cleanup');
+ wp_clear_scheduled_hook('_cron_'.GLOBAL_NS.'_cleanup');
+ wp_schedule_event(time() + 60, $this->options['cache_cleanup_schedule'], '_cron_'.GLOBAL_NS.'_cleanup');
- /*[pro strip-from="lite"]*/ // Auto-cache engine.
- wp_clear_scheduled_hook('_cron_'.GLOBAL_NS.'_auto_cache');
- wp_schedule_event(time() + 60, 'every15m', '_cron_'.GLOBAL_NS.'_auto_cache');
- /*[/pro]*/
+ /*[pro strip-from="lite"]*/ // Auto-cache engine.
+ wp_clear_scheduled_hook('_cron_'.GLOBAL_NS.'_auto_cache');
+ wp_schedule_event(time() + 60, 'every15m', '_cron_'.GLOBAL_NS.'_auto_cache');
+ /*[/pro]*/
- $self->updateOptions(
- array(
- 'crons_setup' => time(),
- 'crons_setup_on_namespace' => __NAMESPACE__,
- 'crons_setup_with_cache_cleanup_schedule' => $self->options['cache_cleanup_schedule'],
- 'crons_setup_on_wp_with_schedules' => sha1(serialize(wp_get_schedules()))
- )
- );
+ $this->updateOptions(
+ [
+ 'crons_setup' => time(),
+ 'crons_setup_on_namespace' => __NAMESPACE__,
+ 'crons_setup_with_cache_cleanup_schedule' => $this->options['cache_cleanup_schedule'],
+ 'crons_setup_on_wp_with_schedules' => sha1(serialize(wp_get_schedules())),
+ ]
+ );
+ }
}
-};
-/*
- * Resets `crons_setup` and clears WP-Cron schedules.
- *
- * @since 151220 Fixing bug with Auto-Cache Engine cron disappearing in some scenarios
- *
- * @note This MUST happen upon uninstall and deactivation due to buggy WP_Cron behavior. Events with a custom schedule will disappear when plugin is not active (see http://bit.ly/1lGdr78).
- */
-$self->resetCronSetup = function ( ) use ($self) {
- if (is_multisite()) { // Main site CRON jobs.
- switch_to_blog(get_current_site()->blog_id);
- /*[pro strip-from="lite"]*/ // Auto-cache engine.
- wp_clear_scheduled_hook('_cron_'.GLOBAL_NS.'_auto_cache');
- /*[/pro]*/
- wp_clear_scheduled_hook('_cron_'.GLOBAL_NS.'_cleanup');
- restore_current_blog(); // Restore current blog.
- } else { // Standard WP installation.
- /*[pro strip-from="lite"]*/ // Auto-cache engine.
- wp_clear_scheduled_hook('_cron_'.GLOBAL_NS.'_auto_cache');
- /*[/pro]*/
- wp_clear_scheduled_hook('_cron_'.GLOBAL_NS.'_cleanup');
+ /*
+ * Resets `crons_setup` and clears WP-Cron schedules.
+ *
+ * @since 151220 Fixing bug with Auto-Cache Engine cron disappearing in some scenarios
+ *
+ * @note This MUST happen upon uninstall and deactivation due to buggy WP_Cron behavior. Events with a custom schedule will disappear when plugin is not active (see http://bit.ly/1lGdr78).
+ */
+ public function resetCronSetup()
+ {
+ if (is_multisite()) { // Main site CRON jobs.
+ switch_to_blog(get_current_site()->blog_id);
+ /*[pro strip-from="lite"]*/ // Auto-cache engine.
+ wp_clear_scheduled_hook('_cron_'.GLOBAL_NS.'_auto_cache');
+ /*[/pro]*/
+ wp_clear_scheduled_hook('_cron_'.GLOBAL_NS.'_cleanup');
+ restore_current_blog(); // Restore current blog.
+ } else { // Standard WP installation.
+ /*[pro strip-from="lite"]*/ // Auto-cache engine.
+ wp_clear_scheduled_hook('_cron_'.GLOBAL_NS.'_auto_cache');
+ /*[/pro]*/
+ wp_clear_scheduled_hook('_cron_'.GLOBAL_NS.'_cleanup');
+ }
+ $this->updateOptions(
+ [ // Reset so that crons are rescheduled upon next activation
+ 'crons_setup' => $this->default_options['crons_setup'],
+ 'crons_setup_on_namespace' => $this->default_options['crons_setup_on_namespace'],
+ 'crons_setup_with_cache_cleanup_schedule' => $this->default_options['crons_setup_with_cache_cleanup_schedule'],
+ 'crons_setup_on_wp_with_schedules' => $this->default_options['crons_setup_on_wp_with_schedules'],
+ ]
+ );
}
- $self->updateOptions(
- array( // Reset so that crons are rescheduled upon next activation
- 'crons_setup' => $self->default_options['crons_setup'],
- 'crons_setup_on_namespace' => $self->default_options['crons_setup_on_namespace'],
- 'crons_setup_with_cache_cleanup_schedule' => $self->default_options['crons_setup_with_cache_cleanup_schedule'],
- 'crons_setup_on_wp_with_schedules' => $self->default_options['crons_setup_on_wp_with_schedules']
- )
- );
-};
+}
diff --git a/src/includes/traits/Plugin/DbUtils.php b/src/includes/traits/Plugin/DbUtils.php
index 294e0e14..df8eb727 100644
--- a/src/includes/traits/Plugin/DbUtils.php
+++ b/src/includes/traits/Plugin/DbUtils.php
@@ -1,13 +1,16 @@
wpdb = function () use ($self) {
- return $GLOBALS['wpdb'];
-};
+trait DbUtils {
+ /*
+ * WordPress database instance.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return \wpdb Reference for IDEs.
+ */
+ public function wpdb()
+ {
+ return $GLOBALS['wpdb'];
+ }
+}
diff --git a/src/includes/traits/Plugin/DirUtils.php b/src/includes/traits/Plugin/DirUtils.php
index 067a7597..fdfd4cdc 100644
--- a/src/includes/traits/Plugin/DirUtils.php
+++ b/src/includes/traits/Plugin/DirUtils.php
@@ -1,79 +1,84 @@
wpContentBaseDirTo = function ($rel_dir_file) use ($self) {
- $rel_dir_file = trim((string) $rel_dir_file, '\\/'." \t\n\r\0\x0B");
+trait DirUtils {
+ /*
+ * This constructs an absolute server directory path (no trailing slashes);
+ * which is always nested into {@link \WP_CONTENT_DIR} and the configured `base_dir` option value.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $rel_dir_file A sub-directory or file; relative location please.
+ *
+ * @throws \Exception If `base_dir` is empty when this method is called upon;
+ * i.e. if you attempt to call upon this method before {@link setup()} runs.
+ *
+ * @return string The full absolute server path to `$rel_dir_file`.
+ */
+ public function wpContentBaseDirTo($rel_dir_file)
+ {
+ $rel_dir_file = trim((string) $rel_dir_file, '\\/'." \t\n\r\0\x0B");
- if (empty($self->options['base_dir'])) {
- throw new \Exception(__('Missing `base_dir` option value.', SLUG_TD));
- }
- $wp_content_base_dir_to = WP_CONTENT_DIR.'/'.$self->options['base_dir'];
+ if (empty($this->options['base_dir'])) {
+ throw new \Exception(__('Missing `base_dir` option value.', SLUG_TD));
+ }
+ $wp_content_base_dir_to = WP_CONTENT_DIR.'/'.$this->options['base_dir'];
- if (isset($rel_dir_file[0])) {
- $wp_content_base_dir_to .= '/'.$rel_dir_file;
+ if (isset($rel_dir_file[0])) {
+ $wp_content_base_dir_to .= '/'.$rel_dir_file;
+ }
+ return $wp_content_base_dir_to;
}
- return $wp_content_base_dir_to;
-};
-/*
- * This constructs a relative/base directory path (no leading/trailing slashes).
- * Always relative to {@link \WP_CONTENT_DIR}. Depends on the configured `base_dir` option value.
- *
- * @since 150422 Rewrite.
- *
- * @param string $rel_dir_file A sub-directory or file; relative location please.
- *
- * @throws \Exception If `base_dir` is empty when this method is called upon;
- * i.e. if you attempt to call upon this method before {@link setup()} runs.
- *
- * @return string The relative/base directory path to `$rel_dir_file`.
- */
-$self->basePathTo = function ($rel_dir_file) use ($self) {
- $rel_dir_file = trim((string) $rel_dir_file, '\\/'." \t\n\r\0\x0B");
+ /*
+ * This constructs a relative/base directory path (no leading/trailing slashes).
+ * Always relative to {@link \WP_CONTENT_DIR}. Depends on the configured `base_dir` option value.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $rel_dir_file A sub-directory or file; relative location please.
+ *
+ * @throws \Exception If `base_dir` is empty when this method is called upon;
+ * i.e. if you attempt to call upon this method before {@link setup()} runs.
+ *
+ * @return string The relative/base directory path to `$rel_dir_file`.
+ */
+ public function basePathTo($rel_dir_file)
+ {
+ $rel_dir_file = trim((string) $rel_dir_file, '\\/'." \t\n\r\0\x0B");
- if (empty($self->options['base_dir'])) {
- throw new \Exception(__('Missing `base_dir` option value.', SLUG_TD));
- }
- $base_path_to = $self->options['base_dir'];
+ if (empty($this->options['base_dir'])) {
+ throw new \Exception(__('Missing `base_dir` option value.', SLUG_TD));
+ }
+ $base_path_to = $this->options['base_dir'];
- if (isset($rel_dir_file[0])) {
- $base_path_to .= '/'.$rel_dir_file;
+ if (isset($rel_dir_file[0])) {
+ $base_path_to .= '/'.$rel_dir_file;
+ }
+ return $base_path_to;
}
- return $base_path_to;
-};
-/**
- * Get the absolute filesystem path to the root of the WordPress installation
- *
- * Copied verbatim from get_home_path() in wp-admin/includes/file.php
- *
- * @since 151114 Adding `.htaccess` tweaks.
- *
- * @return string Full filesystem path to the root of the WordPress installation
- */
-$self->wpHomePath = function () use ($self) {
- $home = set_url_scheme( get_option( 'home' ), 'http' );
- $siteurl = set_url_scheme( get_option( 'siteurl' ), 'http' );
- if ( ! empty( $home ) && 0 !== strcasecmp( $home, $siteurl ) ) {
- $wp_path_rel_to_home = str_ireplace( $home, '', $siteurl ); /* $siteurl - $home */
- $pos = strripos( str_replace( '\\', '/', $_SERVER['SCRIPT_FILENAME'] ), trailingslashit( $wp_path_rel_to_home ) );
- $home_path = substr( $_SERVER['SCRIPT_FILENAME'], 0, $pos );
- $home_path = trailingslashit( $home_path );
- } else {
- $home_path = ABSPATH;
+ /**
+ * Get the absolute filesystem path to the root of the WordPress installation
+ *
+ * Copied verbatim from get_home_path() in wp-admin/includes/file.php
+ *
+ * @since 151114 Adding `.htaccess` tweaks.
+ *
+ * @return string Full filesystem path to the root of the WordPress installation
+ */
+ public function wpHomePath()
+ {
+ $home = set_url_scheme(get_option('home'), 'http');
+ $siteurl = set_url_scheme(get_option('siteurl'), 'http');
+ if (!empty($home) && 0 !== strcasecmp($home, $siteurl)) {
+ $wp_path_rel_to_home = str_ireplace($home, '', $siteurl); /* $siteurl - $home */
+ $pos = strripos(str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']), trailingslashit($wp_path_rel_to_home));
+ $home_path = substr($_SERVER['SCRIPT_FILENAME'], 0, $pos);
+ $home_path = trailingslashit($home_path);
+ } else {
+ $home_path = ABSPATH;
+ }
+ return str_replace('\\', '/', $home_path);
}
- return str_replace( '\\', '/', $home_path );
-};
+}
diff --git a/src/includes/traits/Plugin/HtaccessUtils.php b/src/includes/traits/Plugin/HtaccessUtils.php
index 676135fe..4987feeb 100644
--- a/src/includes/traits/Plugin/HtaccessUtils.php
+++ b/src/includes/traits/Plugin/HtaccessUtils.php
@@ -1,279 +1,289 @@
addWpHtaccess = function () use ($self) {
- global $is_apache;
+ /*
+ * Add template blocks to `/.htaccess` file.
+ *
+ * @since 151114 Adding `.htaccess` tweaks.
+ *
+ * @return boolean True if added successfully.
+ *
+ * @TODO Improve error reporting detail to better catch unexpected failures; see http://git.io/vEFLT
+ */
+ public function addWpHtaccess()
+ {
+ global $is_apache;
- if (!$is_apache) {
- return false; // Not running the Apache web server.
- }
- if (!$self->options['enable']) {
- return true; // Nothing to do.
- }
- if (!$self->needHtaccessRules()) {
- if($self->findHtaccessMarker()) { // Do we need to clean up previously added rules?
- $self->removeWpHtaccess(); // Fail silently since we don't need rules in place.
+ if (!$is_apache) {
+ return false; // Not running the Apache web server.
+ }
+ if (!$this->options['enable']) {
+ return true; // Nothing to do.
+ }
+ if (!$this->needHtaccessRules()) {
+ if ($this->findHtaccessMarker()) { // Do we need to clean up previously added rules?
+ $this->removeWpHtaccess(); // Fail silently since we don't need rules in place.
+ }
+ return true; // Nothing to do; no options enabled that require htaccess rules.
+ }
+ if (!$this->removeWpHtaccess()) {
+ return false; // Unable to remove.
+ }
+ if (!($htaccess = $this->readHtaccessFile())) {
+ return false; // Failure; could not read file or invalid UTF8 encountered, file may be corrupt.
}
- return true; // Nothing to do; no options enabled that require htaccess rules.
- }
- if (!$self->removeWpHtaccess()) {
- return false; // Unable to remove.
- }
- if (!($htaccess = $self->readHtaccessFile())) {
- return false; // Failure; could not read file or invalid UTF8 encountered, file may be corrupt.
- }
- $template_blocks = ''; // Initialize.
- if (is_dir($templates_dir = dirname(dirname(dirname(__FILE__))).'/templates/htaccess')) {
- foreach (scandir($templates_dir) as $_template_file) {
- switch ($_template_file) {
- /*[pro strip-from="lite"]*/
- case 'cdn-filters.txt':
- if ($self->options['cdn_enable']) {
- $template_blocks .= trim(file_get_contents($templates_dir.'/'.$_template_file))."\n";
- } // Only if CDN filters are enabled at this time.
- break;
- /*[/pro]*/
+ $template_blocks = ''; // Initialize.
+ if (is_dir($templates_dir = dirname(dirname(dirname(__FILE__))).'/templates/htaccess')) {
+ foreach (scandir($templates_dir) as $_template_file) {
+ switch ($_template_file) {
+ /*[pro strip-from="lite"]*/
+ case 'cdn-filters.txt':
+ if ($this->options['cdn_enable']) {
+ $template_blocks .= trim(file_get_contents($templates_dir.'/'.$_template_file))."\n";
+ } // Only if CDN filters are enabled at this time.
+ break;
+ /*[/pro]*/
+ }
}
+ unset($_template_file); // Housekeeping.
}
- unset($_template_file); // Housekeeping.
- }
- if(empty($template_blocks)) { // Do we need to add anything to htaccess?
- $self->closeHtaccessFile($htaccess); // No need to write to htaccess file in this case.
- return true; // Nothing to do, but no failures either.
- }
+ if (empty($template_blocks)) { // Do we need to add anything to htaccess?
+ $this->closeHtaccessFile($htaccess); // No need to write to htaccess file in this case.
+ return true; // Nothing to do, but no failures either.
+ }
+
+ $template_header = '# BEGIN '.NAME.' '.$this->htaccess_marker.' (the '.$this->htaccess_marker.' marker is required for '.NAME.'; do not remove)'."\n";
+ $template_footer = '# END '.NAME.' '.$this->htaccess_marker;
+ $htaccess['file_contents'] = $template_header.trim($template_blocks)."\n".$template_footer."\n\n".$htaccess['file_contents'];
- $template_header = '# BEGIN '.NAME.' '.$self->htaccess_marker.' (the '.$self->htaccess_marker.' marker is required for '.NAME.'; do not remove)'."\n";
- $template_footer = '# END '.NAME.' '.$self->htaccess_marker;
- $htaccess['file_contents'] = $template_header.trim($template_blocks)."\n".$template_footer."\n\n".$htaccess['file_contents'];
+ if (!$this->writeHtaccessFile($htaccess, true)) {
+ return false; // Failure; could not write changes.
+ }
- if (!$self->writeHtaccessFile($htaccess, true)) {
- return false; // Failure; could not write changes.
+ return true; // Added successfully.
}
- return true; // Added successfully.
-};
+ /*
+ * Remove template blocks from `/.htaccess` file.
+ *
+ * @since 151114 Adding `.htaccess` tweaks.
+ *
+ * @return boolean True if removed successfully.
+ *
+ * @TODO Improve error reporting detail to better catch unexpected failures; see http://git.io/vEFLT
+ */
+ public function removeWpHtaccess()
+ {
+ global $is_apache;
-/*
- * Remove template blocks from `/.htaccess` file.
- *
- * @since 151114 Adding `.htaccess` tweaks.
- *
- * @return boolean True if removed successfully.
- *
- * @TODO Improve error reporting detail to better catch unexpected failures; see http://git.io/vEFLT
- */
-$self->removeWpHtaccess = function () use ($self) {
- global $is_apache;
+ if (!$is_apache) {
+ return false; // Not running the Apache web server.
+ }
+ if (!($htaccess_file = $this->findHtaccessFile())) {
+ return true; // File does not exist.
+ }
+ if (!$this->findHtaccessMarker()) {
+ return true; // Template blocks are already gone.
+ }
+ if (!($htaccess = $this->readHtaccessFile())) {
+ return false; // Failure; could not read file, create file, or invalid UTF8 encountered, file may be corrupt.
+ }
- if (!$is_apache) {
- return false; // Not running the Apache web server.
- }
- if (!($htaccess_file = $self->findHtaccessFile())) {
- return true; // File does not exist.
- }
- if (!$self->findHtaccessMarker()) {
- return true; // Template blocks are already gone.
- }
- if (!($htaccess = $self->readHtaccessFile())) {
- return false; // Failure; could not read file, create file, or invalid UTF8 encountered, file may be corrupt.
- }
+ $regex = '/#\s*BEGIN\s+'.preg_quote(NAME, '/').'\s+'.$this->htaccess_marker.'.*?#\s*END\s+'.preg_quote(NAME, '/').'\s+'.$this->htaccess_marker.'\s*/is';
+ $htaccess['file_contents'] = preg_replace($regex, '', $htaccess['file_contents']);
- $regex = '/#\s*BEGIN\s+'.preg_quote(NAME, '/').'\s+'.$self->htaccess_marker.'.*?#\s*END\s+'.preg_quote(NAME, '/').'\s+'.$self->htaccess_marker.'\s*/is';
- $htaccess['file_contents'] = preg_replace($regex, '', $htaccess['file_contents']);
+ if (!$this->writeHtaccessFile($htaccess, false)) {
+ return false; // Failure; could not write changes.
+ }
- if (!$self->writeHtaccessFile($htaccess, false)) {
- return false; // Failure; could not write changes.
+ return true; // Removed successfully.
}
- return true; // Removed successfully.
-};
+ /*
+ * Finds absolute server path to `/.htaccess` file.
+ *
+ * @since 151114 Adding `.htaccess` tweaks.
+ *
+ * @return string Absolute server path to `/.htaccess` file;
+ * else an empty string if unable to locate the file.
+ */
+ public function findHtaccessFile()
+ {
+ $file = ''; // Initialize.
+ $home_path = $this->wpHomePath();
-/*
- * Finds absolute server path to `/.htaccess` file.
- *
- * @since 151114 Adding `.htaccess` tweaks.
- *
- * @return string Absolute server path to `/.htaccess` file;
- * else an empty string if unable to locate the file.
- */
-$self->findHtaccessFile = function () use ($self) {
- $file = ''; // Initialize.
- $home_path = $self->wpHomePath();
-
- if (is_file($htaccess_file = $home_path.'.htaccess')) {
- $file = $htaccess_file;
+ if (is_file($htaccess_file = $home_path.'.htaccess')) {
+ $file = $htaccess_file;
+ }
+ return $file;
}
- return $file;
-};
-/*
- * Determines if there are any plugin options enabled that require htaccess rules to be added.
- *
- * @since 160103 Improving `.htaccess` tweaks.
- *
- * @return bool True when an option is enabled that requires htaccess rules, false otherwise.
- */
-$self->needHtaccessRules = function () use ($self) {
- if(!is_array($self->options_with_htaccess_rules)) {
- return false; // Nothing to do.
- }
- foreach ($self->options_with_htaccess_rules as $option) {
- if ($self->options[$option]) {
- return true; // Yes, there are options enabled that require htaccess rules.
+ /*
+ * Determines if there are any plugin options enabled that require htaccess rules to be added.
+ *
+ * @since 160103 Improving `.htaccess` tweaks.
+ *
+ * @return bool True when an option is enabled that requires htaccess rules, false otherwise.
+ */
+ public function needHtaccessRules()
+ {
+ if (!is_array($this->options_with_htaccess_rules)) {
+ return false; // Nothing to do.
+ }
+ foreach ($this->options_with_htaccess_rules as $option) {
+ if ($this->options[$option]) {
+ return true; // Yes, there are options enabled that require htaccess rules.
+ }
}
+ return false; // No, there are no options enabled that require htaccess rules.
}
- return false; // No, there are no options enabled that require htaccess rules.
-};
-/*
- * Utility method used to check if htaccess file contains $htaccess_marker
- *
- * @since 151114 Adding `.htaccess` tweaks.
- *
- * @param string $htaccess_marker Unique comment marker used to identify rules added by this plugin.
- *
- * @return bool False on failure or when marker does not exist in htaccess, true otherwise.
- */
-$self->findHtaccessMarker = function ($htaccess_marker = '') use ($self) {
- if (!($htaccess_file = $self->findHtaccessFile())) {
- return false; // File does not exist.
- }
- if (!is_readable($htaccess_file)) {
- return false; // Not possible.
- }
- if (($htaccess_file_contents = file_get_contents($htaccess_file)) === false) {
- return false; // Failure; could not read file.
- }
- if (empty($htaccess_marker)) {
- $htaccess_marker = $self->htaccess_marker;
- }
- if (stripos($htaccess_file_contents, $htaccess_marker) === false) {
- return false; // Htaccess marker is missing
- }
+ /*
+ * Utility method used to check if htaccess file contains $htaccess_marker
+ *
+ * @since 151114 Adding `.htaccess` tweaks.
+ *
+ * @param string $htaccess_marker Unique comment marker used to identify rules added by this plugin.
+ *
+ * @return bool False on failure or when marker does not exist in htaccess, true otherwise.
+ */
+ public function findHtaccessMarker($htaccess_marker = '')
+ {
+ if (!($htaccess_file = $this->findHtaccessFile())) {
+ return false; // File does not exist.
+ }
+ if (!is_readable($htaccess_file)) {
+ return false; // Not possible.
+ }
+ if (($htaccess_file_contents = file_get_contents($htaccess_file)) === false) {
+ return false; // Failure; could not read file.
+ }
+ if (empty($htaccess_marker)) {
+ $htaccess_marker = $this->htaccess_marker;
+ }
+ if (stripos($htaccess_file_contents, $htaccess_marker) === false) {
+ return false; // Htaccess marker is missing
+ }
- return true; // Htaccess has the marker
-};
+ return true; // Htaccess has the marker
+ }
-/*
- * Gets contents of `/.htaccess` file with exclusive lock to read+write. If file doesn't exist, we attempt to create it.
- *
- * @since 151220 Improving `.htaccess` utils.
- *
- * @param string $htaccess_file Absolute path to the htaccess file. Optional.
- * If not provided, we attempt to find it or create it if it doesn't exist.
- *
- * @return array|bool Returns an array with data necessary to call $self->writeHtaccessFile():
- * `fp` a file pointer resource, `file_contents` a string. Returns `false` on failure.
- *
- * @note If a call to this method is not followed by a call to $self->writeHtaccessFile(),
- * you must make sure that you unlock and close the `fp` resource yourself.
- */
-$self->readHtaccessFile = function ($htaccess_file = '') use ($self) {
+ /*
+ * Gets contents of `/.htaccess` file with exclusive lock to read+write. If file doesn't exist, we attempt to create it.
+ *
+ * @since 151220 Improving `.htaccess` utils.
+ *
+ * @param string $htaccess_file Absolute path to the htaccess file. Optional.
+ * If not provided, we attempt to find it or create it if it doesn't exist.
+ *
+ * @return array|bool Returns an array with data necessary to call $this->writeHtaccessFile():
+ * `fp` a file pointer resource, `file_contents` a string. Returns `false` on failure.
+ *
+ * @note If a call to this method is not followed by a call to $this->writeHtaccessFile(),
+ * you must make sure that you unlock and close the `fp` resource yourself.
+ */
+ public function readHtaccessFile($htaccess_file = '')
+ {
- if (empty($htaccess_file) && !($htaccess_file = $self->findHtaccessFile())) {
- if (!is_writable($self->wpHomePath()) || file_put_contents($htaccess_file = $self->wpHomePath().'.htaccess', '') === false) {
- return false; // Unable to find and/or create `.htaccess`.
- } // If it doesn't exist, we create the `.htaccess` file here.
- }
- if (!is_readable($htaccess_file) || !is_writable($htaccess_file) || (defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS)) {
- return false; // Not possible.
- }
- if (!($fp = fopen($htaccess_file, 'rb+')) || !flock($fp, LOCK_EX)) {
- fclose($fp); // Just in case we opened it before failing to obtain a lock.
- return false; // Failure; could not open file and obtain an exclusive lock.
- }
- if (($file_contents = fread($fp, filesize($htaccess_file))) && ($file_contents === wp_check_invalid_utf8($file_contents))) {
- rewind($fp); // Rewind pointer to beginning of file.
- return compact('fp', 'file_contents');
- } else { // Failure; could not read file or invalid UTF8 encountered, file may be corrupt.
- flock($fp, LOCK_UN);
- fclose($fp);
- return false;
+ if (empty($htaccess_file) && !($htaccess_file = $this->findHtaccessFile())) {
+ if (!is_writable($this->wpHomePath()) || file_put_contents($htaccess_file = $this->wpHomePath().'.htaccess', '') === false) {
+ return false; // Unable to find and/or create `.htaccess`.
+ } // If it doesn't exist, we create the `.htaccess` file here.
+ }
+ if (!is_readable($htaccess_file) || !is_writable($htaccess_file) || (defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS)) {
+ return false; // Not possible.
+ }
+ if (!($fp = fopen($htaccess_file, 'rb+')) || !flock($fp, LOCK_EX)) {
+ fclose($fp); // Just in case we opened it before failing to obtain a lock.
+ return false; // Failure; could not open file and obtain an exclusive lock.
+ }
+ if (($file_contents = fread($fp, filesize($htaccess_file))) && ($file_contents === wp_check_invalid_utf8($file_contents))) {
+ rewind($fp); // Rewind pointer to beginning of file.
+ return compact('fp', 'file_contents');
+ } else { // Failure; could not read file or invalid UTF8 encountered, file may be corrupt.
+ flock($fp, LOCK_UN);
+ fclose($fp);
+ return false;
+ }
}
-};
-/*
- * Writes to `/.htaccess` file using provided file pointer.
- *
- * @since 151220 Improving `.htaccess` utils.
- *
- * @param array $htaccess Array containing `fp` file resource pointing to htaccess file and `file_contents` to write to file.
- * @param bool $require_marker Whether or not to require the marker be present in contents before writing.
- * @param string $htaccess_marker Unique comment marker used to identify rules added by this plugin.
- *
- * @return bool True on success, false on failure.
- */
-$self->writeHtaccessFile = function (array $htaccess, $require_marker = true, $htaccess_marker = '') use ($self) {
+ /*
+ * Writes to `/.htaccess` file using provided file pointer.
+ *
+ * @since 151220 Improving `.htaccess` utils.
+ *
+ * @param array $htaccess Array containing `fp` file resource pointing to htaccess file and `file_contents` to write to file.
+ * @param bool $require_marker Whether or not to require the marker be present in contents before writing.
+ * @param string $htaccess_marker Unique comment marker used to identify rules added by this plugin.
+ *
+ * @return bool True on success, false on failure.
+ */
+ public function writeHtaccessFile(array $htaccess, $require_marker = true, $htaccess_marker = '')
+ {
- if (defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS) {
- return false; // Not possible.
- }
- if (!is_resource($htaccess['fp'])) {
- return false;
- }
- $htaccess_marker = $htaccess_marker ?: $self->htaccess_marker;
+ if (defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS) {
+ return false; // Not possible.
+ }
+ if (!is_resource($htaccess['fp'])) {
+ return false;
+ }
+ $htaccess_marker = $htaccess_marker ?: $this->htaccess_marker;
- $_have_marker = stripos($htaccess['file_contents'], $htaccess_marker);
+ $_have_marker = stripos($htaccess['file_contents'], $htaccess_marker);
- // Note: rewind() necessary here because we fread() above.
- if (($require_marker && $_have_marker === false) || !rewind($htaccess['fp']) || !ftruncate($htaccess['fp'], 0) || !fwrite($htaccess['fp'], $htaccess['file_contents'])) {
+ // Note: rewind() necessary here because we fread() above.
+ if (($require_marker && $_have_marker === false) || !rewind($htaccess['fp']) || !ftruncate($htaccess['fp'], 0) || !fwrite($htaccess['fp'], $htaccess['file_contents'])) {
+ flock($htaccess['fp'], LOCK_UN);
+ fclose($htaccess['fp']);
+ return false; // Failure; could not write changes.
+ }
+ fflush($htaccess['fp']);
flock($htaccess['fp'], LOCK_UN);
fclose($htaccess['fp']);
- return false; // Failure; could not write changes.
+
+ return true;
}
- fflush($htaccess['fp']);
- flock($htaccess['fp'], LOCK_UN);
- fclose($htaccess['fp']);
- return true;
-};
+ /*
+ * Utility method used to unlock and close htaccess file resource.
+ *
+ * @since 151114 Adding `.htaccess` tweaks.
+ *
+ * @param array $htaccess Array containing at least an `fp` file resource pointing to htaccess file.
+ *
+ * @return bool False on failure, true otherwise.
+ */
+ public function closeHtaccessFile(array $htaccess)
+ {
+ if (!is_resource($htaccess['fp'])) {
+ return false; // Failure; requires a valid file resource.
+ }
+ flock($htaccess['fp'], LOCK_UN);
+ fclose($htaccess['fp']);
-/*
- * Utility method used to unlock and close htaccess file resource.
- *
- * @since 151114 Adding `.htaccess` tweaks.
- *
- * @param array $htaccess Array containing at least an `fp` file resource pointing to htaccess file.
- *
- * @return bool False on failure, true otherwise.
- */
-$self->closeHtaccessFile = function (array $htaccess) use ($self) {
- if (!is_resource($htaccess['fp'])) {
- return false; // Failure; requires a valid file resource.
+ return true;
}
- flock($htaccess['fp'], LOCK_UN);
- fclose($htaccess['fp']);
-
- return true;
-};
+}
diff --git a/src/includes/traits/Plugin/HtmlCUtils.php b/src/includes/traits/Plugin/HtmlCUtils.php
index 52e62042..8a0ced82 100644
--- a/src/includes/traits/Plugin/HtmlCUtils.php
+++ b/src/includes/traits/Plugin/HtmlCUtils.php
@@ -2,17 +2,20 @@
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Traits\Plugin;
-/*
- * Adds marker for the HTML Compressor.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `wp_print_footer_scripts` hook (twice).
- */
-$self->htmlCFooterScripts = function () use ($self) {
- if (!$self->options['enable']) {
- return; // Nothing to do.
+trait HtmlCUtils {
+ /*
+ * Adds marker for the HTML Compressor.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `wp_print_footer_scripts` hook (twice).
+ */
+ public function htmlCFooterScripts()
+ {
+ if (!$this->options['enable']) {
+ return; // Nothing to do.
+ }
+ echo "\n".''."\n";
}
- echo "\n".''."\n";
-};
+}
/*[/pro]*/
diff --git a/src/includes/traits/Plugin/InstallUtils.php b/src/includes/traits/Plugin/InstallUtils.php
index 1d32f7d9..52f24b37 100644
--- a/src/includes/traits/Plugin/InstallUtils.php
+++ b/src/includes/traits/Plugin/InstallUtils.php
@@ -1,555 +1,572 @@
activate = function () use ($self) {
- $self->setup(); // Ensure setup is complete.
-
- if (!$self->options['welcomed'] && !$self->options['enable']) {
- $settings_url = add_query_arg(urlencode_deep(array('page' => GLOBAL_NS)), network_admin_url('/admin.php'));
- $self->enqueueMainNotice(sprintf(__('%1$s successfully installed! :-) Please enable caching and review options.', SLUG_TD), esc_html(NAME), esc_attr($settings_url)), array('push_to_top' => true));
- $self->updateOptions(array('welcomed' => '1'));
- }
+trait InstallUtils {
+
+ /*
+ * Plugin activation hook.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to {@link \register_activation_hook()}
+ */
+ public function activate()
+ {
+ $this->setup(); // Ensure setup is complete.
+
+ if (!$this->options['welcomed'] && !$this->options['enable']) {
+ $settings_url = add_query_arg(urlencode_deep(['page' => GLOBAL_NS]), network_admin_url('/admin.php'));
+ $this->enqueueMainNotice(sprintf(__('%1$s successfully installed! :-) Please enable caching and review options.', SLUG_TD), esc_html(NAME), esc_attr($settings_url)), ['push_to_top' => true]);
+ $this->updateOptions(['welcomed' => '1']);
+ }
- if (!$self->options['enable']) {
- return; // Nothing to do.
- }
+ if (!$this->options['enable']) {
+ return; // Nothing to do.
+ }
- $self->addWpCacheToWpConfig();
- $self->addWpHtaccess();
- $self->addAdvancedCache();
- $self->updateBlogPaths();
- $self->autoClearCache();
-};
-
-/*
- * Check current plugin version that is installed in WP.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `admin_init` hook.
- */
-$self->checkVersion = function () use ($self) {
- $prev_version = $self->options['version'];
- if (version_compare($prev_version, VERSION, '>=')) {
- return; // Nothing to do; up-to-date.
- }
- $self->updateOptions(array('version' => VERSION));
+ $this->addWpCacheToWpConfig();
+ $this->addWpHtaccess();
+ $this->addAdvancedCache();
+ $this->updateBlogPaths();
+ $this->autoClearCache();
+ }
+
+ /*
+ * Check current plugin version that is installed in WP.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `admin_init` hook.
+ */
+ public function checkVersion()
+ {
+ $prev_version = $this->options['version'];
+ if (version_compare($prev_version, VERSION, '>=')) {
+ return; // Nothing to do; up-to-date.
+ }
+ $this->updateOptions(['version' => VERSION]);
- new VsUpgrades($prev_version);
+ new VsUpgrades($prev_version);
- if ($self->options['enable']) {
- $self->addWpCacheToWpConfig();
- $self->addWpHtaccess();
- $self->addAdvancedCache();
- $self->updateBlogPaths();
- }
- $self->wipeCache(); // Fresh start now.
-
- $self->enqueueMainNotice(sprintf(__('%1$s: detected a new version of itself. Recompiling w/ latest version... wiping the cache... all done :-)', SLUG_TD), esc_html(NAME)), array('push_to_top' => true));
-};
-
-/*
- * Plugin deactivation hook.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to {@link \register_deactivation_hook()}
- */
-$self->deactivate = function () use ($self) {
- $self->setup(); // Ensure setup is complete.
-
- $self->removeWpCacheFromWpConfig();
- $self->removeWpHtaccess();
- $self->removeAdvancedCache();
- $self->clearCache();
- $self->resetCronSetup();
-};
-
-/*
- * Plugin uninstall hook.
- *
- * @since 150422 Rewrite.
- */
-$self->uninstall = function () use ($self) {
- $self->setup(); // Ensure setup is complete.
-
- if (!defined('WP_UNINSTALL_PLUGIN')) {
- return; // Disallow.
- }
- if (empty($GLOBALS[GLOBAL_NS.'_uninstalling'])) {
- return; // Not uninstalling.
- }
- if (!current_user_can($self->uninstall_cap)) {
- return; // Extra layer of security.
- }
- $self->removeWpCacheFromWpConfig();
- $self->removeWpHtaccess();
- $self->removeAdvancedCache();
- $self->wipeCache();
- $self->resetCronSetup();
-
- if (!$self->options['uninstall_on_deletion']) {
- return; // Nothing to do here.
- }
- $self->deleteAdvancedCache();
- $self->deleteBaseDir();
+ if ($this->options['enable']) {
+ $this->addWpCacheToWpConfig();
+ $this->addWpHtaccess();
+ $this->addAdvancedCache();
+ $this->updateBlogPaths();
+ }
+ $this->wipeCache(); // Fresh start now.
+
+ $this->enqueueMainNotice(sprintf(__('%1$s: detected a new version of itself. Recompiling w/ latest version... wiping the cache... all done :-)', SLUG_TD), esc_html(NAME)), ['push_to_top' => true]);
+ }
+
+ /*
+ * Plugin deactivation hook.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to {@link \register_deactivation_hook()}
+ */
+ public function deactivate()
+ {
+ $this->setup(); // Ensure setup is complete.
+
+ $this->removeWpCacheFromWpConfig();
+ $this->removeWpHtaccess();
+ $this->removeAdvancedCache();
+ $this->clearCache();
+ $this->resetCronSetup();
+ }
+
+ /*
+ * Plugin uninstall hook.
+ *
+ * @since 150422 Rewrite.
+ */
+ public function uninstall()
+ {
+ $this->setup(); // Ensure setup is complete.
+
+ if (!defined('WP_UNINSTALL_PLUGIN')) {
+ return; // Disallow.
+ }
+ if (empty($GLOBALS[GLOBAL_NS.'_uninstalling'])) {
+ return; // Not uninstalling.
+ }
+ if (!current_user_can($this->uninstall_cap)) {
+ return; // Extra layer of security.
+ }
+ $this->removeWpCacheFromWpConfig();
+ $this->removeWpHtaccess();
+ $this->removeAdvancedCache();
+ $this->wipeCache();
+ $this->resetCronSetup();
+
+ if (!$this->options['uninstall_on_deletion']) {
+ return; // Nothing to do here.
+ }
+ $this->deleteAdvancedCache();
+ $this->deleteBaseDir();
- $wpdb = $self->wpdb(); // WordPress DB.
- $like = '%'.$wpdb->esc_like(GLOBAL_NS).'%';
+ $wpdb = $this->wpdb(); // WordPress DB.
+ $like = '%'.$wpdb->esc_like(GLOBAL_NS).'%';
- if (is_multisite()) { // Site options for a network installation.
- $wpdb->query('DELETE FROM `'.esc_sql($wpdb->sitemeta).'` WHERE `meta_key` LIKE \''.esc_sql($like).'\'');
+ if (is_multisite()) { // Site options for a network installation.
+ $wpdb->query('DELETE FROM `'.esc_sql($wpdb->sitemeta).'` WHERE `meta_key` LIKE \''.esc_sql($like).'\'');
- switch_to_blog(get_current_site()->blog_id); // In case it started as a standard WP installation.
- $wpdb->query('DELETE FROM `'.esc_sql($wpdb->options).'` WHERE `option_name` LIKE \''.esc_sql($like).'\'');
- restore_current_blog(); // Restore current blog.
- //
- } else { // Standard WP installation.
- $wpdb->query('DELETE FROM `'.esc_sql($wpdb->options).'` WHERE `option_name` LIKE \''.esc_sql($like).'\'');
- }
-};
-
-/*
- * Adds `define('WP_CACHE', TRUE);` to the `/wp-config.php` file.
- *
- * @since 150422 Rewrite.
- *
- * @return string The new contents of the updated `/wp-config.php` file;
- * else an empty string if unable to add the `WP_CACHE` constant.
- */
-$self->addWpCacheToWpConfig = function () use ($self) {
- if (!$self->options['enable']) {
- return ''; // Nothing to do.
- }
- if (!($wp_config_file = $self->findWpConfigFile())) {
- return ''; // Unable to find `/wp-config.php`.
- }
- if (!is_readable($wp_config_file)) {
- return ''; // Not possible.
- }
- if (!($wp_config_file_contents = file_get_contents($wp_config_file))) {
- return ''; // Failure; could not read file.
- }
- if (!($wp_config_file_contents_no_whitespace = php_strip_whitespace($wp_config_file))) {
- return ''; // Failure; file empty
- }
- if (preg_match('/\bdefine\s*\(\s*([\'"])WP_CACHE\\1\s*,\s*(?:\-?[1-9][0-9\.]*|TRUE|([\'"])(?:[^0\'"]|[^\'"]{2,})\\2)\s*\)\s*;/i', $wp_config_file_contents_no_whitespace)) {
- return $wp_config_file_contents; // It's already in there; no need to modify this file.
- }
- if (!($wp_config_file_contents = $self->removeWpCacheFromWpConfig())) {
- return ''; // Unable to remove previous value.
- }
- if (!($wp_config_file_contents = preg_replace('/^\s*(\<\?php|\<\?)\s+/i', '${1}'."\n"."define('WP_CACHE', TRUE);"."\n", $wp_config_file_contents, 1))) {
- return ''; // Failure; something went terribly wrong here.
- }
- if (strpos($wp_config_file_contents, "define('WP_CACHE', TRUE);") === false) {
- return ''; // Failure; unable to add; unexpected PHP code.
- }
- if (defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS) {
- return ''; // We may NOT edit any files.
- }
- if (!is_writable($wp_config_file)) {
- return ''; // Not possible.
- }
- if (!file_put_contents($wp_config_file, $wp_config_file_contents)) {
- return ''; // Failure; could not write changes.
- }
- return $wp_config_file_contents;
-};
-
-/*
- * Removes `define('WP_CACHE', TRUE);` from the `/wp-config.php` file.
- *
- * @since 150422 Rewrite.
- *
- * @return string The new contents of the updated `/wp-config.php` file;
- * else an empty string if unable to remove the `WP_CACHE` constant.
- */
-$self->removeWpCacheFromWpConfig = function () use ($self) {
- if (!($wp_config_file = $self->findWpConfigFile())) {
- return ''; // Unable to find `/wp-config.php`.
- }
- if (!is_readable($wp_config_file)) {
- return ''; // Not possible.
- }
- if (!($wp_config_file_contents = file_get_contents($wp_config_file))) {
- return ''; // Failure; could not read file.
- }
- if (!($wp_config_file_contents_no_whitespace = php_strip_whitespace($wp_config_file))) {
- return ''; // Failure; file empty
- }
- if (!preg_match('/([\'"])WP_CACHE\\1/i', $wp_config_file_contents_no_whitespace)) {
- return $wp_config_file_contents; // Already gone.
- }
- if (preg_match('/\bdefine\s*\(\s*([\'"])WP_CACHE\\1\s*,\s*(?:0|FALSE|NULL|([\'"])0?\\2)\s*\)\s*;/i', $wp_config_file_contents_no_whitespace) && !is_writable($wp_config_file)) {
- return $wp_config_file_contents; // It's already disabled, and since we can't write to this file let's let this slide.
- }
- if (!($wp_config_file_contents = preg_replace('/\bdefine\s*\(\s*([\'"])WP_CACHE\\1\s*,\s*(?:\-?[0-9\.]+|TRUE|FALSE|NULL|([\'"])[^\'"]*\\2)\s*\)\s*;/i', '', $wp_config_file_contents))) {
- return ''; // Failure; something went terribly wrong here.
- }
- if (preg_match('/([\'"])WP_CACHE\\1/i', $wp_config_file_contents)) {
- return ''; // Failure; perhaps the `/wp-config.php` file contains syntax we cannot remove safely.
- }
- if (defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS) {
- return ''; // We may NOT edit any files.
- }
- if (!is_writable($wp_config_file)) {
- return ''; // Not possible.
- }
- if (!file_put_contents($wp_config_file, $wp_config_file_contents)) {
- return ''; // Failure; could not write changes.
- }
- return $wp_config_file_contents;
-};
-
-/*
- * Checks to make sure the `advanced-cache.php` file still exists;
- * and if it doesn't, the `advanced-cache.php` is regenerated automatically.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `init` hook.
- *
- * @note This runs so that remote deployments which completely wipe out an
- * existing set of website files (like the AWS Elastic Beanstalk does) will NOT cause Comet Cache
- * to stop functioning due to the lack of an `advanced-cache.php` file, which is generated by Comet Cache.
- *
- * For instance, if you have a Git repo with all of your site files; when you push those files
- * to your website to deploy them, you most likely do NOT have the `advanced-cache.php` file.
- * Comet Cache creates this file on its own. Thus, if it's missing (and CC is active)
- * we simply regenerate the file automatically to keep Comet Cache running.
- */
-$self->checkAdvancedCache = function () use ($self) {
- if (!$self->options['enable']) {
- return; // Nothing to do.
- }
- if (!empty($_REQUEST[GLOBAL_NS])) {
- return; // Skip on plugin actions.
+ switch_to_blog(get_current_site()->blog_id); // In case it started as a standard WP installation.
+ $wpdb->query('DELETE FROM `'.esc_sql($wpdb->options).'` WHERE `option_name` LIKE \''.esc_sql($like).'\'');
+ restore_current_blog(); // Restore current blog.
+ //
+ } else { // Standard WP installation.
+ $wpdb->query('DELETE FROM `'.esc_sql($wpdb->options).'` WHERE `option_name` LIKE \''.esc_sql($like).'\'');
+ }
}
- $cache_dir = $self->cacheDir();
- $advanced_cache_file = WP_CONTENT_DIR.'/advanced-cache.php';
- $advanced_cache_check_file = $cache_dir.'/'.strtolower(SHORT_NAME).'-advanced-cache';
- // Fixes zero-byte advanced-cache.php bug related to migrating from ZenCache
- // See:
+ /*
+ * Adds `define('WP_CACHE', TRUE);` to the `/wp-config.php` file.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return string The new contents of the updated `/wp-config.php` file;
+ * else an empty string if unable to add the `WP_CACHE` constant.
+ */
+ public function addWpCacheToWpConfig()
+ {
+ if (!$this->options['enable']) {
+ return ''; // Nothing to do.
+ }
+ if (!($wp_config_file = $this->findWpConfigFile())) {
+ return ''; // Unable to find `/wp-config.php`.
+ }
+ if (!is_readable($wp_config_file)) {
+ return ''; // Not possible.
+ }
+ if (!($wp_config_file_contents = file_get_contents($wp_config_file))) {
+ return ''; // Failure; could not read file.
+ }
+ if (!($wp_config_file_contents_no_whitespace = php_strip_whitespace($wp_config_file))) {
+ return ''; // Failure; file empty
+ }
+ if (preg_match('/\bdefine\s*\(\s*([\'"])WP_CACHE\\1\s*,\s*(?:\-?[1-9][0-9\.]*|TRUE|([\'"])(?:[^0\'"]|[^\'"]{2,})\\2)\s*\)\s*;/i', $wp_config_file_contents_no_whitespace)) {
+ return $wp_config_file_contents; // It's already in there; no need to modify this file.
+ }
+ if (!($wp_config_file_contents = $this->removeWpCacheFromWpConfig())) {
+ return ''; // Unable to remove previous value.
+ }
+ if (!($wp_config_file_contents = preg_replace('/^\s*(\<\?php|\<\?)\s+/i', '${1}'."\n"."define('WP_CACHE', TRUE);"."\n", $wp_config_file_contents, 1))) {
+ return ''; // Failure; something went terribly wrong here.
+ }
+ if (strpos($wp_config_file_contents, "define('WP_CACHE', TRUE);") === false) {
+ return ''; // Failure; unable to add; unexpected PHP code.
+ }
+ if (defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS) {
+ return ''; // We may NOT edit any files.
+ }
+ if (!is_writable($wp_config_file)) {
+ return ''; // Not possible.
+ }
+ if (!file_put_contents($wp_config_file, $wp_config_file_contents)) {
+ return ''; // Failure; could not write changes.
+ }
+ return $wp_config_file_contents;
+ }
+
+ /*
+ * Removes `define('WP_CACHE', TRUE);` from the `/wp-config.php` file.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return string The new contents of the updated `/wp-config.php` file;
+ * else an empty string if unable to remove the `WP_CACHE` constant.
+ */
+ public function removeWpCacheFromWpConfig()
+ {
+ if (!($wp_config_file = $this->findWpConfigFile())) {
+ return ''; // Unable to find `/wp-config.php`.
+ }
+ if (!is_readable($wp_config_file)) {
+ return ''; // Not possible.
+ }
+ if (!($wp_config_file_contents = file_get_contents($wp_config_file))) {
+ return ''; // Failure; could not read file.
+ }
+ if (!($wp_config_file_contents_no_whitespace = php_strip_whitespace($wp_config_file))) {
+ return ''; // Failure; file empty
+ }
+ if (!preg_match('/([\'"])WP_CACHE\\1/i', $wp_config_file_contents_no_whitespace)) {
+ return $wp_config_file_contents; // Already gone.
+ }
+ if (preg_match('/\bdefine\s*\(\s*([\'"])WP_CACHE\\1\s*,\s*(?:0|FALSE|NULL|([\'"])0?\\2)\s*\)\s*;/i', $wp_config_file_contents_no_whitespace) && !is_writable($wp_config_file)) {
+ return $wp_config_file_contents; // It's already disabled, and since we can't write to this file let's let this slide.
+ }
+ if (!($wp_config_file_contents = preg_replace('/\bdefine\s*\(\s*([\'"])WP_CACHE\\1\s*,\s*(?:\-?[0-9\.]+|TRUE|FALSE|NULL|([\'"])[^\'"]*\\2)\s*\)\s*;/i', '', $wp_config_file_contents))) {
+ return ''; // Failure; something went terribly wrong here.
+ }
+ if (preg_match('/([\'"])WP_CACHE\\1/i', $wp_config_file_contents)) {
+ return ''; // Failure; perhaps the `/wp-config.php` file contains syntax we cannot remove safely.
+ }
+ if (defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS) {
+ return ''; // We may NOT edit any files.
+ }
+ if (!is_writable($wp_config_file)) {
+ return ''; // Not possible.
+ }
+ if (!file_put_contents($wp_config_file, $wp_config_file_contents)) {
+ return ''; // Failure; could not write changes.
+ }
+ return $wp_config_file_contents;
+ }
+
+ /*
+ * Checks to make sure the `advanced-cache.php` file still exists;
+ * and if it doesn't, the `advanced-cache.php` is regenerated automatically.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `init` hook.
+ *
+ * @note This runs so that remote deployments which completely wipe out an
+ * existing set of website files (like the AWS Elastic Beanstalk does) will NOT cause Comet Cache
+ * to stop functioning due to the lack of an `advanced-cache.php` file, which is generated by Comet Cache.
+ *
+ * For instance, if you have a Git repo with all of your site files; when you push those files
+ * to your website to deploy them, you most likely do NOT have the `advanced-cache.php` file.
+ * Comet Cache creates this file on its own. Thus, if it's missing (and CC is active)
+ * we simply regenerate the file automatically to keep Comet Cache running.
+ */
+ public function checkAdvancedCache()
+ {
+ if (!$this->options['enable']) {
+ return; // Nothing to do.
+ }
+ if (!empty($_REQUEST[GLOBAL_NS])) {
+ return; // Skip on plugin actions.
+ }
+ $cache_dir = $this->cacheDir();
+ $advanced_cache_file = WP_CONTENT_DIR.'/advanced-cache.php';
+ $advanced_cache_check_file = $cache_dir.'/'.strtolower(SHORT_NAME).'-advanced-cache';
+
+ // Fixes zero-byte advanced-cache.php bug related to migrating from ZenCache
+ // See:
- // Also fixes a missing `define('WP_CACHE', TRUE)` bug related to migrating from ZenCache
- // See
+ // Also fixes a missing `define('WP_CACHE', TRUE)` bug related to migrating from ZenCache
+ // See
- if (!is_file($advanced_cache_check_file) || !is_file($advanced_cache_file) || filesize($advanced_cache_file) === 0) {
- $self->addAdvancedCache();
- $self->addWpCacheToWpConfig();
- }
-};
-
-/*
- * Creates and adds the `advanced-cache.php` file.
- *
- * @since 150422 Rewrite.
- *
- * @return bool|null `TRUE` on success. `FALSE` or `NULL` on failure.
- * A special `NULL` return value indicates success with a single failure
- * that is specifically related to the `[SHORT_NAME]-advanced-cache` file.
- */
-$self->addAdvancedCache = function () use ($self) {
- if (!$self->removeAdvancedCache()) {
- return false; // Still exists.
+ if (!is_file($advanced_cache_check_file) || !is_file($advanced_cache_file) || filesize($advanced_cache_file) === 0) {
+ $this->addAdvancedCache();
+ $this->addWpCacheToWpConfig();
+ }
}
- $cache_dir = $self->cacheDir();
- $advanced_cache_file = WP_CONTENT_DIR.'/advanced-cache.php';
- $advanced_cache_check_file = $cache_dir.'/'.strtolower(SHORT_NAME).'-advanced-cache';
- $advanced_cache_template = dirname(dirname(dirname(__FILE__))).'/templates/advanced-cache.txt';
- if (is_file($advanced_cache_file) && !is_writable($advanced_cache_file)) {
- return false; // Not possible to create.
- }
- if (!is_file($advanced_cache_file) && !is_writable(dirname($advanced_cache_file))) {
- return false; // Not possible to create.
- }
- if (!is_file($advanced_cache_template) || !is_readable($advanced_cache_template)) {
- return false; // Template file is missing; or not readable.
- }
- if (!($advanced_cache_contents = file_get_contents($advanced_cache_template))) {
- return false; // Template file is missing; or is not readable.
- }
- $possible_advanced_cache_constant_key_values = array_merge(
- $self->options, // The following additional keys are dynamic.
- array('cache_dir' => $self->basePathTo($self->cache_sub_dir),
- /*[pro strip-from="lite"]*/
- 'htmlc_cache_dir_public' => $self->basePathTo($self->htmlc_cache_sub_dir_public),
- 'htmlc_cache_dir_private' => $self->basePathTo($self->htmlc_cache_sub_dir_private),
- /*[/pro]*/
- )
- );
- if ($self->applyWpFilters(GLOBAL_NS.'_exclude_uris_client_side_too', true)) {
- $possible_advanced_cache_constant_key_values['exclude_client_side_uris'] .= "\n".$self->options['exclude_uris'];
- }
- foreach ($possible_advanced_cache_constant_key_values as $_option => $_value) {
- $_value = (string) $_value; // Force string.
+ /*
+ * Creates and adds the `advanced-cache.php` file.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return bool|null `TRUE` on success. `FALSE` or `NULL` on failure.
+ * A special `NULL` return value indicates success with a single failure
+ * that is specifically related to the `[SHORT_NAME]-advanced-cache` file.
+ */
+ public function addAdvancedCache()
+ {
+ if (!$this->removeAdvancedCache()) {
+ return false; // Still exists.
+ }
+ $cache_dir = $this->cacheDir();
+ $advanced_cache_file = WP_CONTENT_DIR.'/advanced-cache.php';
+ $advanced_cache_check_file = $cache_dir.'/'.strtolower(SHORT_NAME).'-advanced-cache';
+ $advanced_cache_template = dirname(dirname(dirname(__FILE__))).'/templates/advanced-cache.txt';
- switch ($_option) {
- case 'exclude_uris': // Converts to regex (caSe insensitive).
- case 'exclude_client_side_uris': // Converts to regex (caSe insensitive).
- case 'exclude_refs': // Converts to regex (caSe insensitive).
- case 'exclude_agents': // Converts to regex (caSe insensitive).
+ if (is_file($advanced_cache_file) && !is_writable($advanced_cache_file)) {
+ return false; // Not possible to create.
+ }
+ if (!is_file($advanced_cache_file) && !is_writable(dirname($advanced_cache_file))) {
+ return false; // Not possible to create.
+ }
+ if (!is_file($advanced_cache_template) || !is_readable($advanced_cache_template)) {
+ return false; // Template file is missing; or not readable.
+ }
+ if (!($advanced_cache_contents = file_get_contents($advanced_cache_template))) {
+ return false; // Template file is missing; or is not readable.
+ }
+ $possible_advanced_cache_constant_key_values = array_merge(
+ $this->options, // The following additional keys are dynamic.
+ [
+ 'cache_dir' => $this->basePathTo($this->cache_sub_dir),
+ /*[pro strip-from="lite"]*/
+ 'htmlc_cache_dir_public' => $this->basePathTo($this->htmlc_cache_sub_dir_public),
+ 'htmlc_cache_dir_private' => $this->basePathTo($this->htmlc_cache_sub_dir_private),
+ /*[/pro]*/
+ ]
+ );
+ if ($this->applyWpFilters(GLOBAL_NS.'_exclude_uris_client_side_too', true)) {
+ $possible_advanced_cache_constant_key_values['exclude_client_side_uris'] .= "\n".$this->options['exclude_uris'];
+ }
+ foreach ($possible_advanced_cache_constant_key_values as $_option => $_value) {
+ $_value = (string) $_value; // Force string.
- /*[pro strip-from="lite"]*/
- case 'htmlc_css_exclusions': // Converts to regex (caSe insensitive).
- case 'htmlc_js_exclusions': // Converts to regex (caSe insensitive).
- case 'htmlc_uri_exclusions': // Converts to regex (caSe insensitive).
- /*[/pro]*/
+ switch ($_option) {
+ case 'exclude_uris': // Converts to regex (caSe insensitive).
+ case 'exclude_client_side_uris': // Converts to regex (caSe insensitive).
+ case 'exclude_refs': // Converts to regex (caSe insensitive).
+ case 'exclude_agents': // Converts to regex (caSe insensitive).
- $_value = "'".$self->escSq($self->lineDelimitedPatternsToRegex($_value))."'";
+ /*[pro strip-from="lite"]*/
+ case 'htmlc_css_exclusions': // Converts to regex (caSe insensitive).
+ case 'htmlc_js_exclusions': // Converts to regex (caSe insensitive).
+ case 'htmlc_uri_exclusions': // Converts to regex (caSe insensitive).
+ /*[/pro]*/
- break; // Break switch handler.
+ $_value = "'".$this->escSq($this->lineDelimitedPatternsToRegex($_value))."'";
- /*[pro strip-from="lite"]*/
- case 'version_salt': // This is PHP code; and we MUST validate syntax.
+ break; // Break switch handler.
- if ($_value && !is_wp_error($_response = wp_remote_post('http://phpcodechecker.com/api/', array('body' => array('code' => $_value))))
- && is_object($_response = json_decode(wp_remote_retrieve_body($_response))) && !empty($_response->errors) && strcasecmp($_response->errors, 'true') === 0
- ) {
- $_value = ''; // PHP syntax errors; empty this.
- $self->enqueueMainError(sprintf(__('%1$s: ignoring your Version Salt; it seems to contain PHP syntax errors.', SLUG_TD), esc_html(NAME)));
- }
- if (!$_value) {
- $_value = "''"; // Use an empty string (default).
- }
- break; // Break switch handler.
- /*[/pro]*/
+ /*[pro strip-from="lite"]*/
+ case 'version_salt': // This is PHP code; and we MUST validate syntax.
+
+ if ($_value && !is_wp_error($_response = wp_remote_post('http://phpcodechecker.com/api/', ['body' => ['code' => $_value]]))
+ && is_object($_response = json_decode(wp_remote_retrieve_body($_response))) && !empty($_response->errors) && strcasecmp($_response->errors, 'true') === 0
+ ) {
+ $_value = ''; // PHP syntax errors; empty this.
+ $this->enqueueMainError(sprintf(__('%1$s: ignoring your Version Salt; it seems to contain PHP syntax errors.', SLUG_TD), esc_html(NAME)));
+ }
+ if (!$_value) {
+ $_value = "''"; // Use an empty string (default).
+ }
+ break; // Break switch handler.
+ /*[/pro]*/
- default: // Default case handler.
+ default: // Default case handler.
- $_value = "'".$self->escSq($_value)."'";
+ $_value = "'".$this->escSq($_value)."'";
- break; // Break switch handler.
+ break; // Break switch handler.
+ }
+ $advanced_cache_contents = // Fill replacement codes.
+ str_ireplace(
+ [
+ "'%%".GLOBAL_NS.'_'.$_option."%%'",
+ "'%%".GLOBAL_NS.'_'.preg_replace('/^cache_/i', '', $_option)."%%'",
+ ],
+ $_value,
+ $advanced_cache_contents
+ );
}
- $advanced_cache_contents = // Fill replacement codes.
- str_ireplace(
- array(
- "'%%".GLOBAL_NS.'_'.$_option."%%'",
- "'%%".GLOBAL_NS.'_'.preg_replace('/^cache_/i', '', $_option)."%%'",
- ),
- $_value,
- $advanced_cache_contents
- );
- }
- unset($_option, $_value, $_values, $_response); // Housekeeping.
+ unset($_option, $_value, $_values, $_response); // Housekeeping.
- if (strpos(PLUGIN_FILE, WP_CONTENT_DIR) === 0) {
- $plugin_file = "WP_CONTENT_DIR.'".$self->escSq(str_replace(WP_CONTENT_DIR, '', PLUGIN_FILE))."'";
- } else {
- $plugin_file = "'".$self->escSq(PLUGIN_FILE)."'"; // Full absolute path.
- }
- // Make it possible for the `advanced-cache.php` handler to find the plugin directory reliably.
- $advanced_cache_contents = str_ireplace("'%%".GLOBAL_NS."_PLUGIN_FILE%%'", $plugin_file, $advanced_cache_contents);
+ if (strpos(PLUGIN_FILE, WP_CONTENT_DIR) === 0) {
+ $plugin_file = "WP_CONTENT_DIR.'".$this->escSq(str_replace(WP_CONTENT_DIR, '', PLUGIN_FILE))."'";
+ } else {
+ $plugin_file = "'".$this->escSq(PLUGIN_FILE)."'"; // Full absolute path.
+ }
+ // Make it possible for the `advanced-cache.php` handler to find the plugin directory reliably.
+ $advanced_cache_contents = str_ireplace("'%%".GLOBAL_NS."_PLUGIN_FILE%%'", $plugin_file, $advanced_cache_contents);
- // Ignore; this is created by Comet Cache; and we don't need to obey in this case.
- #if(defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS)
- # return FALSE; // We may NOT edit any files.
+ // Ignore; this is created by Comet Cache; and we don't need to obey in this case.
+ #if(defined('DISALLOW_FILE_MODS') && DISALLOW_FILE_MODS)
+ # return FALSE; // We may NOT edit any files.
- if (!file_put_contents($advanced_cache_file, $advanced_cache_contents)) {
- return false; // Failure; could not write file.
- }
- $cache_lock = $self->cacheLock(); // Lock cache.
+ if (!file_put_contents($advanced_cache_file, $advanced_cache_contents)) {
+ return false; // Failure; could not write file.
+ }
+ $cache_lock = $this->cacheLock(); // Lock cache.
- if (!is_dir($cache_dir)) {
- mkdir($cache_dir, 0775, true);
- }
- if (is_writable($cache_dir) && !is_file($cache_dir.'/.htaccess')) {
- file_put_contents($cache_dir.'/.htaccess', $self->htaccess_deny);
- }
- if (!is_dir($cache_dir) || !is_writable($cache_dir) || !is_file($cache_dir.'/.htaccess') || !file_put_contents($advanced_cache_check_file, time())) {
- $self->cacheUnlock($cache_lock); // Release.
- return; // Special return value (NULL).
- }
- $self->cacheUnlock($cache_lock); // Release.
-
- $self->clearAcDropinFromOpcacheByForce();
-
- return true;
-};
-
-/*
- * Removes the `advanced-cache.php` file.
- *
- * @since 150422 Rewrite.
- *
- * @return bool `TRUE` on success. `FALSE` on failure.
- *
- * @note The `advanced-cache.php` file is NOT actually deleted by this routine.
- * Instead of deleting the file, we simply empty it out so that it's `0` bytes in size.
- *
- * The reason for this is to preserve any file permissions set by the site owner.
- * If the site owner previously allowed this specific file to become writable, we don't want to
- * lose that permission by deleting the file; forcing the site owner to do it all over again later.
- *
- * An example of where this is useful is when a site owner deactivates the CC plugin,
- * but later they decide that CC really is the most awesome plugin in the world and they turn it back on.
- */
-$self->removeAdvancedCache = function () use ($self) {
- $advanced_cache_file = WP_CONTENT_DIR.'/advanced-cache.php';
-
- if (!is_file($advanced_cache_file)) {
- return true; // Already gone.
- }
- if (is_readable($advanced_cache_file) && filesize($advanced_cache_file) === 0) {
- return true; // Already gone; i.e. it's empty already.
- }
- if (!is_writable($advanced_cache_file)) {
- return false; // Not possible.
- }
- /* Empty the file only. This way permissions are NOT lost in cases where
- a site owner makes this specific file writable for Comet Cache. */
- if (file_put_contents($advanced_cache_file, '') !== 0) {
- return false; // Failure.
- }
- $self->clearAcDropinFromOpcacheByForce();
-
- return true;
-};
-
-/*
- * Deletes the `advanced-cache.php` file.
- *
- * @since 150422 Rewrite.
- *
- * @return bool `TRUE` on success. `FALSE` on failure.
- *
- * @note The `advanced-cache.php` file is deleted by this routine.
- */
-$self->deleteAdvancedCache = function () use ($self) {
- $cache_dir = $self->cacheDir();
- $advanced_cache_file = WP_CONTENT_DIR.'/advanced-cache.php';
- $advanced_cache_check_file = $cache_dir.'/'.strtolower(SHORT_NAME).'-advanced-cache';
-
- if (is_file($advanced_cache_file)) {
- if (!is_writable($advanced_cache_file) || !unlink($advanced_cache_file)) {
- return false; // Not possible; or outright failure.
+ if (!is_dir($cache_dir)) {
+ mkdir($cache_dir, 0775, true);
}
- }
- if (is_file($advanced_cache_check_file)) {
- if (!is_writable($advanced_cache_check_file) || !unlink($advanced_cache_check_file)) {
- return false; // Not possible; or outright failure.
+ if (is_writable($cache_dir) && !is_file($cache_dir.'/.htaccess')) {
+ file_put_contents($cache_dir.'/.htaccess', $this->htaccess_deny);
}
- }
- $self->clearAcDropinFromOpcacheByForce();
-
- return true; // Deletion success.
-};
-
-/*
- * Checks to make sure the `[SHORT_NAME]-blog-paths` file still exists;
- * and if it doesn't, the `[SHORT_NAME]-blog-paths` file is regenerated automatically.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `init` hook.
- *
- * @note This runs so that remote deployments which completely wipe out an
- * existing set of website files (like the AWS Elastic Beanstalk does) will NOT cause Comet Cache
- * to stop functioning due to the lack of a `[SHORT_NAME]-blog-paths` file, which is generated by Comet Cache.
- *
- * For instance, if you have a Git repo with all of your site files; when you push those files
- * to your website to deploy them, you most likely do NOT have the `[SHORT_NAME]-blog-paths` file.
- * Comet Cache creates this file on its own. Thus, if it's missing (and CC is active)
- * we simply regenerate the file automatically to keep Comet Cache running.
- */
-$self->checkBlogPaths = function () use ($self) {
- if (!$self->options['enable']) {
- return; // Nothing to do.
- }
- if (!is_multisite()) {
- return; // N/A.
- }
- if (!empty($_REQUEST[GLOBAL_NS])) {
- return; // Skip on plugin actions.
- }
- $cache_dir = $self->cacheDir();
- $blog_paths_file = $cache_dir.'/'.strtolower(SHORT_NAME).'-blog-paths';
+ if (!is_dir($cache_dir) || !is_writable($cache_dir) || !is_file($cache_dir.'/.htaccess') || !file_put_contents($advanced_cache_check_file, time())) {
+ $this->cacheUnlock($cache_lock); // Release.
+ return; // Special return value (NULL).
+ }
+ $this->cacheUnlock($cache_lock); // Release.
+
+ $this->clearAcDropinFromOpcacheByForce();
+
+ return true;
+ }
+
+ /*
+ * Removes the `advanced-cache.php` file.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return bool `TRUE` on success. `FALSE` on failure.
+ *
+ * @note The `advanced-cache.php` file is NOT actually deleted by this routine.
+ * Instead of deleting the file, we simply empty it out so that it's `0` bytes in size.
+ *
+ * The reason for this is to preserve any file permissions set by the site owner.
+ * If the site owner previously allowed this specific file to become writable, we don't want to
+ * lose that permission by deleting the file; forcing the site owner to do it all over again later.
+ *
+ * An example of where this is useful is when a site owner deactivates the CC plugin,
+ * but later they decide that CC really is the most awesome plugin in the world and they turn it back on.
+ */
+ public function removeAdvancedCache()
+ {
+ $advanced_cache_file = WP_CONTENT_DIR.'/advanced-cache.php';
+
+ if (!is_file($advanced_cache_file)) {
+ return true; // Already gone.
+ }
+ if (is_readable($advanced_cache_file) && filesize($advanced_cache_file) === 0) {
+ return true; // Already gone; i.e. it's empty already.
+ }
+ if (!is_writable($advanced_cache_file)) {
+ return false; // Not possible.
+ }
+ /* Empty the file only. This way permissions are NOT lost in cases where
+ a site owner makes this specific file writable for Comet Cache. */
+ if (file_put_contents($advanced_cache_file, '') !== 0) {
+ return false; // Failure.
+ }
+ $this->clearAcDropinFromOpcacheByForce();
+
+ return true;
+ }
+
+ /*
+ * Deletes the `advanced-cache.php` file.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return bool `TRUE` on success. `FALSE` on failure.
+ *
+ * @note The `advanced-cache.php` file is deleted by this routine.
+ */
+ public function deleteAdvancedCache()
+ {
+ $cache_dir = $this->cacheDir();
+ $advanced_cache_file = WP_CONTENT_DIR.'/advanced-cache.php';
+ $advanced_cache_check_file = $cache_dir.'/'.strtolower(SHORT_NAME).'-advanced-cache';
+
+ if (is_file($advanced_cache_file)) {
+ if (!is_writable($advanced_cache_file) || !unlink($advanced_cache_file)) {
+ return false; // Not possible; or outright failure.
+ }
+ }
+ if (is_file($advanced_cache_check_file)) {
+ if (!is_writable($advanced_cache_check_file) || !unlink($advanced_cache_check_file)) {
+ return false; // Not possible; or outright failure.
+ }
+ }
+ $this->clearAcDropinFromOpcacheByForce();
+
+ return true; // Deletion success.
+ }
+
+ /*
+ * Checks to make sure the `[SHORT_NAME]-blog-paths` file still exists;
+ * and if it doesn't, the `[SHORT_NAME]-blog-paths` file is regenerated automatically.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `init` hook.
+ *
+ * @note This runs so that remote deployments which completely wipe out an
+ * existing set of website files (like the AWS Elastic Beanstalk does) will NOT cause Comet Cache
+ * to stop functioning due to the lack of a `[SHORT_NAME]-blog-paths` file, which is generated by Comet Cache.
+ *
+ * For instance, if you have a Git repo with all of your site files; when you push those files
+ * to your website to deploy them, you most likely do NOT have the `[SHORT_NAME]-blog-paths` file.
+ * Comet Cache creates this file on its own. Thus, if it's missing (and CC is active)
+ * we simply regenerate the file automatically to keep Comet Cache running.
+ */
+ public function checkBlogPaths()
+ {
+ if (!$this->options['enable']) {
+ return; // Nothing to do.
+ }
+ if (!is_multisite()) {
+ return; // N/A.
+ }
+ if (!empty($_REQUEST[GLOBAL_NS])) {
+ return; // Skip on plugin actions.
+ }
+ $cache_dir = $this->cacheDir();
+ $blog_paths_file = $cache_dir.'/'.strtolower(SHORT_NAME).'-blog-paths';
- if (!is_file($blog_paths_file)) {
- $self->updateBlogPaths();
- }
-};
-
-/*
- * Creates and/or updates the `[SHORT_NAME]-blog-paths` file.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `enable_live_network_counts` filter.
- *
- * @param mixed $enable_live_network_counts Optional, defaults to a `NULL` value.
- *
- * @return mixed The value of `$enable_live_network_counts` (passes through).
- *
- * @note While this routine is attached to a WP filter, we also call upon it directly at times.
- */
-$self->updateBlogPaths = function ($enable_live_network_counts = null) use ($self) {
- $value = $enable_live_network_counts; // This hook actually rides on a filter.
-
- if (!$self->options['enable']) {
- return $value; // Nothing to do.
- }
- if (!is_multisite()) {
- return $value; // N/A.
+ if (!is_file($blog_paths_file)) {
+ $this->updateBlogPaths();
+ }
}
- $cache_dir = $self->cacheDir();
- $blog_paths_file = $cache_dir.'/'.strtolower(SHORT_NAME).'-blog-paths';
- $cache_lock = $self->cacheLock();
+ /*
+ * Creates and/or updates the `[SHORT_NAME]-blog-paths` file.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `enable_live_network_counts` filter.
+ *
+ * @param mixed $enable_live_network_counts Optional, defaults to a `NULL` value.
+ *
+ * @return mixed The value of `$enable_live_network_counts` (passes through).
+ *
+ * @note While this routine is attached to a WP filter, we also call upon it directly at times.
+ */
+ public function updateBlogPaths($enable_live_network_counts = null)
+ {
+ $value = $enable_live_network_counts; // This hook actually rides on a filter.
+
+ if (!$this->options['enable']) {
+ return $value; // Nothing to do.
+ }
+ if (!is_multisite()) {
+ return $value; // N/A.
+ }
+ $cache_dir = $this->cacheDir();
+ $blog_paths_file = $cache_dir.'/'.strtolower(SHORT_NAME).'-blog-paths';
+
+ $cache_lock = $this->cacheLock();
- if (!is_dir($cache_dir)) {
- mkdir($cache_dir, 0775, true);
- }
- if (is_writable($cache_dir) && !is_file($cache_dir.'/.htaccess')) {
- file_put_contents($cache_dir.'/.htaccess', $self->htaccess_deny);
- }
- if (is_dir($cache_dir) && is_writable($cache_dir)) {
- $paths = // Collect child `[/base]/path/`s from the WordPress database.
- $self->wpdb()->get_col('SELECT `path` FROM `'.esc_sql($self->wpdb()->blogs)."` WHERE `deleted` <= '0'");
+ if (!is_dir($cache_dir)) {
+ mkdir($cache_dir, 0775, true);
+ }
+ if (is_writable($cache_dir) && !is_file($cache_dir.'/.htaccess')) {
+ file_put_contents($cache_dir.'/.htaccess', $this->htaccess_deny);
+ }
+ if (is_dir($cache_dir) && is_writable($cache_dir)) {
+ $paths = // Collect child `[/base]/path/`s from the WordPress database.
+ $this->wpdb()->get_col('SELECT `path` FROM `'.esc_sql($this->wpdb()->blogs)."` WHERE `deleted` <= '0'");
- $host_base_token = $self->hostBaseToken(); // Pull this once only.
+ $host_base_token = $this->hostBaseToken(); // Pull this once only.
- foreach ($paths as $_key => &$_path) {
- if ($_path && $_path !== '/' && $host_base_token && $host_base_token !== '/') {
- // Note that each `path` in the DB looks like: `[/base]/path/` (i.e., it includes base).
- $_path = '/'.ltrim(preg_replace('/^'.preg_quote($host_base_token, '/').'/', '', $_path), '/');
- }
- if (!$_path || $_path === '/') {
- unset($paths[$_key]); // Exclude main site.
+ foreach ($paths as $_key => &$_path) {
+ if ($_path && $_path !== '/' && $host_base_token && $host_base_token !== '/') {
+ // Note that each `path` in the DB looks like: `[/base]/path/` (i.e., it includes base).
+ $_path = '/'.ltrim(preg_replace('/^'.preg_quote($host_base_token, '/').'/', '', $_path), '/');
+ }
+ if (!$_path || $_path === '/') {
+ unset($paths[$_key]); // Exclude main site.
+ }
}
+ unset($_key, $_path); // Housekeeping.
+
+ file_put_contents($blog_paths_file, serialize($paths));
}
- unset($_key, $_path); // Housekeeping.
+ $this->cacheUnlock($cache_lock); // Release.
- file_put_contents($blog_paths_file, serialize($paths));
+ return $value; // Pass through untouched (always).
}
- $self->cacheUnlock($cache_lock); // Release.
- return $value; // Pass through untouched (always).
-};
+ /*
+ * Deletes base directory.
+ *
+ * @since 151002 Improving multisite compat.
+ *
+ * @return int Total files removed by this routine (if any).
+ */
+ public function deleteBaseDir()
+ {
+ $counter = 0; // Initialize.
-/*
- * Deletes base directory.
- *
- * @since 151002 Improving multisite compat.
- *
- * @return int Total files removed by this routine (if any).
- */
-$self->deleteBaseDir = function () use ($self) {
- $counter = 0; // Initialize.
+ @set_time_limit(1800); // @TODO Display a warning.
- @set_time_limit(1800); // @TODO Display a warning.
+ $counter += $this->deleteAllFilesDirsIn($this->wpContentBaseDirTo(''), true);
- $counter += $self->deleteAllFilesDirsIn($self->wpContentBaseDirTo(''), true);
-
- return $counter;
-};
+ return $counter;
+ }
+}
diff --git a/src/includes/traits/Plugin/MenuPageUtils.php b/src/includes/traits/Plugin/MenuPageUtils.php
index b5ab642b..54574281 100644
--- a/src/includes/traits/Plugin/MenuPageUtils.php
+++ b/src/includes/traits/Plugin/MenuPageUtils.php
@@ -1,248 +1,262 @@
enqueueAdminStyles = function () use ($self) {
- if (empty($_GET['page']) || strpos($_GET['page'], GLOBAL_NS) !== 0) {
- return; // NOT a plugin page in the administrative area.
- }
- $deps = array(); // Plugin dependencies.
-
- wp_enqueue_style(GLOBAL_NS, $self->url('/src/client-s/css/menu-pages.min.css'), $deps, VERSION, 'all');
-};
-
-/*
- * Adds JS for administrative menu pages.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `admin_enqueue_scripts` hook.
- */
-$self->enqueueAdminScripts = function () use ($self) {
- if (empty($_GET['page']) || strpos($_GET['page'], GLOBAL_NS) !== 0) {
- return; // NOT a plugin page in the administrative area.
+trait MenuPageUtils {
+ /*
+ * Adds CSS for administrative menu pages.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `admin_enqueue_scripts` hook.
+ */
+ public function enqueueAdminStyles()
+ {
+ if (empty($_GET['page']) || strpos($_GET['page'], GLOBAL_NS) !== 0) {
+ return; // NOT a plugin page in the administrative area.
+ }
+ $deps = []; // Plugin dependencies.
+
+ wp_enqueue_style(GLOBAL_NS, $this->url('/src/client-s/css/menu-pages.min.css'), $deps, VERSION, 'all');
}
- $deps = array('jquery', 'chartjs'); // Plugin dependencies.
-
- wp_enqueue_script('chartjs', set_url_scheme('//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'), array(), null, true);
- wp_enqueue_script(GLOBAL_NS, $self->url('/src/client-s/js/menu-pages.min.js'), $deps, VERSION, true);
- wp_localize_script(GLOBAL_NS, GLOBAL_NS.'_menu_page_vars', array(
- '_wpnonce' => wp_create_nonce(),
- 'isMultisite' => is_multisite(), // Network?
- 'currentUserHasCap' => current_user_can($self->cap),
- 'currentUserHasNetworkCap' => current_user_can($self->network_cap),
- 'htmlCompressorEnabled' => (boolean) $self->options['htmlc_enable'],
- 'ajaxURL' => site_url('/wp-load.php', is_ssl() ? 'https' : 'http'),
- 'emptyStatsCountsImageUrl' => $self->url('/src/client-s/images/stats-fc-empty.png'),
- 'emptyStatsFilesImageUrl' => $self->url('/src/client-s/images/stats-fs-empty.png'),
- 'i18n' => array(
- 'name' => NAME,
- 'perSymbol' => __('%', SLUG_TD),
- 'file' => __('file', SLUG_TD),
- 'files' => __('files', SLUG_TD),
- 'pageCache' => __('Page Cache', SLUG_TD),
- 'htmlCompressor' => __('HTML Compressor', SLUG_TD),
- 'currentTotal' => __('Current Total', SLUG_TD),
- 'currentSite' => __('Current Site', SLUG_TD),
- 'xDayHigh' => __('%s Day High', SLUG_TD),
- ),
- ));
-};
-
-/*
- * Creates network admin menu pages.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `network_admin_menu` hook.
- */
-$self->addNetworkMenuPages = function () use ($self) {
- if (!is_multisite()) {
- return; // Not applicable.
+
+ /*
+ * Adds JS for administrative menu pages.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `admin_enqueue_scripts` hook.
+ */
+ public function enqueueAdminScripts()
+ {
+ if (empty($_GET['page']) || strpos($_GET['page'], GLOBAL_NS) !== 0) {
+ return; // NOT a plugin page in the administrative area.
+ }
+ $deps = ['jquery', 'chartjs']; // Plugin dependencies.
+
+ wp_enqueue_script('chartjs', set_url_scheme('//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js'), [], null, true);
+ wp_enqueue_script(GLOBAL_NS, $this->url('/src/client-s/js/menu-pages.min.js'), $deps, VERSION, true);
+ wp_localize_script(
+ GLOBAL_NS, GLOBAL_NS.'_menu_page_vars', [
+ '_wpnonce' => wp_create_nonce(),
+ 'isMultisite' => is_multisite(), // Network?
+ 'currentUserHasCap' => current_user_can($this->cap),
+ 'currentUserHasNetworkCap' => current_user_can($this->network_cap),
+ 'htmlCompressorEnabled' => (boolean) $this->options['htmlc_enable'],
+ 'ajaxURL' => site_url('/wp-load.php', is_ssl() ? 'https' : 'http'),
+ 'emptyStatsCountsImageUrl' => $this->url('/src/client-s/images/stats-fc-empty.png'),
+ 'emptyStatsFilesImageUrl' => $this->url('/src/client-s/images/stats-fs-empty.png'),
+ 'i18n' => [
+ 'name' => NAME,
+ 'perSymbol' => __('%', SLUG_TD),
+ 'file' => __('file', SLUG_TD),
+ 'files' => __('files', SLUG_TD),
+ 'pageCache' => __('Page Cache', SLUG_TD),
+ 'htmlCompressor' => __('HTML Compressor', SLUG_TD),
+ 'currentTotal' => __('Current Total', SLUG_TD),
+ 'currentSite' => __('Current Site', SLUG_TD),
+ 'xDayHigh' => __('%s Day High', SLUG_TD),
+ ],
+ ]
+ );
}
- $icon = file_get_contents(dirname(dirname(dirname(dirname(__FILE__)))).'/client-s/images/inline-icon.svg');
- $icon = 'data:image/svg+xml;base64,'.base64_encode($self->colorSvgMenuIcon($icon));
- add_menu_page(NAME . (IS_PRO ? ' Pro' : ''), NAME . (IS_PRO ? ' Pro' : ''), $self->network_cap, GLOBAL_NS, array($self, 'menuPageOptions'), $icon);
- add_submenu_page(GLOBAL_NS, __('Plugin Options', SLUG_TD), __('Plugin Options', SLUG_TD), $self->network_cap, GLOBAL_NS, array($self, 'menuPageOptions'));
+ /*
+ * Creates network admin menu pages.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `network_admin_menu` hook.
+ */
+ public function addNetworkMenuPages()
+ {
+ if (!is_multisite()) {
+ return; // Not applicable.
+ }
+ $icon = file_get_contents(dirname(dirname(dirname(dirname(__FILE__)))).'/client-s/images/inline-icon.svg');
+ $icon = 'data:image/svg+xml;base64,'.base64_encode($this->colorSvgMenuIcon($icon));
- /*[pro strip-from="lite"]*/
- if ($self->options['stats_enable']) {
- add_submenu_page(GLOBAL_NS, __('Stats / Charts', SLUG_TD), __('Stats / Charts', SLUG_TD), $self->network_cap, GLOBAL_NS.'-stats', array($self, 'menuPageStats'));
- } /*[/pro]*/
+ add_menu_page(NAME.(IS_PRO ? ' Pro' : ''), NAME.(IS_PRO ? ' Pro' : ''), $this->network_cap, GLOBAL_NS, [$self, 'menuPageOptions'], $icon);
+ add_submenu_page(GLOBAL_NS, __('Plugin Options', SLUG_TD), __('Plugin Options', SLUG_TD), $this->network_cap, GLOBAL_NS, [$self, 'menuPageOptions']);
- /*[pro strip-from="lite"]*/
- if (current_user_can($self->network_cap)) {
- add_submenu_page(GLOBAL_NS, __('Pro Plugin Updater', SLUG_TD), __('Plugin Updater', SLUG_TD), $self->update_cap, GLOBAL_NS.'-pro-updater', array($self, 'menuPageProUpdater'));
- } /*[/pro]*/
-};
-
-/*
- * Creates admin menu pages.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `admin_menu` hook.
- */
-$self->addMenuPages = function () use ($self) {
- if (is_multisite()) {
- return; // Multisite networks MUST use network admin area.
+ /*[pro strip-from="lite"]*/
+ if ($this->options['stats_enable']) {
+ add_submenu_page(GLOBAL_NS, __('Stats / Charts', SLUG_TD), __('Stats / Charts', SLUG_TD), $this->network_cap, GLOBAL_NS.'-stats', [$self, 'menuPageStats']);
+ } /*[/pro]*/
+
+ /*[pro strip-from="lite"]*/
+ if (current_user_can($this->network_cap)) {
+ add_submenu_page(GLOBAL_NS, __('Pro Plugin Updater', SLUG_TD), __('Plugin Updater', SLUG_TD), $this->update_cap, GLOBAL_NS.'-pro-updater', [$self, 'menuPageProUpdater']);
+ } /*[/pro]*/
}
- $icon = file_get_contents(dirname(dirname(dirname(dirname(__FILE__)))).'/client-s/images/inline-icon.svg');
- $icon = 'data:image/svg+xml;base64,'.base64_encode($self->colorSvgMenuIcon($icon));
- add_menu_page(NAME . (IS_PRO ? ' Pro' : ''), NAME . (IS_PRO ? ' Pro' : ''), $self->cap, GLOBAL_NS, array($self, 'menuPageOptions'), $icon);
- add_submenu_page(GLOBAL_NS, __('Plugin Options', SLUG_TD), __('Plugin Options', SLUG_TD), $self->cap, GLOBAL_NS, array($self, 'menuPageOptions'));
+ /*
+ * Creates admin menu pages.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `admin_menu` hook.
+ */
+ public function addMenuPages()
+ {
+ if (is_multisite()) {
+ return; // Multisite networks MUST use network admin area.
+ }
+ $icon = file_get_contents(dirname(dirname(dirname(dirname(__FILE__)))).'/client-s/images/inline-icon.svg');
+ $icon = 'data:image/svg+xml;base64,'.base64_encode($this->colorSvgMenuIcon($icon));
- /*[pro strip-from="lite"]*/
- if ($self->options['stats_enable']) {
- add_submenu_page(GLOBAL_NS, __('Stats / Charts', SLUG_TD), __('Stats / Charts', SLUG_TD), $self->cap, GLOBAL_NS.'-stats', array($self, 'menuPageStats'));
- } /*[/pro]*/
+ add_menu_page(NAME.(IS_PRO ? ' Pro' : ''), NAME.(IS_PRO ? ' Pro' : ''), $this->cap, GLOBAL_NS, [$self, 'menuPageOptions'], $icon);
+ add_submenu_page(GLOBAL_NS, __('Plugin Options', SLUG_TD), __('Plugin Options', SLUG_TD), $this->cap, GLOBAL_NS, [$self, 'menuPageOptions']);
- /*[pro strip-from="lite"]*/
- add_submenu_page(GLOBAL_NS, __('Pro Plugin Updater', SLUG_TD), __('Plugin Updater', SLUG_TD), $self->update_cap, GLOBAL_NS.'-pro-updater', array($self, 'menuPageProUpdater'));
- /*[/pro]*/
-};
-
-/*
- * Adds link(s) to Comet Cache row on the WP plugins page.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `plugin_action_links_'.plugin_basename(PLUGIN_FILE)` filter.
- *
- * @param array $links An array of the existing links provided by WordPress.
- *
- * @return array Revised array of links.
- */
-$self->addSettingsLink = function ($links) use ($self) {
- if (is_multisite() && !is_network_admin()) {
- return $links;
- }
+ /*[pro strip-from="lite"]*/
+ if ($this->options['stats_enable']) {
+ add_submenu_page(GLOBAL_NS, __('Stats / Charts', SLUG_TD), __('Stats / Charts', SLUG_TD), $this->cap, GLOBAL_NS.'-stats', [$self, 'menuPageStats']);
+ } /*[/pro]*/
- $links[] = ''.__('Settings', SLUG_TD).'';
- if (!IS_PRO) {
- $links[] = '
'.__('Preview Pro Features', SLUG_TD).'';
- $links[] = ''.__('Upgrade', SLUG_TD).'';
- }
- return $links;
-};
-
-/*
- * Fills menu page inline SVG icon color.
- *
- * @since 150422 Rewrite.
- *
- * @param string $svg Inline SVG icon markup.
- *
- * @return string Inline SVG icon markup.
- */
-$self->colorSvgMenuIcon = function ($svg) use ($self) {
- if (!($color = get_user_option('admin_color'))) {
- $color = 'fresh'; // Default color scheme.
- }
- if (empty($self->wp_admin_icon_colors[$color])) {
- return $svg; // Not possible.
+ /*[pro strip-from="lite"]*/
+ add_submenu_page(GLOBAL_NS, __('Pro Plugin Updater', SLUG_TD), __('Plugin Updater', SLUG_TD), $this->update_cap, GLOBAL_NS.'-pro-updater', [$self, 'menuPageProUpdater']);
+ /*[/pro]*/
}
- $icon_colors = $self->wp_admin_icon_colors[$color];
- $use_icon_fill_color = $icon_colors['base']; // Default base.
- $current_pagenow = !empty($GLOBALS['pagenow']) ? $GLOBALS['pagenow'] : '';
- $current_page = !empty($_REQUEST['page']) ? $_REQUEST['page'] : '';
+ /*
+ * Adds link(s) to Comet Cache row on the WP plugins page.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `plugin_action_links_'.plugin_basename(PLUGIN_FILE)` filter.
+ *
+ * @param array $links An array of the existing links provided by WordPress.
+ *
+ * @return array Revised array of links.
+ */
+ public function addSettingsLink($links)
+ {
+ if (is_multisite() && !is_network_admin()) {
+ return $links;
+ }
- if (strpos($current_pagenow, GLOBAL_NS) === 0 || strpos($current_page, GLOBAL_NS) === 0) {
- $use_icon_fill_color = $icon_colors['current'];
- }
- return str_replace(' fill="currentColor"', ' fill="'.esc_attr($use_icon_fill_color).'"', $svg);
-};
-
-/*
- * Loads the admin menu page options.
- *
- * @since 150422 Rewrite.
- */
-$self->menuPageOptions = function () use ($self) {
- new MenuPage('options');
-};
-
-/*[pro strip-from="lite"]*/
-/*
- * Loads admin menu page for stats.
- *
- * @since 151002 Directory stats.
- */
-$self->menuPageStats = function () use ($self) {
- new MenuPage('stats');
-};
-/*[/pro]*/
-
-/*[pro strip-from="lite"]*/
-/*
- * Loads admin menu page for pro updater.
- *
- * @since 150422 Rewrite.
- */
-$self->menuPageProUpdater = function () use ($self) {
- new MenuPage('pro-updater');
-};
-/*[/pro]*/
-
-/*
- * WordPress admin icon color schemes.
- *
- * @since 150422 Rewrite.
- *
- * @type array WP admin icon colors.
- *
- * @note These must be hard-coded, because they don't become available
- * in core until `admin_init`; i.e., too late for `admin_menu`.
- */
-public $wp_admin_icon_colors = [
- 'fresh' => array('base' => '#999999', 'focus' => '#2EA2CC', 'current' => '#FFFFFF'),
- 'light' => array('base' => '#999999', 'focus' => '#CCCCCC', 'current' => '#CCCCCC'),
- 'blue' => array('base' => '#E5F8FF', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'),
- 'midnight' => array('base' => '#F1F2F3', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'),
- 'sunrise' => array('base' => '#F3F1F1', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'),
- 'ectoplasm' => array('base' => '#ECE6F6', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'),
- 'ocean' => array('base' => '#F2FCFF', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'),
- 'coffee' => array('base' => '#F3F2F1', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'),
-];
-
-/*
- * On a specific menu page?
- *
- * @since 151002 Improving multisite compat.
- *
- * @param string $which Which page to check; may contain wildcards.
- *
- * @return boolean True if is the menu page.
- */
-$self->isMenuPage = function ($which) use ($self) {
- if (!($which = trim((string) $which))) {
- return false; // Empty.
+ $links[] = ''.__('Settings', SLUG_TD).'';
+ if (!IS_PRO) {
+ $links[] = '
'.__('Preview Pro Features', SLUG_TD).'';
+ $links[] = ''.__('Upgrade', SLUG_TD).'';
+ }
+ return $links;
}
- if (!is_admin()) {
- return false;
+
+ /*
+ * Fills menu page inline SVG icon color.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $svg Inline SVG icon markup.
+ *
+ * @return string Inline SVG icon markup.
+ */
+ public function colorSvgMenuIcon($svg)
+ {
+ if (!($color = get_user_option('admin_color'))) {
+ $color = 'fresh'; // Default color scheme.
+ }
+ if (empty($this->wp_admin_icon_colors[$color])) {
+ return $svg; // Not possible.
+ }
+ $icon_colors = $this->wp_admin_icon_colors[$color];
+ $use_icon_fill_color = $icon_colors['base']; // Default base.
+
+ $current_pagenow = !empty($GLOBALS['pagenow']) ? $GLOBALS['pagenow'] : '';
+ $current_page = !empty($_REQUEST['page']) ? $_REQUEST['page'] : '';
+
+ if (strpos($current_pagenow, GLOBAL_NS) === 0 || strpos($current_page, GLOBAL_NS) === 0) {
+ $use_icon_fill_color = $icon_colors['current'];
+ }
+ return str_replace(' fill="currentColor"', ' fill="'.esc_attr($use_icon_fill_color).'"', $svg);
}
- $page = $pagenow = ''; // Initialize.
- if (!empty($_REQUEST['page'])) {
- $page = (string) $_REQUEST['page'];
+ /*
+ * Loads the admin menu page options.
+ *
+ * @since 150422 Rewrite.
+ */
+ public function menuPageOptions()
+ {
+ new MenuPage('options');
}
- if (!empty($GLOBALS['pagenow'])) {
- $pagenow = (string) $GLOBALS['pagenow'];
+
+ /*[pro strip-from="lite"]*/
+ /*
+ * Loads admin menu page for stats.
+ *
+ * @since 151002 Directory stats.
+ */
+ public function menuPageStats()
+ {
+ new MenuPage('stats');
}
- if ($page && fnmatch($which, $page, FNM_CASEFOLD)) {
- return true; // Wildcard match.
+ /*[/pro]*/
+
+ /*[pro strip-from="lite"]*/
+ /*
+ * Loads admin menu page for pro updater.
+ *
+ * @since 150422 Rewrite.
+ */
+ public function menuPageProUpdater()
+ {
+ new MenuPage('pro-updater');
}
- if ($pagenow && fnmatch($which, $pagenow, FNM_CASEFOLD)) {
- return true; // Wildcard match.
+ /*[/pro]*/
+
+ /*
+ * WordPress admin icon color schemes.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @type array WP admin icon colors.
+ *
+ * @note These must be hard-coded, because they don't become available
+ * in core until `admin_init`; i.e., too late for `admin_menu`.
+ */
+ public $wp_admin_icon_colors = [
+ 'fresh' => ['base' => '#999999', 'focus' => '#2EA2CC', 'current' => '#FFFFFF'],
+ 'light' => ['base' => '#999999', 'focus' => '#CCCCCC', 'current' => '#CCCCCC'],
+ 'blue' => ['base' => '#E5F8FF', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'],
+ 'midnight' => ['base' => '#F1F2F3', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'],
+ 'sunrise' => ['base' => '#F3F1F1', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'],
+ 'ectoplasm' => ['base' => '#ECE6F6', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'],
+ 'ocean' => ['base' => '#F2FCFF', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'],
+ 'coffee' => ['base' => '#F3F2F1', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'],
+ ];
+
+ /*
+ * On a specific menu page?
+ *
+ * @since 151002 Improving multisite compat.
+ *
+ * @param string $which Which page to check; may contain wildcards.
+ *
+ * @return boolean True if is the menu page.
+ */
+ public function isMenuPage($which)
+ {
+ if (!($which = trim((string) $which))) {
+ return false; // Empty.
+ }
+ if (!is_admin()) {
+ return false;
+ }
+ $page = $pagenow = ''; // Initialize.
+
+ if (!empty($_REQUEST['page'])) {
+ $page = (string) $_REQUEST['page'];
+ }
+ if (!empty($GLOBALS['pagenow'])) {
+ $pagenow = (string) $GLOBALS['pagenow'];
+ }
+ if ($page && fnmatch($which, $page, FNM_CASEFOLD)) {
+ return true; // Wildcard match.
+ }
+ if ($pagenow && fnmatch($which, $pagenow, FNM_CASEFOLD)) {
+ return true; // Wildcard match.
+ }
+ return false; // Nope.
}
- return false; // Nope.
-};
+}
diff --git a/src/includes/traits/Plugin/NoticeUtils.php b/src/includes/traits/Plugin/NoticeUtils.php
index 5fcc0d34..14803eb0 100644
--- a/src/includes/traits/Plugin/NoticeUtils.php
+++ b/src/includes/traits/Plugin/NoticeUtils.php
@@ -1,296 +1,308 @@
enqueueNotice = function ($notice, array $args = array(), $blog_id = 0) use ($self) {
- $notice = trim((string) $notice);
- $blog_id = (integer) $blog_id;
-
- if (!$notice) {
- return; // Nothing to do.
- }
- $notice = array('notice' => $notice);
- $notice = $self->normalizeNotice($notice, $args);
- $key = sha1(serialize($notice)); // Prevent dupes.
+trait NoticeUtils {
+ /*
+ * Notice queue handlers.
+ */
+
+ /*
+ * Enqueue an administrative notice.
+ *
+ * @since 150422 Rewrite. Improved 151002.
+ *
+ * @param string $notice HTML markup containing the notice itself.
+ * @param string $args Any additional arguments supported by the notice API in this plugin.
+ * @param integer $blog_id Optional. Defaults to the current blog ID. Use any value `< 0` to indicate the main site.
+ *
+ * @return string A unique key generated for this notice.
+ */
+ public function enqueueNotice($notice, array $args = [], $blog_id = 0)
+ {
+ $notice = trim((string) $notice);
+ $blog_id = (integer) $blog_id;
+
+ if (!$notice) {
+ return; // Nothing to do.
+ }
+ $notice = ['notice' => $notice];
+ $notice = $this->normalizeNotice($notice, $args);
+ $key = sha1(serialize($notice)); // Prevent dupes.
- $notices = $self->getNotices($blog_id);
+ $notices = $this->getNotices($blog_id);
- if ($notice['push_to_top']) {
- $notices = array($key => $notice) + $notices;
- } else {
- $notices[$key] = $notice; // Default behavior.
- }
- $self->updateNotices($notices, $blog_id);
-
- return $key; // For dismissals.
-};
-
-/*
- * Dismiss an administrative notice.
- *
- * @since 151002 Improving multisite compat.
- *
- * @param string $key_to_dismiss A unique key which identifies a particular notice.
- * Or, a persistent key which identifies one or more persistent notices.
- *
- * @param integer $blog_id The blog ID from which to dismiss the notice.
- *
- * @return array All remaining notices.
- */
-$self->dismissNotice = function ($key_to_dismiss, $blog_id = 0) use ($self) {
- $key_to_dismiss = trim((string) $key_to_dismiss);
- $blog_id = (integer) $blog_id; // For multisite compat.
- $notices = $enqueued_notices = $self->getNotices($blog_id);
-
- if (!$key_to_dismiss) {
- return $notices; // Nothing to do.
- }
- foreach ($notices as $_key => $_notice) {
- if ($_key === $key_to_dismiss) {
- unset($notices[$_key]); // A specific key.
- } elseif ($_notice['persistent_key'] === $key_to_dismiss) {
- unset($notices[$_key]); // All matching keys.
+ if ($notice['push_to_top']) {
+ $notices = [$key => $notice] + $notices;
+ } else {
+ $notices[$key] = $notice; // Default behavior.
}
- } // ↑ Dismisses all matching keys.
- unset($_key, $_notice); // Housekeeping.
+ $this->updateNotices($notices, $blog_id);
- if ($notices !== $enqueued_notices) { // Something changed?
- $self->updateNotices($notices, $blog_id); // Update.
+ return $key; // For dismissals.
}
- return $notices; // All remaining notices.
-};
-
-/*
- * Enqueue an administrative error notice.
- *
- * @since 150422 Rewrite. Improved 151002.
- */
-$self->enqueueError = function ($notice, array $args = array(), $blog_id = 0) use ($self) {
- return $self->enqueueNotice($notice, array_merge($args, array('class' => 'error')), $blog_id);
-};
-
-/*
- * Enqueue an administrative notice (main site).
- *
- * @since 151002. Improving multisite compat.
- */
-$self->enqueueMainNotice = function ($notice, array $args = array()) use ($self) {
- return $self->enqueueNotice($notice, $args, -1);
-};
-
-/*
- * Enqueue an administrative error notice (main site).
- *
- * @since 151002. Improving multisite compat.
- */
-$self->enqueueMainError = function ($notice, array $args = array()) use ($self) {
- return $self->enqueueNotice($notice, array_merge($args, array('class' => 'error')), -1);
-};
-
-/*
- * Dismiss an administrative notice (main site).
- *
- * @since 151002 Improving multisite compat.
- */
-$self->dismissMainNotice = function ($key_to_dismiss) use ($self) {
- return $self->dismissNotice($key_to_dismiss, -1);
-};
-
-/*
- * Notice display handler.
- */
-
-/*
- * Render admin notices.
- *
- * @since 150422 Rewrite. Improved 151002.
- *
- * @attaches-to `all_admin_notices` hook.
- */
-$self->allAdminNotices = function () use ($self) {
- $notices = $enqueued_notices = $self->getNotices();
-
- foreach ($notices as $_key => $_notice) {
- # Always dismiss all non-persistent transients.
-
- if ($_notice['is_transient'] && !$_notice['persistent_key']) {
- unset($notices[$_key]); // Dismiss.
- }
- # Current user can see this notice?
-
- if (!current_user_can($self->cap)) {
- continue; // Current user unable to see.
- }
- if ($_notice['cap_required'] && !current_user_can($_notice['cap_required'])) {
- continue; // Current user unable to see this notice.
- }
- # Current URI matches a limited scope/context for this notice?
- if ($_notice['only_on_uris'] && !@preg_match($_notice['only_on_uris'], $_SERVER['REQUEST_URI'])) {
- continue; // Not in the right context at the moment; i.e., does not regex.
+ /*
+ * Dismiss an administrative notice.
+ *
+ * @since 151002 Improving multisite compat.
+ *
+ * @param string $key_to_dismiss A unique key which identifies a particular notice.
+ * Or, a persistent key which identifies one or more persistent notices.
+ *
+ * @param integer $blog_id The blog ID from which to dismiss the notice.
+ *
+ * @return array All remaining notices.
+ */
+ public function dismissNotice($key_to_dismiss, $blog_id = 0)
+ {
+ $key_to_dismiss = trim((string) $key_to_dismiss);
+ $blog_id = (integer) $blog_id; // For multisite compat.
+ $notices = $enqueued_notices = $this->getNotices($blog_id);
+
+ if (!$key_to_dismiss) {
+ return $notices; // Nothing to do.
}
- # If persistent, allow a site owner to dismiss.
-
- $_dismiss = ''; // Reset this to its default state.
- if ($_notice['persistent_key'] && $_notice['dismissable']) { // See above. The `dismissNotice()` action requires `$self->cap` always.
- $_dismiss = add_query_arg(urlencode_deep(array(GLOBAL_NS => array('dismissNotice' => array('key' => $_key)), '_wpnonce' => wp_create_nonce())));
- $_dismiss = ''.__('dismiss ×', SLUG_TD).'';
+ foreach ($notices as $_key => $_notice) {
+ if ($_key === $key_to_dismiss) {
+ unset($notices[$_key]); // A specific key.
+ } elseif ($_notice['persistent_key'] === $key_to_dismiss) {
+ unset($notices[$_key]); // All matching keys.
+ }
+ } // ↑ Dismisses all matching keys.
+ unset($_key, $_notice); // Housekeeping.
+
+ if ($notices !== $enqueued_notices) { // Something changed?
+ $this->updateNotices($notices, $blog_id); // Update.
}
- # Display this notice. If not persistent, we can dismiss it too.
+ return $notices; // All remaining notices.
+ }
- echo ''.$_notice['notice'].$_dismiss.'
';
+ /*
+ * Enqueue an administrative error notice.
+ *
+ * @since 150422 Rewrite. Improved 151002.
+ */
+ public function enqueueError($notice, array $args = [], $blog_id = 0)
+ {
+ return $this->enqueueNotice($notice, array_merge($args, ['class' => 'error']), $blog_id);
+ }
- if (!$_notice['persistent_key']) { // If not persistent, dismiss.
- unset($notices[$_key]); // Dismiss; this notice has been displayed now.
- }
+ /*
+ * Enqueue an administrative notice (main site).
+ *
+ * @since 151002. Improving multisite compat.
+ */
+ public function enqueueMainNotice($notice, array $args = [])
+ {
+ return $this->enqueueNotice($notice, $args, -1);
}
- unset($_key, $_notice, $_dismiss); // Housekeeping.
- # Update notices if something changed above.
+ /*
+ * Enqueue an administrative error notice (main site).
+ *
+ * @since 151002. Improving multisite compat.
+ */
+ public function enqueueMainError($notice, array $args = [])
+ {
+ return $this->enqueueNotice($notice, array_merge($args, ['class' => 'error']), -1);
+ }
- if ($notices !== $enqueued_notices) { // Something changed?
- $self->updateNotices($notices); // Update.
+ /*
+ * Dismiss an administrative notice (main site).
+ *
+ * @since 151002 Improving multisite compat.
+ */
+ public function dismissMainNotice($key_to_dismiss)
+ {
+ return $this->dismissNotice($key_to_dismiss, -1);
}
-};
-
-/*
- * Notice getter/setter.
- */
-
-/*
- * Get admin notices.
- *
- * @since 151002 Improving multisite compat.
- *
- * @param integer $blog_id Optional. Defaults to the current blog ID.
- * Use any value `< 0` to indicate the main site.
- *
- * @return array All notices.
- */
-$self->getNotices = function ($blog_id = 0) use ($self) {
- if (is_multisite()) {
- if (!($blog_id = (integer) $blog_id)) {
- $blog_id = (integer) get_current_blog_id();
+
+ /*
+ * Notice display handler.
+ */
+
+ /*
+ * Render admin notices.
+ *
+ * @since 150422 Rewrite. Improved 151002.
+ *
+ * @attaches-to `all_admin_notices` hook.
+ */
+ public function allAdminNotices()
+ {
+ $notices = $enqueued_notices = $this->getNotices();
+
+ foreach ($notices as $_key => $_notice) {
+ # Always dismiss all non-persistent transients.
+
+ if ($_notice['is_transient'] && !$_notice['persistent_key']) {
+ unset($notices[$_key]); // Dismiss.
+ }
+ # Current user can see this notice?
+
+ if (!current_user_can($this->cap)) {
+ continue; // Current user unable to see.
+ }
+ if ($_notice['cap_required'] && !current_user_can($_notice['cap_required'])) {
+ continue; // Current user unable to see this notice.
+ }
+ # Current URI matches a limited scope/context for this notice?
+
+ if ($_notice['only_on_uris'] && !@preg_match($_notice['only_on_uris'], $_SERVER['REQUEST_URI'])) {
+ continue; // Not in the right context at the moment; i.e., does not regex.
+ }
+ # If persistent, allow a site owner to dismiss.
+
+ $_dismiss = ''; // Reset this to its default state.
+ if ($_notice['persistent_key'] && $_notice['dismissable']) { // See above. The `dismissNotice()` action requires `$this->cap` always.
+ $_dismiss = add_query_arg(urlencode_deep([GLOBAL_NS => ['dismissNotice' => ['key' => $_key]], '_wpnonce' => wp_create_nonce()]));
+ $_dismiss = ''.__('dismiss ×', SLUG_TD).'';
+ }
+ # Display this notice. If not persistent, we can dismiss it too.
+
+ echo ''.$_notice['notice'].$_dismiss.'
';
+
+ if (!$_notice['persistent_key']) { // If not persistent, dismiss.
+ unset($notices[$_key]); // Dismiss; this notice has been displayed now.
+ }
}
- if ($blog_id < 0) { // Blog for main site.
- $blog_id = (integer) get_current_site()->blog_id;
+ unset($_key, $_notice, $_dismiss); // Housekeeping.
+
+ # Update notices if something changed above.
+
+ if ($notices !== $enqueued_notices) { // Something changed?
+ $this->updateNotices($notices); // Update.
}
- $blog_suffix = '_'.$blog_id; // Site option suffix.
- $notices = get_site_option(GLOBAL_NS.$blog_suffix.'_notices');
- } else {
- $notices = get_site_option(GLOBAL_NS.'_notices');
- }
- if (!is_array($notices)) {
- $notices = array(); // Force array.
- // Prevent multiple DB queries by adding this key.
- $self->updateNotices($notices, $blog_id);
}
- foreach ($notices as $_key => &$_notice) {
- if (!is_string($_key) || !is_array($_notice) || empty($_notice['notice'])) {
- unset($notices[$_key]); // Old notice.
- continue; // Bypass; i.e., do not normalize.
- }
- $_notice = $self->normalizeNotice($_notice);
- } // ↑ Typecast/normalized each of the array elements.
- unset($_key, $_notice); // Housekeeping.
-
- return $notices;
-};
-
-/*
- * Update admin notices.
- *
- * @since 151002 Improving multisite compat.
- *
- * @param array $notices New array of notices.
- *
- * @param integer $blog_id Optional. Defaults to the current blog ID.
- * Use any value `< 0` to indicate the main site.
- *
- * @return array All notices.
- */
-$self->updateNotices = function (array $notices, $blog_id = 0) use ($self) {
- if (is_multisite()) {
- if (!($blog_id = (integer) $blog_id)) {
- $blog_id = (integer) get_current_blog_id();
+
+ /*
+ * Notice getter/setter.
+ */
+
+ /*
+ * Get admin notices.
+ *
+ * @since 151002 Improving multisite compat.
+ *
+ * @param integer $blog_id Optional. Defaults to the current blog ID.
+ * Use any value `< 0` to indicate the main site.
+ *
+ * @return array All notices.
+ */
+ public function getNotices($blog_id = 0)
+ {
+ if (is_multisite()) {
+ if (!($blog_id = (integer) $blog_id)) {
+ $blog_id = (integer) get_current_blog_id();
+ }
+ if ($blog_id < 0) { // Blog for main site.
+ $blog_id = (integer) get_current_site()->blog_id;
+ }
+ $blog_suffix = '_'.$blog_id; // Site option suffix.
+ $notices = get_site_option(GLOBAL_NS.$blog_suffix.'_notices');
+ } else {
+ $notices = get_site_option(GLOBAL_NS.'_notices');
}
- if ($blog_id < 0) { // Blog for main site.
- $blog_id = (integer) get_current_site()->blog_id;
+ if (!is_array($notices)) {
+ $notices = []; // Force array.
+ // Prevent multiple DB queries by adding this key.
+ $this->updateNotices($notices, $blog_id);
}
- $blog_suffix = '_'.$blog_id; // Site option suffix.
- update_site_option(GLOBAL_NS.$blog_suffix.'_notices', $notices);
- } else {
- update_site_option(GLOBAL_NS.'_notices', $notices);
+ foreach ($notices as $_key => &$_notice) {
+ if (!is_string($_key) || !is_array($_notice) || empty($_notice['notice'])) {
+ unset($notices[$_key]); // Old notice.
+ continue; // Bypass; i.e., do not normalize.
+ }
+ $_notice = $this->normalizeNotice($_notice);
+ } // ↑ Typecast/normalized each of the array elements.
+ unset($_key, $_notice); // Housekeeping.
+
+ return $notices;
}
- return $notices;
-};
-
-/*
- * Notice property utilities.
- */
-
-/*
-* Normalize notice elements.
-*
-* @since 151002 Improving multisite compat.
-*
-* @param array $notice Notice array elements.
-* @param array $args Any additional array elements.
-*
-* @return array Normalized notice array elements.
-*/
-$self->normalizeNotice = function (array $notice, array $args = array()) use ($self) {
- $notice_defaults = array(
- 'notice' => '',
- 'only_on_uris' => '',
- 'persistent_key' => '',
- 'dismissable' => true,
- 'is_transient' => true,
- 'push_to_top' => false,
- 'class' => 'updated',
- 'cap_required' => '', // `$self->cap` always.
- // i.e., this cap is in addition to `$self->cap`.
- );
- $notice = array_merge($notice_defaults, $notice, $args);
- $notice = array_intersect_key($notice, $notice_defaults);
-
- foreach ($notice as $_key => &$_value) {
- switch ($_key) {
- case 'notice':
- case 'only_on_uris':
- case 'persistent_key':
- $_value = trim((string) $_value);
- break; // Stop here.
-
- case 'is_transient':
- case 'push_to_top':
- case 'dismissable':
- $_value = (boolean) $_value;
- break; // Stop here.
-
- case 'class':
- case 'cap_required':
- $_value = trim((string) $_value);
- break; // Stop here.
- }
- } // ↑ Typecast each of the array elements.
- unset($_key, $_value); // A little housekeeping.
- ksort($notice); // For more accurate comparison in other routines.
+ /*
+ * Update admin notices.
+ *
+ * @since 151002 Improving multisite compat.
+ *
+ * @param array $notices New array of notices.
+ *
+ * @param integer $blog_id Optional. Defaults to the current blog ID.
+ * Use any value `< 0` to indicate the main site.
+ *
+ * @return array All notices.
+ */
+ public function updateNotices(array $notices, $blog_id = 0)
+ {
+ if (is_multisite()) {
+ if (!($blog_id = (integer) $blog_id)) {
+ $blog_id = (integer) get_current_blog_id();
+ }
+ if ($blog_id < 0) { // Blog for main site.
+ $blog_id = (integer) get_current_site()->blog_id;
+ }
+ $blog_suffix = '_'.$blog_id; // Site option suffix.
+ update_site_option(GLOBAL_NS.$blog_suffix.'_notices', $notices);
+ } else {
+ update_site_option(GLOBAL_NS.'_notices', $notices);
+ }
+ return $notices;
+ }
- return $notice; // Normalized.
-};
+ /*
+ * Notice property utilities.
+ */
+
+ /*
+ * Normalize notice elements.
+ *
+ * @since 151002 Improving multisite compat.
+ *
+ * @param array $notice Notice array elements.
+ * @param array $args Any additional array elements.
+ *
+ * @return array Normalized notice array elements.
+ */
+ public function normalizeNotice(array $notice, array $args = [])
+ {
+ $notice_defaults = [
+ 'notice' => '',
+ 'only_on_uris' => '',
+ 'persistent_key' => '',
+ 'dismissable' => true,
+ 'is_transient' => true,
+ 'push_to_top' => false,
+ 'class' => 'updated',
+ 'cap_required' => '', // `$this->cap` always.
+ // i.e., this cap is in addition to `$this->cap`.
+ ];
+ $notice = array_merge($notice_defaults, $notice, $args);
+ $notice = array_intersect_key($notice, $notice_defaults);
+
+ foreach ($notice as $_key => &$_value) {
+ switch ($_key) {
+ case 'notice':
+ case 'only_on_uris':
+ case 'persistent_key':
+ $_value = trim((string) $_value);
+ break; // Stop here.
+
+ case 'is_transient':
+ case 'push_to_top':
+ case 'dismissable':
+ $_value = (boolean) $_value;
+ break; // Stop here.
+
+ case 'class':
+ case 'cap_required':
+ $_value = trim((string) $_value);
+ break; // Stop here.
+ }
+ } // ↑ Typecast each of the array elements.
+ unset($_key, $_value); // A little housekeeping.
+
+ ksort($notice); // For more accurate comparison in other routines.
+
+ return $notice; // Normalized.
+ }
+}
diff --git a/src/includes/traits/Plugin/OptionUtils.php b/src/includes/traits/Plugin/OptionUtils.php
index 9aa82067..476df2c5 100644
--- a/src/includes/traits/Plugin/OptionUtils.php
+++ b/src/includes/traits/Plugin/OptionUtils.php
@@ -1,70 +1,76 @@
getOptions = function () use ($self) {
- if (!($options = $self->options)) { // Not defined yet?
- if (!is_array($options = get_site_option(GLOBAL_NS.'_options'))) {
- $options = array(); // Force array.
+trait OptionUtils {
+ /*
+ * Get plugin options.
+ *
+ * @since 151002 Improving multisite compat.
+ *
+ * @return array Plugin options.
+ */
+ public function getOptions()
+ {
+ if (!($options = $this->options)) { // Not defined yet?
+ if (!is_array($options = get_site_option(GLOBAL_NS.'_options'))) {
+ $options = []; // Force array.
+ }
+ if (!$options && is_array($zencache_options = get_site_option('zencache_options'))) {
+ $options = $zencache_options; // Old ZenCache options.
+ $options['crons_setup'] = $this->default_options['crons_setup'];
+ }
}
- if (!$options && is_array($zencache_options = get_site_option('zencache_options'))) {
- $options = $zencache_options; // Old ZenCache options.
- $options['crons_setup'] = $this->default_options['crons_setup'];
+ $this->options = array_merge($this->default_options, $options);
+ $this->options = $this->applyWpFilters(GLOBAL_NS.'_options', $this->options);
+ $this->options = array_intersect_key($this->options, $this->default_options);
+
+ foreach ($this->options as $_key => &$_value) {
+ $_value = trim((string) $_value); // Force strings.
+ }
+ unset($_key, $_value); // Housekeeping.
+
+ $this->options['base_dir'] = trim($this->options['base_dir'], '\\/'." \t\n\r\0\x0B");
+ if (!$this->options['base_dir'] || strpos(basename($this->options['base_dir']), 'wp-') === 0) {
+ $this->options['base_dir'] = $this->default_options['base_dir'];
}
+ return $this->options; // Plugin options.
}
- $self->options = array_merge($self->default_options, $options);
- $self->options = $self->applyWpFilters(GLOBAL_NS.'_options', $self->options);
- $self->options = array_intersect_key($self->options, $self->default_options);
- foreach ($self->options as $_key => &$_value) {
- $_value = trim((string) $_value); // Force strings.
- } unset($_key, $_value); // Housekeeping.
+ /*
+ * Update plugin options.
+ *
+ * @since 151002 Improving multisite compat.
+ *
+ * @param array $options One or more new options.
+ *
+ * @return array Plugin options after update.
+ */
+ public function updateOptions(array $options)
+ {
+ if (!IS_PRO) { // Do not save Pro option keys.
+ $options = array_diff_key($options, $this->pro_only_option_keys);
+ }
+ if (!empty($options['base_dir']) && $options['base_dir'] !== $this->options['base_dir']) {
+ $this->tryErasingAllFilesDirsIn($this->wpContentBaseDirTo(''));
+ }
+ $this->options = array_merge($this->default_options, $this->options, $options);
+ $this->options = array_intersect_key($this->options, $this->default_options);
+ update_site_option(GLOBAL_NS.'_options', $this->options);
- $self->options['base_dir'] = trim($self->options['base_dir'], '\\/'." \t\n\r\0\x0B");
- if (!$self->options['base_dir'] || strpos(basename($self->options['base_dir']), 'wp-') === 0) {
- $self->options['base_dir'] = $self->default_options['base_dir'];
+ return $this->getOptions();
}
- return $self->options; // Plugin options.
-};
-/*
- * Update plugin options.
- *
- * @since 151002 Improving multisite compat.
- *
- * @param array $options One or more new options.
- *
- * @return array Plugin options after update.
- */
-$self->updateOptions = function (array $options) use ($self) {
- if (!IS_PRO) { // Do not save Pro option keys.
- $options = array_diff_key($options, $self->pro_only_option_keys);
- }
- if (!empty($options['base_dir']) && $options['base_dir'] !== $self->options['base_dir']) {
- $self->tryErasingAllFilesDirsIn($self->wpContentBaseDirTo(''));
+ /*
+ * Restore default plugin options.
+ *
+ * @since 151002 Improving multisite compat.
+ *
+ * @return array Plugin options after update.
+ */
+ public function restoreDefaultOptions()
+ {
+ delete_site_option(GLOBAL_NS.'_options'); // Force restore.
+ $this->options = $this->default_options; // In real-time.
+ return $this->getOptions();
}
- $self->options = array_merge($self->default_options, $self->options, $options);
- $self->options = array_intersect_key($self->options, $self->default_options);
- update_site_option(GLOBAL_NS.'_options', $self->options);
-
- return $self->getOptions();
-};
-
-/*
- * Restore default plugin options.
- *
- * @since 151002 Improving multisite compat.
- *
- * @return array Plugin options after update.
- */
-$self->restoreDefaultOptions = function () use ($self) {
- delete_site_option(GLOBAL_NS.'_options'); // Force restore.
- $self->options = $self->default_options; // In real-time.
- return $self->getOptions();
-};
+}
diff --git a/src/includes/traits/Plugin/PostUtils.php b/src/includes/traits/Plugin/PostUtils.php
index 2c616aed..bdfc4fb1 100644
--- a/src/includes/traits/Plugin/PostUtils.php
+++ b/src/includes/traits/Plugin/PostUtils.php
@@ -1,42 +1,46 @@
postStatuses = function () use ($self) {
- if (!is_null($statuses = &$self->cacheKey('postStatuses'))) {
- return $statuses; // Already did this.
- }
- $statuses = get_post_stati();
- $statuses = array_keys($statuses);
-
- return $statuses;
-};
+trait PostUtils {
+ /*
+ * All post statuses.
+ *
+ * @since 150821 Improving bbPress support.
+ *
+ * @return array All post statuses.
+ */
+ public function postStatuses()
+ {
+ if (!is_null($statuses = &$this->cacheKey('postStatuses'))) {
+ return $statuses; // Already did this.
+ }
+ $statuses = get_post_stati();
+ $statuses = array_keys($statuses);
-/*
- * All built-in post statuses.
- *
- * @since 150821 Improving bbPress support.
- *
- * @return array All built-in post statuses.
- */
-$self->builtInPostStatuses = function () use ($self) {
- if (!is_null($statuses = &$self->cacheKey('builtInPostStatuses'))) {
- return $statuses; // Already did this.
+ return $statuses;
}
- $statuses = array(); // Initialize.
- foreach (get_post_stati(array(), 'objects') as $_key => $_status) {
- if (!empty($_status->_builtin)) {
- $statuses[] = $_status->name;
+ /*
+ * All built-in post statuses.
+ *
+ * @since 150821 Improving bbPress support.
+ *
+ * @return array All built-in post statuses.
+ */
+ public function builtInPostStatuses()
+ {
+ if (!is_null($statuses = &$this->cacheKey('builtInPostStatuses'))) {
+ return $statuses; // Already did this.
}
- }
- unset($_key, $_status); // Housekeeping.
+ $statuses = []; // Initialize.
- return $statuses;
-};
+ foreach (get_post_stati([], 'objects') as $_key => $_status) {
+ if (!empty($_status->_builtin)) {
+ $statuses[] = $_status->name;
+ }
+ }
+ unset($_key, $_status); // Housekeeping.
+
+ return $statuses;
+ }
+}
diff --git a/src/includes/traits/Plugin/StatsUtils.php b/src/includes/traits/Plugin/StatsUtils.php
index 4a6fe532..2d8ba9a3 100644
--- a/src/includes/traits/Plugin/StatsUtils.php
+++ b/src/includes/traits/Plugin/StatsUtils.php
@@ -2,42 +2,45 @@
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Traits\Plugin;
-/*
- * Pings our stats log w/ anonymous details.
- *
- * @since 150716 Adding stats logging.
- *
- * @attaches-to `admin_init` hook.
- *
- * @see https://cometcache.com/?p=2426
- */
-$self->statsLogPinger = function () use ($self) {
- if (!$self->applyWpFilters(GLOBAL_NS.'_statsLogPinger_enable', IS_PRO)) {
- return; // Stats collection disabled by site.
- }
- if ($self->options['last_pro_stats_log'] >= strtotime('-1 week')) {
- return; // No reason to keep pinging.
- }
- $self->updateOptions(array('last_pro_stats_log' => time()));
+trait StatsUtils {
+ /*
+ * Pings our stats log w/ anonymous details.
+ *
+ * @since 150716 Adding stats logging.
+ *
+ * @attaches-to `admin_init` hook.
+ *
+ * @see https://cometcache.com/?p=2426
+ */
+ public function statsLogPinger()
+ {
+ if (!$this->applyWpFilters(GLOBAL_NS.'_statsLogPinger_enable', IS_PRO)) {
+ return; // Stats collection disabled by site.
+ }
+ if ($this->options['last_pro_stats_log'] >= strtotime('-1 week')) {
+ return; // No reason to keep pinging.
+ }
+ $this->updateOptions(['last_pro_stats_log' => time()]);
- $wpdb = $self->wpdb(); // WordPress DB.
- $stats_api_url = 'https://stats.wpsharks.io/log';
- $stats_api_url_args = array( // See:
- 'os' => PHP_OS,
- 'php_version' => PHP_VERSION,
- 'mysql_version' => $wpdb->db_version(),
- 'wp_version' => get_bloginfo('version'),
- 'product_version' => VERSION, // Plugin version.
- 'product' => SLUG_TD.(IS_PRO ? '-pro' : ''),
- );
- $stats_api_url = add_query_arg(urlencode_deep($stats_api_url_args), $stats_api_url);
+ $wpdb = $this->wpdb(); // WordPress DB.
+ $stats_api_url = 'https://stats.wpsharks.io/log';
+ $stats_api_url_args = [ // See:
+ 'os' => PHP_OS,
+ 'php_version' => PHP_VERSION,
+ 'mysql_version' => $wpdb->db_version(),
+ 'wp_version' => get_bloginfo('version'),
+ 'product_version' => VERSION, // Plugin version.
+ 'product' => SLUG_TD.(IS_PRO ? '-pro' : ''),
+ ];
+ $stats_api_url = add_query_arg(urlencode_deep($stats_api_url_args), $stats_api_url);
- wp_remote_get(
- $stats_api_url,
- array(
- 'blocking' => false,
- 'sslverify' => false,
- )
- );
-};
+ wp_remote_get(
+ $stats_api_url,
+ [
+ 'blocking' => false,
+ 'sslverify' => false,
+ ]
+ );
+ }
+}
/*[/pro]*/
diff --git a/src/includes/traits/Plugin/UpdateUtils.php b/src/includes/traits/Plugin/UpdateUtils.php
index 0d0eda3f..345d912b 100644
--- a/src/includes/traits/Plugin/UpdateUtils.php
+++ b/src/includes/traits/Plugin/UpdateUtils.php
@@ -1,179 +1,185 @@
maybeCheckLatestLiteVersion = function () use ($self) {
- if (IS_PRO) {
- return; // Not applicable.
- }
- if (!$self->options['lite_update_check']) {
- return; // Nothing to do.
- }
- if (!current_user_can($self->update_cap)) {
- return; // Nothing to do.
- }
- if (is_multisite() && !current_user_can($self->network_cap)) {
- return; // Nothing to do.
- }
- if ($self->options['last_lite_update_check'] >= strtotime('-1 hour')) {
- return; // No reason to keep checking on this.
- }
- $self->updateOptions(array('last_lite_update_check' => time()));
+trait UpdateUtils {
+ /*
+ * Checks for a new lite release.
+ *
+ * @since 151220 Show version number in plugin options.
+ *
+ * @attaches-to `admin_init` hook.
+ */
+ public function maybeCheckLatestLiteVersion()
+ {
+ if (IS_PRO) {
+ return; // Not applicable.
+ }
+ if (!$this->options['lite_update_check']) {
+ return; // Nothing to do.
+ }
+ if (!current_user_can($this->update_cap)) {
+ return; // Nothing to do.
+ }
+ if (is_multisite() && !current_user_can($this->network_cap)) {
+ return; // Nothing to do.
+ }
+ if ($this->options['last_lite_update_check'] >= strtotime('-1 hour')) {
+ return; // No reason to keep checking on this.
+ }
+ $this->updateOptions(['last_lite_update_check' => time()]);
- $product_api_url = 'https://'.urlencode(DOMAIN).'/';
- $product_api_input_vars = array('product_api' => array('action' => 'latest_lite_version'));
+ $product_api_url = 'https://'.urlencode(DOMAIN).'/';
+ $product_api_input_vars = ['product_api' => ['action' => 'latest_lite_version']];
- $product_api_response = wp_remote_post($product_api_url, array('body' => $product_api_input_vars));
- $product_api_response = json_decode(wp_remote_retrieve_body($product_api_response));
+ $product_api_response = wp_remote_post($product_api_url, ['body' => $product_api_input_vars]);
+ $product_api_response = json_decode(wp_remote_retrieve_body($product_api_response));
- if (is_object($product_api_response) && !empty($product_api_response->lite_version)) {
- $self->updateOptions(array('latest_lite_version' => $product_api_response->lite_version));
+ if (is_object($product_api_response) && !empty($product_api_response->lite_version)) {
+ $this->updateOptions(['latest_lite_version' => $product_api_response->lite_version]);
+ }
+ // Disabling the notice for now. We only run this check to collect the latest version number.
+ #if ($this->options['latest_lite_version'] && version_compare(VERSION, $this->options['latest_lite_version'], '<')) {
+ # $this->dismissMainNotice('new-lite-version-available'); // Dismiss any existing notices like this.
+ # $lite_updater_page = network_admin_url('/plugins.php'); // In a network this points to the master plugins list.
+ # $this->enqueueMainNotice(sprintf(__('%1$s: a new version is now available. Please upgrade to v%3$s.', SLUG_TD), esc_html(NAME), esc_attr($lite_updater_page), esc_html($this->options['latest_lite_version'])), array('persistent_key' => 'new-lite-version-available'));
+ #}
}
- // Disabling the notice for now. We only run this check to collect the latest version number.
- #if ($self->options['latest_lite_version'] && version_compare(VERSION, $self->options['latest_lite_version'], '<')) {
- # $self->dismissMainNotice('new-lite-version-available'); // Dismiss any existing notices like this.
- # $lite_updater_page = network_admin_url('/plugins.php'); // In a network this points to the master plugins list.
- # $self->enqueueMainNotice(sprintf(__('%1$s: a new version is now available. Please upgrade to v%3$s.', SLUG_TD), esc_html(NAME), esc_attr($lite_updater_page), esc_html($self->options['latest_lite_version'])), array('persistent_key' => 'new-lite-version-available'));
- #}
-};
-/*[pro strip-from="lite"]*/
-/*
- * Checks for a new pro release.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `admin_init` hook.
- *
- * @see pre_site_transient_update_plugins()
- */
-$self->maybeCheckLatestProVersion = function () use ($self) {
- if (!$self->options['pro_update_check']) {
- return; // Nothing to do.
- }
- if (!current_user_can($self->update_cap)) {
- return; // Nothing to do.
- }
- if (is_multisite() && !current_user_can($self->network_cap)) {
- return; // Nothing to do.
- }
- if ($self->options['last_pro_update_check'] >= strtotime('-1 hour')) {
- return; // No reason to keep checking on this.
- }
- $self->updateOptions(array('last_pro_update_check' => time()));
+ /*[pro strip-from="lite"]*/
+ /*
+ * Checks for a new pro release.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `admin_init` hook.
+ *
+ * @see pre_site_transient_update_plugins()
+ */
+ public function maybeCheckLatestProVersion()
+ {
+ if (!$this->options['pro_update_check']) {
+ return; // Nothing to do.
+ }
+ if (!current_user_can($this->update_cap)) {
+ return; // Nothing to do.
+ }
+ if (is_multisite() && !current_user_can($this->network_cap)) {
+ return; // Nothing to do.
+ }
+ if ($this->options['last_pro_update_check'] >= strtotime('-1 hour')) {
+ return; // No reason to keep checking on this.
+ }
+ $this->updateOptions(['last_pro_update_check' => time()]);
- $product_api_url = 'https://'.urlencode(DOMAIN).'/';
- $product_api_input_vars = array('product_api' => array('action' => 'latest_pro_version'));
+ $product_api_url = 'https://'.urlencode(DOMAIN).'/';
+ $product_api_input_vars = ['product_api' => ['action' => 'latest_pro_version']];
- $product_api_response = wp_remote_post($product_api_url, array('body' => $product_api_input_vars));
- $product_api_response = json_decode(wp_remote_retrieve_body($product_api_response));
+ $product_api_response = wp_remote_post($product_api_url, ['body' => $product_api_input_vars]);
+ $product_api_response = json_decode(wp_remote_retrieve_body($product_api_response));
- if (is_object($product_api_response) && !empty($product_api_response->pro_version)) {
- $self->updateOptions(array('latest_pro_version' => $product_api_response->pro_version));
+ if (is_object($product_api_response) && !empty($product_api_response->pro_version)) {
+ $this->updateOptions(['latest_pro_version' => $product_api_response->pro_version]);
+ }
+ if ($this->options['latest_pro_version'] && version_compare(VERSION, $this->options['latest_pro_version'], '<')) {
+ $this->dismissMainNotice('new-pro-version-available'); // Dismiss any existing notices like this.
+ $pro_updater_page = add_query_arg(urlencode_deep(['page' => GLOBAL_NS.'-pro-updater']), network_admin_url('/admin.php'));
+ $this->enqueueMainNotice(sprintf(__('%1$s Pro: a new version is now available. Please upgrade to v%3$s.', SLUG_TD), esc_html(NAME), esc_attr($pro_updater_page), esc_html($this->options['latest_pro_version'])), ['persistent_key' => 'new-pro-version-available']);
+ }
}
- if ($self->options['latest_pro_version'] && version_compare(VERSION, $self->options['latest_pro_version'], '<')) {
- $self->dismissMainNotice('new-pro-version-available'); // Dismiss any existing notices like this.
- $pro_updater_page = add_query_arg(urlencode_deep(array('page' => GLOBAL_NS.'-pro-updater')), network_admin_url('/admin.php'));
- $self->enqueueMainNotice(sprintf(__('%1$s Pro: a new version is now available. Please upgrade to v%3$s.', SLUG_TD), esc_html(NAME), esc_attr($pro_updater_page), esc_html($self->options['latest_pro_version'])), array('persistent_key' => 'new-pro-version-available'));
- }
-};
-/*
- * Modifies transient data associated with this plugin.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `pre_site_transient_update_plugins` filter.
- *
- * @param object $transient Transient data provided by the WP filter.
- *
- * @return object Transient object; possibly altered by this routine.
- */
-$self->preSiteTransientUpdatePlugins = function ($transient) use ($self) {
- if (!current_user_can($self->update_cap)) {
- return $transient; // Nothing to do.
- }
- if (is_multisite() && !current_user_can($self->network_cap)) {
- return $transient; // Nothing to do.
- }
- if (!is_admin() || $GLOBALS['pagenow'] !== 'update.php') {
- return $transient; // Nothing to do.
- }
- $_r = $self->trimDeep(stripslashes_deep($_REQUEST));
+ /*
+ * Modifies transient data associated with this plugin.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `pre_site_transient_update_plugins` filter.
+ *
+ * @param object $transient Transient data provided by the WP filter.
+ *
+ * @return object Transient object; possibly altered by this routine.
+ */
+ public function preSiteTransientUpdatePlugins($transient)
+ {
+ if (!current_user_can($this->update_cap)) {
+ return $transient; // Nothing to do.
+ }
+ if (is_multisite() && !current_user_can($this->network_cap)) {
+ return $transient; // Nothing to do.
+ }
+ if (!is_admin() || $GLOBALS['pagenow'] !== 'update.php') {
+ return $transient; // Nothing to do.
+ }
+ $_r = $this->trimDeep(stripslashes_deep($_REQUEST));
- if (empty($_r['action']) || $_r['action'] !== 'upgrade-plugin') {
- return $transient; // Nothing to do here.
- }
- if (empty($_r['_wpnonce']) || !wp_verify_nonce((string) $_r['_wpnonce'], 'upgrade-plugin_'.plugin_basename(PLUGIN_FILE))) {
- return $transient; // Nothing to do here.
- }
- if (empty($_r[GLOBAL_NS.'_update_pro_version']) || empty($_r[GLOBAL_NS.'_update_pro_zip'])) {
- return $transient; // Nothing to do here.
- }
- $update_pro_version = (string) $_r[GLOBAL_NS.'_update_pro_version'];
- $update_pro_zip = base64_decode((string) $_r[GLOBAL_NS.'_update_pro_zip'], true);
- // @TODO Encrypt/decrypt to avoid mod_security issues. Base64 is not enough.
+ if (empty($_r['action']) || $_r['action'] !== 'upgrade-plugin') {
+ return $transient; // Nothing to do here.
+ }
+ if (empty($_r['_wpnonce']) || !wp_verify_nonce((string) $_r['_wpnonce'], 'upgrade-plugin_'.plugin_basename(PLUGIN_FILE))) {
+ return $transient; // Nothing to do here.
+ }
+ if (empty($_r[GLOBAL_NS.'_update_pro_version']) || empty($_r[GLOBAL_NS.'_update_pro_zip'])) {
+ return $transient; // Nothing to do here.
+ }
+ $update_pro_version = (string) $_r[GLOBAL_NS.'_update_pro_version'];
+ $update_pro_zip = base64_decode((string) $_r[GLOBAL_NS.'_update_pro_zip'], true);
+ // @TODO Encrypt/decrypt to avoid mod_security issues. Base64 is not enough.
- if (!is_object($transient)) {
- $transient = new \stdClass();
+ if (!is_object($transient)) {
+ $transient = new \stdClass();
+ }
+ $transient->last_checked = time();
+ $transient->checked[plugin_basename(PLUGIN_FILE)] = VERSION;
+ $transient->response[plugin_basename(PLUGIN_FILE)] = (object) [
+ 'id' => 0,
+ 'slug' => basename(PLUGIN_FILE, '.php'),
+ 'url' => add_query_arg(urlencode_deep(['page' => GLOBAL_NS.'-pro-updater']), self_admin_url('/admin.php')),
+ 'new_version' => $update_pro_version, 'package' => $update_pro_zip,
+ ];
+ return $transient; // Nodified now.
}
- $transient->last_checked = time();
- $transient->checked[plugin_basename(PLUGIN_FILE)] = VERSION;
- $transient->response[plugin_basename(PLUGIN_FILE)] = (object) array(
- 'id' => 0,
- 'slug' => basename(PLUGIN_FILE, '.php'),
- 'url' => add_query_arg(urlencode_deep(array('page' => GLOBAL_NS.'-pro-updater')), self_admin_url('/admin.php')),
- 'new_version' => $update_pro_version, 'package' => $update_pro_zip,
- );
- return $transient; // Nodified now.
-};
-/*
- * Appends hidden inputs for pro updater when FTP credentials are requested by WP.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `fs_ftp_connection_types` filter.
- *
- * @param array $types Types of connections.
- *
- * @return array $types Types of connections.
- */
-$self->fsFtpConnectionTypes = function ($types) use ($self) {
- if (!current_user_can($self->update_cap)) {
- return $types; // Nothing to do.
- }
- if (is_multisite() && !current_user_can($self->network_cap)) {
- return $types; // Nothing to do.
- }
- if (!is_admin() || $GLOBALS['pagenow'] !== 'update.php') {
- return $types; // Nothing to do.
- }
- $_r = $self->trimDeep(stripslashes_deep($_REQUEST));
+ /*
+ * Appends hidden inputs for pro updater when FTP credentials are requested by WP.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `fs_ftp_connection_types` filter.
+ *
+ * @param array $types Types of connections.
+ *
+ * @return array $types Types of connections.
+ */
+ public function fsFtpConnectionTypes($types)
+ {
+ if (!current_user_can($this->update_cap)) {
+ return $types; // Nothing to do.
+ }
+ if (is_multisite() && !current_user_can($this->network_cap)) {
+ return $types; // Nothing to do.
+ }
+ if (!is_admin() || $GLOBALS['pagenow'] !== 'update.php') {
+ return $types; // Nothing to do.
+ }
+ $_r = $this->trimDeep(stripslashes_deep($_REQUEST));
- if (empty($_r['action']) || $_r['action'] !== 'upgrade-plugin') {
- return $types; // Nothing to do.
- }
- if (empty($_r[GLOBAL_NS.'_update_pro_version']) || empty($_r[GLOBAL_NS.'_update_pro_zip'])) {
- return $types; // Nothing to do.
- }
- $update_pro_version = (string) $_r[GLOBAL_NS.'_update_pro_version'];
- $update_pro_zip = (string) $_r[GLOBAL_NS.'_update_pro_zip']; // Encrypted!
+ if (empty($_r['action']) || $_r['action'] !== 'upgrade-plugin') {
+ return $types; // Nothing to do.
+ }
+ if (empty($_r[GLOBAL_NS.'_update_pro_version']) || empty($_r[GLOBAL_NS.'_update_pro_zip'])) {
+ return $types; // Nothing to do.
+ }
+ $update_pro_version = (string) $_r[GLOBAL_NS.'_update_pro_version'];
+ $update_pro_zip = (string) $_r[GLOBAL_NS.'_update_pro_zip']; // Encrypted!
- echo '';
+ echo '';
- return $types; // Filter through.
-};
-/*[/pro]*/
+ return $types; // Filter through.
+ }
+ /*[/pro]*/
+}
diff --git a/src/includes/traits/Plugin/UrlUtils.php b/src/includes/traits/Plugin/UrlUtils.php
index f626f2dc..d6d6d328 100644
--- a/src/includes/traits/Plugin/UrlUtils.php
+++ b/src/includes/traits/Plugin/UrlUtils.php
@@ -1,22 +1,25 @@
url = function ($file = '', $scheme = '') use ($self) {
- $url = rtrim(plugin_dir_url(PLUGIN_FILE), '/');
- $url .= (string) $file;
+trait UrlUtils {
+ /*
+ * URL to a Comet Cache plugin file.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $file Optional file path; relative to plugin directory.
+ * @param string $scheme Optional URL scheme; defaults to the current scheme.
+ *
+ * @return string URL to plugin directory; or to the specified `$file` if applicable.
+ */
+ public function url($file = '', $scheme = '')
+ {
+ $url = rtrim(plugin_dir_url(PLUGIN_FILE), '/');
+ $url .= (string) $file;
- if ($scheme) {
- $url = set_url_scheme($url, (string) $scheme);
+ if ($scheme) {
+ $url = set_url_scheme($url, (string) $scheme);
+ }
+ return $url;
}
- return $url;
-};
+}
diff --git a/src/includes/traits/Plugin/UserUtils.php b/src/includes/traits/Plugin/UserUtils.php
index c30045f5..92ac2982 100644
--- a/src/includes/traits/Plugin/UserUtils.php
+++ b/src/includes/traits/Plugin/UserUtils.php
@@ -1,136 +1,143 @@
currentUserCanClearCache = function () use ($self) {
- if (!is_null($can = &$self->cacheKey('currentUserCanClearCache'))) {
- return $can; // Already cached this.
- }
- $is_multisite = is_multisite();
+trait UserUtils {
+ /*
+ * Current user can clear the cache?
+ *
+ * @since 151002 Enhancing user permissions.
+ *
+ * @return boolean Current user can clear the cache?
+ */
+ public function currentUserCanClearCache()
+ {
+ if (!is_null($can = &$this->cacheKey('currentUserCanClearCache'))) {
+ return $can; // Already cached this.
+ }
+ $is_multisite = is_multisite();
- if (!$is_multisite && current_user_can($self->cap)) {
- return ($can = true); // Plugin admin.
- }
- if ($is_multisite && current_user_can($self->network_cap)) {
- return ($can = true); // Plugin admin.
- }
- /*[pro strip-from="lite"]*/
- if (current_user_can($self->clear_min_cap)) { // Might be a privileged user?
- foreach (preg_split('/,+/', $self->options['cache_clear_admin_bar_roles_caps'], -1, PREG_SPLIT_NO_EMPTY) as $_role_cap) {
- if ($_role_cap && current_user_can($_role_cap)) {
- return ($can = true); // Privileged user.
+ if (!$is_multisite && current_user_can($this->cap)) {
+ return ($can = true); // Plugin admin.
+ }
+ if ($is_multisite && current_user_can($this->network_cap)) {
+ return ($can = true); // Plugin admin.
+ }
+ /*[pro strip-from="lite"]*/
+ if (current_user_can($this->clear_min_cap)) { // Might be a privileged user?
+ foreach (preg_split('/,+/', $this->options['cache_clear_admin_bar_roles_caps'], -1, PREG_SPLIT_NO_EMPTY) as $_role_cap) {
+ if ($_role_cap && current_user_can($_role_cap)) {
+ return ($can = true); // Privileged user.
+ }
}
+ unset($_role_cap); // Housekeeping.
}
- unset($_role_cap); // Housekeeping.
+ /*[/pro]*/
+ return ($can = false);
}
- /*[/pro]*/
- return ($can = false);
-};
-$self->currentUserCanWipeCache = $self->currentUserCanClearCache;
+$this->currentUserCanWipeCache = $this->currentUserCanClearCache;
-/*
- * Current user can clear the opcache?
- *
- * @since 151114 Enhancing user permissions.
- *
- * @return boolean Current user can clear the opcache?
- */
-$self->currentUserCanClearOpCache = function () use ($self) {
- if (!is_null($can = &$self->cacheKey('currentUserCanClearOpCache'))) {
- return $can; // Already cached this.
- }
- $is_multisite = is_multisite();
+ /*
+ * Current user can clear the opcache?
+ *
+ * @since 151114 Enhancing user permissions.
+ *
+ * @return boolean Current user can clear the opcache?
+ */
+ public function currentUserCanClearOpCache()
+ {
+ if (!is_null($can = &$this->cacheKey('currentUserCanClearOpCache'))) {
+ return $can; // Already cached this.
+ }
+ $is_multisite = is_multisite();
- if (!$is_multisite && current_user_can($self->cap)) {
- return ($can = true); // Plugin admin.
- }
- if ($is_multisite && current_user_can($self->network_cap)) {
- return ($can = true); // Plugin admin.
+ if (!$is_multisite && current_user_can($this->cap)) {
+ return ($can = true); // Plugin admin.
+ }
+ if ($is_multisite && current_user_can($this->network_cap)) {
+ return ($can = true); // Plugin admin.
+ }
+ return ($can = false);
}
- return ($can = false);
-};
-$self->currentUserCanWipeOpCache = $self->currentUserCanClearOpCache;
+$this->currentUserCanWipeOpCache = $this->currentUserCanClearOpCache;
-/*
- * Current user can clear the CDN cache?
- *
- * @since 151114 Enhancing user permissions.
- *
- * @return boolean Current user can clear the CDN cache?
- */
-$self->currentUserCanClearCdnCache = function () use ($self) {
- if (!is_null($can = &$self->cacheKey('currentUserCanClearCdnCache'))) {
- return $can; // Already cached this.
- }
- $is_multisite = is_multisite();
+ /*
+ * Current user can clear the CDN cache?
+ *
+ * @since 151114 Enhancing user permissions.
+ *
+ * @return boolean Current user can clear the CDN cache?
+ */
+ public function currentUserCanClearCdnCache()
+ {
+ if (!is_null($can = &$this->cacheKey('currentUserCanClearCdnCache'))) {
+ return $can; // Already cached this.
+ }
+ $is_multisite = is_multisite();
- if (!$is_multisite && current_user_can($self->cap)) {
- return ($can = true); // Plugin admin.
- }
- if ($is_multisite && current_user_can($self->network_cap)) {
- return ($can = true); // Plugin admin.
+ if (!$is_multisite && current_user_can($this->cap)) {
+ return ($can = true); // Plugin admin.
+ }
+ if ($is_multisite && current_user_can($this->network_cap)) {
+ return ($can = true); // Plugin admin.
+ }
+ return ($can = false);
}
- return ($can = false);
-};
-$self->currentUserCanWipeCdnCache = $self->currentUserCanClearCdnCache;
+$this->currentUserCanWipeCdnCache = $this->currentUserCanClearCdnCache;
-/*
-* Current user can clear expired transients?
-*
-* @since 151220 Enhancing user permissions.
-*
-* @return boolean Current user can clear expired transients?
-*/
-$self->currentUserCanClearExpiredTransients = function () use ($self) {
- if (!is_null($can = &$self->cacheKey('currentUserCanClearExpiredTransients'))) {
- return $can; // Already cached this.
- }
- $is_multisite = is_multisite();
+ /*
+ * Current user can clear expired transients?
+ *
+ * @since 151220 Enhancing user permissions.
+ *
+ * @return boolean Current user can clear expired transients?
+ */
+ public function currentUserCanClearExpiredTransients()
+ {
+ if (!is_null($can = &$this->cacheKey('currentUserCanClearExpiredTransients'))) {
+ return $can; // Already cached this.
+ }
+ $is_multisite = is_multisite();
- if (!$is_multisite && current_user_can($self->cap)) {
- return ($can = true); // Plugin admin.
- }
- if ($is_multisite && current_user_can($self->network_cap)) {
- return ($can = true); // Plugin admin.
+ if (!$is_multisite && current_user_can($this->cap)) {
+ return ($can = true); // Plugin admin.
+ }
+ if ($is_multisite && current_user_can($this->network_cap)) {
+ return ($can = true); // Plugin admin.
+ }
+ return ($can = false);
}
- return ($can = false);
-};
-$self->currentUserCanWipeExpiredTransients = $self->currentUserCanClearExpiredTransients;
+$this->currentUserCanWipeExpiredTransients = $this->currentUserCanClearExpiredTransients;
-/*
- * Current user can see stats?
- *
- * @since 151002 Enhancing user permissions.
- *
- * @return boolean Current user can see stats?
- */
-$self->currentUserCanSeeStats = function () use ($self) {
- if (!is_null($can = &$self->cacheKey('currentUserCanSeeStats'))) {
- return $can; // Already cached this.
- }
- $is_multisite = is_multisite();
+ /*
+ * Current user can see stats?
+ *
+ * @since 151002 Enhancing user permissions.
+ *
+ * @return boolean Current user can see stats?
+ */
+ public function currentUserCanSeeStats()
+ {
+ if (!is_null($can = &$this->cacheKey('currentUserCanSeeStats'))) {
+ return $can; // Already cached this.
+ }
+ $is_multisite = is_multisite();
- if (!$is_multisite && current_user_can($self->cap)) {
- return ($can = true); // Plugin admin.
- }
- if ($is_multisite && current_user_can($self->network_cap)) {
- return ($can = true); // Plugin admin.
- }
- /*[pro strip-from="lite"]*/
- if (current_user_can($self->stats_min_cap)) { // Might be a privileged user?
- foreach (preg_split('/,+/', $self->options['stats_admin_bar_roles_caps'], -1, PREG_SPLIT_NO_EMPTY) as $_role_cap) {
- if ($_role_cap && current_user_can($_role_cap)) {
- return ($can = true); // Privileged user.
+ if (!$is_multisite && current_user_can($this->cap)) {
+ return ($can = true); // Plugin admin.
+ }
+ if ($is_multisite && current_user_can($this->network_cap)) {
+ return ($can = true); // Plugin admin.
+ }
+ /*[pro strip-from="lite"]*/
+ if (current_user_can($this->stats_min_cap)) { // Might be a privileged user?
+ foreach (preg_split('/,+/', $this->options['stats_admin_bar_roles_caps'], -1, PREG_SPLIT_NO_EMPTY) as $_role_cap) {
+ if ($_role_cap && current_user_can($_role_cap)) {
+ return ($can = true); // Privileged user.
+ }
}
+ unset($_role_cap); // Housekeeping.
}
- unset($_role_cap); // Housekeeping.
+ /*[/pro]*/
+ return ($can = false);
}
- /*[/pro]*/
- return ($can = false);
-};
+}
diff --git a/src/includes/traits/Plugin/WcpAuthorUtils.php b/src/includes/traits/Plugin/WcpAuthorUtils.php
index 779b6076..f4fc31c3 100644
--- a/src/includes/traits/Plugin/WcpAuthorUtils.php
+++ b/src/includes/traits/Plugin/WcpAuthorUtils.php
@@ -1,92 +1,97 @@
autoClearAuthorPageCache = function ($post_id, \WP_Post $post_after, \WP_Post $post_before) use ($self) {
- $counter = 0; // Initialize.
- $enqueued_notices = 0; // Initialize.
- $authors = array(); // Initialize.
- $authors_to_clear = array(); // Initialize.
-
- if (!($post_id = (integer) $post_id)) {
- return $counter; // Nothing to do.
- }
- if (!is_null($done = &$self->cacheKey('autoClearAuthorPageCache', array($post_id, $post_after->ID, $post_before->ID)))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
-
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if (!$self->options['cache_clear_author_page_enable']) {
- return $counter; // Nothing to do.
- }
- if (!is_dir($cache_dir = $self->cacheDir())) {
- return $counter; // Nothing to do.
- }
+trait WcpAuthorUtils {
/*
- * If we're changing the post author AND
- * the previous post status was either 'published' or 'private'
- * then clear the author page for both authors.
+ * Automatically clears cache files for the author page(s).
*
- * Else if the old post status was 'published' or 'private' OR
- * the new post status is 'published' or 'private'
- * then clear the author page for the current author.
+ * @attaches-to `post_updated` hook.
*
- * Else return the counter; post status does not warrant clearing author page cache.
+ * @since 150422 Rewrite.
+ *
+ * @param int $post_id A WordPress post ID.
+ * @param \WP_Post $post_after WP_Post object following the update.
+ * @param \WP_Post $post_before WP_Post object before the update.
+ *
+ * @throws \Exception If a clear failure occurs.
+ *
+ * @return int Total files cleared by this routine (if any).
+ *
+ * @note If the author for the post is being changed, both the previous author
+ * and current author pages are cleared, if the post status is applicable.
*/
- if ($post_after->post_author !== $post_before->post_author &&
- ($post_before->post_status === 'publish' || $post_before->post_status === 'private')
- ) {
- $authors[] = (integer) $post_before->post_author;
- $authors[] = (integer) $post_after->post_author;
- } elseif (($post_before->post_status === 'publish' || $post_before->post_status === 'private') ||
- ($post_after->post_status === 'publish' || $post_after->post_status === 'private')
- ) {
- $authors[] = (integer) $post_after->post_author;
- }
- if (!$authors) {
- return $counter; // Nothing to do.
- }
- foreach ($authors as $_author_id) {
- $authors_to_clear[$_author_id]['posts_url'] = get_author_posts_url($_author_id);
- $authors_to_clear[$_author_id]['display_name'] = get_the_author_meta('display_name', $_author_id);
- }
- unset($_author_id); // Housekeeping.
+ public function autoClearAuthorPageCache($post_id, \WP_Post $post_after, \WP_Post $post_before)
+ {
+ $counter = 0; // Initialize.
+ $enqueued_notices = 0; // Initialize.
+ $authors = []; // Initialize.
+ $authors_to_clear = []; // Initialize.
- foreach ($authors_to_clear as $_author) {
- $_author_regex = $self->buildHostCachePathRegex($_author['posts_url']);
- $_author_counter = $self->clearFilesFromHostCacheDir($_author_regex);
- $counter += $_author_counter; // Add to overall counter.
+ if (!($post_id = (integer) $post_id)) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_null($done = &$this->cacheKey('autoClearAuthorPageCache', [$post_id, $post_after->ID, $post_before->ID]))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- if ($_author_counter && $enqueued_notices < 100 && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected changes. Found %2$s in the cache for Author Page: %3$s
; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($_author_counter)), esc_html($_author['display_name'])));
- $enqueued_notices++; // Increment enqueued notices counter.
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
}
- }
- unset($_author, $_author_regex, $_author_counter); // Housekeeping.
+ if (!$this->options['cache_clear_author_page_enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_dir($cache_dir = $this->cacheDir())) {
+ return $counter; // Nothing to do.
+ }
+ /*
+ * If we're changing the post author AND
+ * the previous post status was either 'published' or 'private'
+ * then clear the author page for both authors.
+ *
+ * Else if the old post status was 'published' or 'private' OR
+ * the new post status is 'published' or 'private'
+ * then clear the author page for the current author.
+ *
+ * Else return the counter; post status does not warrant clearing author page cache.
+ */
+ if ($post_after->post_author !== $post_before->post_author &&
+ ($post_before->post_status === 'publish' || $post_before->post_status === 'private')
+ ) {
+ $authors[] = (integer) $post_before->post_author;
+ $authors[] = (integer) $post_after->post_author;
+ } elseif (($post_before->post_status === 'publish' || $post_before->post_status === 'private') ||
+ ($post_after->post_status === 'publish' || $post_after->post_status === 'private')
+ ) {
+ $authors[] = (integer) $post_after->post_author;
+ }
+ if (!$authors) {
+ return $counter; // Nothing to do.
+ }
+ foreach ($authors as $_author_id) {
+ $authors_to_clear[$_author_id]['posts_url'] = get_author_posts_url($_author_id);
+ $authors_to_clear[$_author_id]['display_name'] = get_the_author_meta('display_name', $_author_id);
+ }
+ unset($_author_id); // Housekeeping.
+
+ foreach ($authors_to_clear as $_author) {
+ $_author_regex = $this->buildHostCachePathRegex($_author['posts_url']);
+ $_author_counter = $this->clearFilesFromHostCacheDir($_author_regex);
+ $counter += $_author_counter; // Add to overall counter.
- $counter += $self->autoClearXmlFeedsCache('blog');
- $counter += $self->autoClearXmlFeedsCache('post-authors', $post_id);
+ if ($_author_counter && $enqueued_notices < 100 && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected changes. Found %2$s in the cache for Author Page: %3$s
; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($_author_counter)), esc_html($_author['display_name']))
+ );
+ $enqueued_notices++; // Increment enqueued notices counter.
+ }
+ }
+ unset($_author, $_author_regex, $_author_counter); // Housekeeping.
+
+ $counter += $this->autoClearXmlFeedsCache('blog');
+ $counter += $this->autoClearXmlFeedsCache('post-authors', $post_id);
- return $counter;
-};
+ return $counter;
+ }
+}
diff --git a/src/includes/traits/Plugin/WcpCdnUtils.php b/src/includes/traits/Plugin/WcpCdnUtils.php
index fb35c80c..27e7163b 100644
--- a/src/includes/traits/Plugin/WcpCdnUtils.php
+++ b/src/includes/traits/Plugin/WcpCdnUtils.php
@@ -2,45 +2,49 @@
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Traits\Plugin;
-/*
- * Wipes out entire CDN cache.
- *
- * @since 151002 Implementing CDN cache wiping.
- *
- * @param bool $manually True if wiping is done manually.
- * @param boolean $maybe Defaults to a true value.
- *
- * @throws \Exception If a wipe failure occurs.
- *
- * @return integer CDN invalidation counter after wiping.
- * Zero, or a negative integer if wiping did not take place.
- */
-$self->wipeCdnCache = function ($manually = false, $maybe = true) use ($self) {
- if (!$self->options['cdn_enable']) {
- return -(integer) $self->options['cdn_invalidation_counter'];
- }
- if ($maybe && !$self->options['cache_clear_cdn_enable']) {
- return -(integer) $self->options['cdn_invalidation_counter'];
- }
- $self->updateOptions(array('cdn_invalidation_counter' => ++$self->options['cdn_invalidation_counter']));
+trait WcpCdnUtils {
+ /*
+ * Wipes out entire CDN cache.
+ *
+ * @since 151002 Implementing CDN cache wiping.
+ *
+ * @param bool $manually True if wiping is done manually.
+ * @param boolean $maybe Defaults to a true value.
+ *
+ * @throws \Exception If a wipe failure occurs.
+ *
+ * @return integer CDN invalidation counter after wiping.
+ * Zero, or a negative integer if wiping did not take place.
+ */
+ public function wipeCdnCache($manually = false, $maybe = true)
+ {
+ if (!$this->options['cdn_enable']) {
+ return -(integer) $this->options['cdn_invalidation_counter'];
+ }
+ if ($maybe && !$this->options['cache_clear_cdn_enable']) {
+ return -(integer) $this->options['cdn_invalidation_counter'];
+ }
+ $this->updateOptions(['cdn_invalidation_counter' => ++$this->options['cdn_invalidation_counter']]);
- return (integer) $self->options['cdn_invalidation_counter'];
-};
+ return (integer) $this->options['cdn_invalidation_counter'];
+ }
-/*
- * Clears the CDN cache.
- *
- * @since 151002 Implementing CDN cache clearing.
- *
- * @param bool $manually True if clearing is done manually.
- * @param boolean $maybe Defaults to a true value.
- *
- * @throws \Exception If a clear failure occurs.
- *
- * @return integer CDN invalidation counter after clearing.
- * Zero, or a negative integer if clearing did not take place.
- */
-$self->clearCdnCache = function ($manually = false, $maybe = true) use ($self) {
- return $self->wipeCdnCache($manually, $maybe);
-};
+ /*
+ * Clears the CDN cache.
+ *
+ * @since 151002 Implementing CDN cache clearing.
+ *
+ * @param bool $manually True if clearing is done manually.
+ * @param boolean $maybe Defaults to a true value.
+ *
+ * @throws \Exception If a clear failure occurs.
+ *
+ * @return integer CDN invalidation counter after clearing.
+ * Zero, or a negative integer if clearing did not take place.
+ */
+ public function clearCdnCache($manually = false, $maybe = true)
+ {
+ return $this->wipeCdnCache($manually, $maybe);
+ }
+}
/*[/pro]*/
diff --git a/src/includes/traits/Plugin/WcpCommentUtils.php b/src/includes/traits/Plugin/WcpCommentUtils.php
index 80b7210f..1d83feb6 100644
--- a/src/includes/traits/Plugin/WcpCommentUtils.php
+++ b/src/includes/traits/Plugin/WcpCommentUtils.php
@@ -1,96 +1,100 @@
autoClearCommentPostCache = function ($comment_id) use ($self) {
- $counter = 0; // Initialize.
+trait WcpCommentUtils {
+ /*
+ * Automatically clears cache files for a post associated with a particular comment.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `trackback_post` hook.
+ * @attaches-to `pingback_post` hook.
+ * @attaches-to `comment_post` hook.
+ *
+ * @param int $comment_id A WordPress comment ID.
+ *
+ * @return int Total files cleared by this routine (if any).
+ */
+ public function autoClearCommentPostCache($comment_id)
+ {
+ $counter = 0; // Initialize.
- if (!($comment_id = (integer) $comment_id)) {
- return $counter; // Nothing to do.
- }
- if (!is_null($done = &$self->cacheKey('autoClearCommentPostCache', $comment_id))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
+ if (!($comment_id = (integer) $comment_id)) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_null($done = &$this->cacheKey('autoClearCommentPostCache', $comment_id))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
+
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_object($comment = get_comment($comment_id))) {
+ return $counter; // Nothing we can do.
+ }
+ if (empty($comment->comment_post_ID)) {
+ return $counter; // Nothing we can do.
+ }
+ if ($comment->comment_approved === 'spam' || $comment->comment_approved === '0') {
+ // Don't allow next `autoClearPostCache()` call to clear post cache.
+ $allow = &$this->cacheKey('autoClearPostCache_allow');
+ $allow = false; // Flag as false; i.e., disallow.
+ return $counter;
+ }
+ $counter += $this->autoClearXmlFeedsCache('blog-comments');
+ $counter += $this->autoClearXmlFeedsCache('post-comments', $comment->comment_post_ID);
+ $counter += $this->autoClearPostCache($comment->comment_post_ID);
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if (!is_object($comment = get_comment($comment_id))) {
- return $counter; // Nothing we can do.
- }
- if (empty($comment->comment_post_ID)) {
- return $counter; // Nothing we can do.
- }
- if ($comment->comment_approved === 'spam' || $comment->comment_approved === '0') {
- // Don't allow next `autoClearPostCache()` call to clear post cache.
- $allow = &$self->cacheKey('autoClearPostCache_allow');
- $allow = false; // Flag as false; i.e., disallow.
return $counter;
}
- $counter += $self->autoClearXmlFeedsCache('blog-comments');
- $counter += $self->autoClearXmlFeedsCache('post-comments', $comment->comment_post_ID);
- $counter += $self->autoClearPostCache($comment->comment_post_ID);
- return $counter;
-};
+ /*
+ * Automatically clears cache files for a post associated with a particular comment.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `transition_comment_status` hook.
+ *
+ * @param string $new_status New comment status.
+ * @param string $old_status Old comment status.
+ * @param \stdClass $comment Comment object.
+ *
+ * @throws \Exception If a clear failure occurs.
+ *
+ * @return int Total files cleared by this routine (if any).
+ *
+ * @note This is also called upon by other routines which listen for
+ * events that are indirectly associated with a comment ID.
+ */
+ public function autoClearCommentPostCacheTransition($new_status, $old_status, $comment)
+ {
+ $counter = 0; // Initialize.
-/*
- * Automatically clears cache files for a post associated with a particular comment.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `transition_comment_status` hook.
- *
- * @param string $new_status New comment status.
- * @param string $old_status Old comment status.
- * @param \stdClass $comment Comment object.
- *
- * @throws \Exception If a clear failure occurs.
- *
- * @return int Total files cleared by this routine (if any).
- *
- * @note This is also called upon by other routines which listen for
- * events that are indirectly associated with a comment ID.
- */
-$self->autoClearCommentPostCacheTransition = function ($new_status, $old_status, $comment) use ($self) {
- $counter = 0; // Initialize.
+ if (!is_object($comment)) {
+ return $counter; // Nothing we can do.
+ }
+ if (empty($comment->comment_post_ID)) {
+ return $counter; // Nothing we can do.
+ }
+ if (!is_null($done = &$this->cacheKey('autoClearCommentPostCacheTransition', [$new_status, $old_status, $comment->comment_post_ID]))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- if (!is_object($comment)) {
- return $counter; // Nothing we can do.
- }
- if (empty($comment->comment_post_ID)) {
- return $counter; // Nothing we can do.
- }
- if (!is_null($done = &$self->cacheKey('autoClearCommentPostCacheTransition', array($new_status, $old_status, $comment->comment_post_ID)))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!($old_status === 'approved' || ($old_status === 'unapproved' && $new_status === 'approved'))) {
+ // If excluded here, don't allow next `autoClearPostCache()` call to clear post cache.
+ $allow = &$this->cacheKey('autoClearPostCache_allow');
+ $allow = false; // Flag as false; i.e., disallow.
+ return $counter;
+ }
+ $counter += $this->autoClearXmlFeedsCache('blog-comments');
+ $counter += $this->autoClearXmlFeedsCache('post-comments', $comment->comment_post_ID);
+ $counter += $this->autoClearPostCache($comment->comment_post_ID);
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if (!($old_status === 'approved' || ($old_status === 'unapproved' && $new_status === 'approved'))) {
- // If excluded here, don't allow next `autoClearPostCache()` call to clear post cache.
- $allow = &$self->cacheKey('autoClearPostCache_allow');
- $allow = false; // Flag as false; i.e., disallow.
return $counter;
}
- $counter += $self->autoClearXmlFeedsCache('blog-comments');
- $counter += $self->autoClearXmlFeedsCache('post-comments', $comment->comment_post_ID);
- $counter += $self->autoClearPostCache($comment->comment_post_ID);
-
- return $counter;
-};
+}
diff --git a/src/includes/traits/Plugin/WcpEvalUtils.php b/src/includes/traits/Plugin/WcpEvalUtils.php
index 897f4dd1..8b926ec8 100644
--- a/src/includes/traits/Plugin/WcpEvalUtils.php
+++ b/src/includes/traits/Plugin/WcpEvalUtils.php
@@ -2,45 +2,50 @@
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Traits\Plugin;
-/*
- * Wipe (i.e., eval) custom code.
- *
- * @since 151002 Enhancing eval support.
- *
- * @param bool $manually True if wiping is done manually.
- * @param boolean $maybe Defaults to a true value.
- *
- * @return string Result from custom code.
- */
-$self->wipeEvalCode = function ($manually = false, $maybe = true) use ($self) {
- $result = ''; // Initialize result.
+trait WcpEvalUtils {
- if ($maybe && !$self->options['cache_clear_eval_code']) {
- return $result; // Not enabled at this time.
- }
- if (!$self->options['cache_clear_eval_code']) {
- return $result; // Nothing to eval.
- }
- if (!$self->functionIsPossible('eval')) {
- return $result; // Not possible.
- }
- ob_start(); // Buffer output from PHP code.
- eval('?>'.$self->options['cache_clear_eval_code'].'options['cache_clear_eval_code']) {
+ return $result; // Not enabled at this time.
+ }
+ if (!$this->options['cache_clear_eval_code']) {
+ return $result; // Nothing to eval.
+ }
+ if (!$this->functionIsPossible('eval')) {
+ return $result; // Not possible.
+ }
+ ob_start(); // Buffer output from PHP code.
+ eval('?>'.$this->options['cache_clear_eval_code'].'clearEvalCode = function ($manually = false, $maybe = true) use ($self) {
- return $self->wipeEvalCode($manually, $maybe);
-};
+ return ($result = ob_get_clean());
+ }
+
+ /*
+ * Clear (i.e., eval) custom code.
+ *
+ * @since 151002 Enhancing eval support.
+ *
+ * @param bool $manually True if wiping is done manually.
+ * @param boolean $maybe Defaults to a true value.
+ *
+ * @return string Result from custom code.
+ */
+ public function clearEvalCode($manually = false, $maybe = true)
+ {
+ return $this->wipeEvalCode($manually, $maybe);
+ }
+}
/*[/pro]*/
diff --git a/src/includes/traits/Plugin/WcpFeedUtils.php b/src/includes/traits/Plugin/WcpFeedUtils.php
index 56991671..021e082b 100644
--- a/src/includes/traits/Plugin/WcpFeedUtils.php
+++ b/src/includes/traits/Plugin/WcpFeedUtils.php
@@ -1,116 +1,121 @@
autoClearXmlFeedsCache = function ($type, $post_id = 0) use ($self) {
- $counter = 0; // Initialize.
+trait WcpFeedUtils {
+ /*
+ * Automatically clears cache files related to XML feeds.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $type Type of feed(s) to auto-clear.
+ * @param int $post_id A Post ID (when applicable).
+ *
+ * @throws \Exception If a clear failure occurs.
+ *
+ * @return int Total files cleared by this routine (if any).
+ *
+ * @note Unlike many of the other `auto_` methods, this one is NOT currently
+ * attached to any hooks. However, it is called upon by other routines attached to hooks.
+ */
+ public function autoClearXmlFeedsCache($type, $post_id = 0)
+ {
+ $counter = 0; // Initialize.
- if (!($type = (string) $type)) {
- return $counter; // Nothing we can do.
- }
- $post_id = (integer) $post_id; // Force integer.
-
- if (!is_null($done = &$self->cacheKey('autoClearXmlFeedsCache', array($type, $post_id)))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
-
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if (!$self->options['feeds_enable']) {
- return $counter; // Nothing to do.
- }
- if (!$self->options['cache_clear_xml_feeds_enable']) {
- return $counter; // Nothing to do.
- }
- if (!is_dir($cache_dir = $self->cacheDir())) {
- return $counter; // Nothing to do.
- }
- $utils = new FeedUtils(); // Feed utilities.
- $variations = $variation_regex_frags = array(); // Initialize.
+ if (!($type = (string) $type)) {
+ return $counter; // Nothing we can do.
+ }
+ $post_id = (integer) $post_id; // Force integer.
- switch ($type) { // Handle clearing based on the `$type`.
+ if (!is_null($done = &$this->cacheKey('autoClearXmlFeedsCache', [$type, $post_id]))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- case 'blog': // The blog feed; i.e. `/feed/` on most WP installs.
- $variations = array_merge($variations, $utils->feedLinkVariations());
- break; // Break switch handler.
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!$this->options['feeds_enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!$this->options['cache_clear_xml_feeds_enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_dir($cache_dir = $this->cacheDir())) {
+ return $counter; // Nothing to do.
+ }
+ $utils = new FeedUtils(); // Feed utilities.
+ $variations = $variation_regex_frags = []; // Initialize.
- case 'blog-comments': // The blog comments feed; i.e. `/comments/feed/` on most WP installs.
- $variations = array_merge($variations, $utils->feedLinkVariations('comments_'));
- break; // Break switch handler.
+ switch ($type) { // Handle clearing based on the `$type`.
- case 'post-comments': // Feeds related to comments that a post has.
- if (!$post_id) {
+ case 'blog': // The blog feed; i.e. `/feed/` on most WP installs.
+ $variations = array_merge($variations, $utils->feedLinkVariations());
break; // Break switch handler.
- }
- if (!($post = get_post($post_id))) {
- break; // Break switch handler.
- }
- $variations = array_merge($variations, $utils->postCommentsFeedLinkVariations($post));
- break; // Break switch handler.
- case 'post-authors': // Feeds related to authors that a post has.
- if (!$post_id) {
- break; // Break switch handler.
- }
- if (!($post = get_post($post_id))) {
+ case 'blog-comments': // The blog comments feed; i.e. `/comments/feed/` on most WP installs.
+ $variations = array_merge($variations, $utils->feedLinkVariations('comments_'));
break; // Break switch handler.
- }
- $variations = array_merge($variations, $utils->postAuthorFeedLinkVariations($post));
- break; // Break switch handler.
- case 'post-terms': // Feeds related to terms that a post has.
- if (!$post_id) {
+ case 'post-comments': // Feeds related to comments that a post has.
+ if (!$post_id) {
+ break; // Break switch handler.
+ }
+ if (!($post = get_post($post_id))) {
+ break; // Break switch handler.
+ }
+ $variations = array_merge($variations, $utils->postCommentsFeedLinkVariations($post));
break; // Break switch handler.
- }
- if (!($post = get_post($post_id))) {
+
+ case 'post-authors': // Feeds related to authors that a post has.
+ if (!$post_id) {
+ break; // Break switch handler.
+ }
+ if (!($post = get_post($post_id))) {
+ break; // Break switch handler.
+ }
+ $variations = array_merge($variations, $utils->postAuthorFeedLinkVariations($post));
break; // Break switch handler.
- }
- $variations = array_merge($variations, $utils->postTermFeedLinkVariations($post, true));
- break; // Break switch handler.
- case 'custom-post-type': // Feeds related to a custom post type archive view.
- if (!$post_id) {
+ case 'post-terms': // Feeds related to terms that a post has.
+ if (!$post_id) {
+ break; // Break switch handler.
+ }
+ if (!($post = get_post($post_id))) {
+ break; // Break switch handler.
+ }
+ $variations = array_merge($variations, $utils->postTermFeedLinkVariations($post, true));
break; // Break switch handler.
- }
- if (!($post = get_post($post_id))) {
+
+ case 'custom-post-type': // Feeds related to a custom post type archive view.
+ if (!$post_id) {
+ break; // Break switch handler.
+ }
+ if (!($post = get_post($post_id))) {
+ break; // Break switch handler.
+ }
+ $variations = array_merge($variations, $utils->postTypeArchiveFeedLinkVariations($post));
break; // Break switch handler.
- }
- $variations = array_merge($variations, $utils->postTypeArchiveFeedLinkVariations($post));
- break; // Break switch handler.
- // @TODO Possibly consider search-related feeds in the future.
- // See:
- }
- if (!($variation_regex_frags = $utils->convertVariationsToHostCachePathRegexFrags($variations))) {
- return $counter; // Nothing to do here.
- }
- $in_sets_of = $self->applyWpFilters(GLOBAL_NS.'_autoClearXmlFeedsCache_in_sets_of', 10, get_defined_vars());
- for ($_i = 0; $_i < count($variation_regex_frags); $_i = $_i + $in_sets_of) {
- $_variation_regex_frags = array_slice($variation_regex_frags, $_i, $in_sets_of);
- $_regex = '/^\/(?:'.implode('|', $_variation_regex_frags).')\./i';
- $counter += $self->clearFilesFromHostCacheDir($_regex);
- }
- unset($_i, $_variation_regex_frags, $_regex); // Housekeeping.
+ // @TODO Possibly consider search-related feeds in the future.
+ // See:
+ }
+ if (!($variation_regex_frags = $utils->convertVariationsToHostCachePathRegexFrags($variations))) {
+ return $counter; // Nothing to do here.
+ }
+ $in_sets_of = $this->applyWpFilters(GLOBAL_NS.'_autoClearXmlFeedsCache_in_sets_of', 10, get_defined_vars());
+ for ($_i = 0; $_i < count($variation_regex_frags); $_i = $_i + $in_sets_of) {
+ $_variation_regex_frags = array_slice($variation_regex_frags, $_i, $in_sets_of);
+ $_regex = '/^\/(?:'.implode('|', $_variation_regex_frags).')\./i';
+ $counter += $this->clearFilesFromHostCacheDir($_regex);
+ }
+ unset($_i, $_variation_regex_frags, $_regex); // Housekeeping.
- if ($counter && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected changes. Found %2$s in the cache, for XML feeds of type: %3$s
; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($counter)), esc_html($type)));
+ if ($counter && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected changes. Found %2$s in the cache, for XML feeds of type: %3$s
; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($counter)), esc_html($type))
+ );
+ }
+ return $counter;
}
- return $counter;
-};
+}
diff --git a/src/includes/traits/Plugin/WcpHomeBlogUtils.php b/src/includes/traits/Plugin/WcpHomeBlogUtils.php
index d2d98a5d..ea74d6ec 100644
--- a/src/includes/traits/Plugin/WcpHomeBlogUtils.php
+++ b/src/includes/traits/Plugin/WcpHomeBlogUtils.php
@@ -1,101 +1,109 @@
autoClearHomePageCache = function () use ($self) {
- $counter = 0; // Initialize.
+trait WcpHomeBlogUtils {
+ /*
+ * Automatically clears cache files for the home page.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @throws \Exception If a clear failure occurs.
+ *
+ * @return int Total files cleared by this routine (if any).
+ *
+ * @note Unlike many of the other `auto_` methods, this one is NOT currently
+ * attached to any hooks. However, it is called upon by {@link autoClearPostCache()}.
+ */
+ public function autoClearHomePageCache()
+ {
+ $counter = 0; // Initialize.
- if (!is_null($done = &$self->cacheKey('autoClearHomePageCache'))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
+ if (!is_null($done = &$this->cacheKey('autoClearHomePageCache'))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if (!$self->options['cache_clear_home_page_enable']) {
- return $counter; // Nothing to do.
- }
- if (!is_dir($cache_dir = $self->cacheDir())) {
- return $counter; // Nothing to do.
- }
- $regex = $self->buildHostCachePathRegex(home_url('/'));
- $counter += $self->clearFilesFromHostCacheDir($regex);
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!$this->options['cache_clear_home_page_enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_dir($cache_dir = $this->cacheDir())) {
+ return $counter; // Nothing to do.
+ }
+ $regex = $this->buildHostCachePathRegex(home_url('/'));
+ $counter += $this->clearFilesFromHostCacheDir($regex);
- if ($counter && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected changes. Found %2$s in the cache for the designated "Home Page"; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($counter))));
+ if ($counter && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected changes. Found %2$s in the cache for the designated "Home Page"; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($counter)))
+ );
+ }
+ $counter += $this->autoClearXmlFeedsCache('blog');
+
+ return $counter;
}
- $counter += $self->autoClearXmlFeedsCache('blog');
- return $counter;
-};
+ /*
+ * Automatically clears cache files for the posts page.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @throws \Exception If a clear failure occurs.
+ *
+ * @return int Total files cleared by this routine (if any).
+ *
+ * @note Unlike many of the other `auto_` methods, this one is NOT currently
+ * attached to any hooks. However, it is called upon by {@link autoClearPostCache()}.
+ */
+ public function autoClearPostsPageCache()
+ {
+ $counter = 0; // Initialize.
-/*
- * Automatically clears cache files for the posts page.
- *
- * @since 150422 Rewrite.
- *
- * @throws \Exception If a clear failure occurs.
- *
- * @return int Total files cleared by this routine (if any).
- *
- * @note Unlike many of the other `auto_` methods, this one is NOT currently
- * attached to any hooks. However, it is called upon by {@link autoClearPostCache()}.
- */
-$self->autoClearPostsPageCache = function () use ($self) {
- $counter = 0; // Initialize.
+ if (!is_null($done = &$this->cacheKey('autoClearPostsPageCache'))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- if (!is_null($done = &$self->cacheKey('autoClearPostsPageCache'))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!$this->options['cache_clear_posts_page_enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_dir($cache_dir = $this->cacheDir())) {
+ return $counter; // Nothing to do.
+ }
+ $show_on_front = get_option('show_on_front');
+ $page_for_posts = get_option('page_for_posts');
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if (!$self->options['cache_clear_posts_page_enable']) {
- return $counter; // Nothing to do.
- }
- if (!is_dir($cache_dir = $self->cacheDir())) {
- return $counter; // Nothing to do.
- }
- $show_on_front = get_option('show_on_front');
- $page_for_posts = get_option('page_for_posts');
+ if (!in_array($show_on_front, ['posts', 'page'], true)) {
+ return $counter; // Nothing we can do in this case.
+ }
+ if ($show_on_front === 'page' && !$page_for_posts) {
+ return $counter; // Nothing we can do.
+ }
+ if ($show_on_front === 'posts') {
+ $posts_page = home_url('/');
+ } elseif ($show_on_front === 'page') {
+ $posts_page = get_permalink($page_for_posts);
+ }
+ if (empty($posts_page)) {
+ return $counter; // Nothing we can do.
+ }
+ $regex = $this->buildHostCachePathRegex($posts_page);
+ $counter += $this->clearFilesFromHostCacheDir($regex);
- if (!in_array($show_on_front, array('posts', 'page'), true)) {
- return $counter; // Nothing we can do in this case.
- }
- if ($show_on_front === 'page' && !$page_for_posts) {
- return $counter; // Nothing we can do.
- }
- if ($show_on_front === 'posts') {
- $posts_page = home_url('/');
- } elseif ($show_on_front === 'page') {
- $posts_page = get_permalink($page_for_posts);
- }
- if (empty($posts_page)) {
- return $counter; // Nothing we can do.
- }
- $regex = $self->buildHostCachePathRegex($posts_page);
- $counter += $self->clearFilesFromHostCacheDir($regex);
+ if ($counter && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected changes. Found %2$s in the cache for the designated "Posts Page"; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($counter)))
+ );
+ }
+ $counter += $this->autoClearXmlFeedsCache('blog');
- if ($counter && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected changes. Found %2$s in the cache for the designated "Posts Page"; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($counter))));
+ return $counter;
}
- $counter += $self->autoClearXmlFeedsCache('blog');
-
- return $counter;
-};
+}
diff --git a/src/includes/traits/Plugin/WcpHtmlCUtils.php b/src/includes/traits/Plugin/WcpHtmlCUtils.php
index 4c618970..f00fe690 100644
--- a/src/includes/traits/Plugin/WcpHtmlCUtils.php
+++ b/src/includes/traits/Plugin/WcpHtmlCUtils.php
@@ -2,90 +2,94 @@
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Traits\Plugin;
-/*
- * Wipes out all HTML Compressor cache files.
- *
- * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
- *
- * @param bool $manually TRUE if the wiping is done manually by the site owner.
- *
- * @throws \Exception If a wipe failure occurs.
- *
- * @return int Total files wiped by this routine (if any).
- */
-$self->wipeHtmlCCache = function ($manually = false) use ($self) {
- $counter = 0; // Initialize.
+trait WcpHtmlCUtils {
+ /*
+ * Wipes out all HTML Compressor cache files.
+ *
+ * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
+ *
+ * @param bool $manually TRUE if the wiping is done manually by the site owner.
+ *
+ * @throws \Exception If a wipe failure occurs.
+ *
+ * @return int Total files wiped by this routine (if any).
+ */
+ public function wipeHtmlCCache($manually = false)
+ {
+ $counter = 0; // Initialize.
- if (!$manually && $self->disableAutoWipeCacheRoutines()) {
- return $counter; // Nothing to do.
- }
- @set_time_limit(1800); // @TODO Display a warning.
+ if (!$manually && $this->disableAutoWipeCacheRoutines()) {
+ return $counter; // Nothing to do.
+ }
+ @set_time_limit(1800); // @TODO Display a warning.
- $htmlc_cache_dirs = array(); // Initialize directories.
- $htmlc_cache_dirs[] = $self->wpContentBaseDirTo($self->htmlc_cache_sub_dir_public);
- $htmlc_cache_dirs[] = $self->wpContentBaseDirTo($self->htmlc_cache_sub_dir_private);
+ $htmlc_cache_dirs = []; // Initialize directories.
+ $htmlc_cache_dirs[] = $this->wpContentBaseDirTo($this->htmlc_cache_sub_dir_public);
+ $htmlc_cache_dirs[] = $this->wpContentBaseDirTo($this->htmlc_cache_sub_dir_private);
- foreach (array_unique($htmlc_cache_dirs) as $_htmlc_cache_dir) {
- $counter += $self->deleteAllFilesDirsIn($_htmlc_cache_dir);
- }
- unset($_htmlc_cache_dir); // Just a little housekeeping.
+ foreach (array_unique($htmlc_cache_dirs) as $_htmlc_cache_dir) {
+ $counter += $this->deleteAllFilesDirsIn($_htmlc_cache_dir);
+ }
+ unset($_htmlc_cache_dir); // Just a little housekeeping.
- return $counter;
-};
+ return $counter;
+ }
-/*
- * Clear all HTML Compressor cache files for the current blog.
- *
- * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
- *
- * @param bool $manually TRUE if the clearing is done manually by the site owner.
- *
- * @throws \Exception If a clearing failure occurs.
- *
- * @return int Total files cleared by this routine (if any).
- */
-$self->clearHtmlCCache = function ($manually = false) use ($self) {
- $counter = 0; // Initialize.
+ /*
+ * Clear all HTML Compressor cache files for the current blog.
+ *
+ * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
+ *
+ * @param bool $manually TRUE if the clearing is done manually by the site owner.
+ *
+ * @throws \Exception If a clearing failure occurs.
+ *
+ * @return int Total files cleared by this routine (if any).
+ */
+ public function clearHtmlCCache($manually = false)
+ {
+ $counter = 0; // Initialize.
- if (!$manually && $self->disableAutoClearCacheRoutines()) {
- return $counter; // Nothing to do.
- }
- @set_time_limit(1800); // @TODO Display a warning.
+ if (!$manually && $this->disableAutoClearCacheRoutines()) {
+ return $counter; // Nothing to do.
+ }
+ @set_time_limit(1800); // @TODO Display a warning.
- // Deals with multisite base & sub-directory installs.
- // e.g. `htmlc/cache/public/www-example-com` (standard WP installation).
- // e.g. `htmlc/cache/public/[[/base]/child1]/www-example-com` (multisite network).
- // Note that `www-example-com` (current host slug) is appended by the HTML compressor.
+ // Deals with multisite base & sub-directory installs.
+ // e.g. `htmlc/cache/public/www-example-com` (standard WP installation).
+ // e.g. `htmlc/cache/public/[[/base]/child1]/www-example-com` (multisite network).
+ // Note that `www-example-com` (current host slug) is appended by the HTML compressor.
- $host_token = $self->hostToken(true); // Dashify.
- $host_base_dir_tokens = $self->hostBaseDirTokens(true); // Dashify.
+ $host_token = $this->hostToken(true); // Dashify.
+ $host_base_dir_tokens = $this->hostBaseDirTokens(true); // Dashify.
- $htmlc_cache_dirs = array(); // Initialize array of all HTML Compressor directories to clear.
- $htmlc_cache_dirs[] = $self->wpContentBaseDirTo($self->htmlc_cache_sub_dir_public.rtrim($host_base_dir_tokens, '/').'/'.$host_token);
- $htmlc_cache_dirs[] = $self->wpContentBaseDirTo($self->htmlc_cache_sub_dir_private.rtrim($host_base_dir_tokens, '/').'/'.$host_token);
+ $htmlc_cache_dirs = []; // Initialize array of all HTML Compressor directories to clear.
+ $htmlc_cache_dirs[] = $this->wpContentBaseDirTo($this->htmlc_cache_sub_dir_public.rtrim($host_base_dir_tokens, '/').'/'.$host_token);
+ $htmlc_cache_dirs[] = $this->wpContentBaseDirTo($this->htmlc_cache_sub_dir_private.rtrim($host_base_dir_tokens, '/').'/'.$host_token);
- if (is_multisite() && $self->canConsiderDomainMapping()) {
- if (($_host_token_for_blog = $self->hostTokenForBlog(true))) { // Dashify.
- $_host_base_dir_tokens_for_blog = $self->hostBaseDirTokensForBlog(true); // Dashify.
- $htmlc_cache_dirs[] = $self->wpContentBaseDirTo($self->htmlc_cache_sub_dir_public.rtrim($_host_base_dir_tokens_for_blog, '/').'/'.$_host_token_for_blog);
- $htmlc_cache_dirs[] = $self->wpContentBaseDirTo($self->htmlc_cache_sub_dir_private.rtrim($_host_base_dir_tokens_for_blog, '/').'/'.$_host_token_for_blog);
- }
- unset($_host_token_for_blog, $_host_base_dir_tokens_for_blog); // Housekeeping.
+ if (is_multisite() && $this->canConsiderDomainMapping()) {
+ if (($_host_token_for_blog = $this->hostTokenForBlog(true))) { // Dashify.
+ $_host_base_dir_tokens_for_blog = $this->hostBaseDirTokensForBlog(true); // Dashify.
+ $htmlc_cache_dirs[] = $this->wpContentBaseDirTo($this->htmlc_cache_sub_dir_public.rtrim($_host_base_dir_tokens_for_blog, '/').'/'.$_host_token_for_blog);
+ $htmlc_cache_dirs[] = $this->wpContentBaseDirTo($this->htmlc_cache_sub_dir_private.rtrim($_host_base_dir_tokens_for_blog, '/').'/'.$_host_token_for_blog);
+ }
+ unset($_host_token_for_blog, $_host_base_dir_tokens_for_blog); // Housekeeping.
- foreach ($self->domainMappingBlogDomains() as $_domain_mapping_blog_domain) {
- if (($_domain_host_token_for_blog = $self->hostTokenForBlog(true, true, $_domain_mapping_blog_domain))) { // Dashify.
- $_domain_host_base_dir_tokens_for_blog = $self->hostBaseDirTokensForBlog(true, true); // Dashify. This is only a formality.
- $htmlc_cache_dirs[] = $self->wpContentBaseDirTo($self->htmlc_cache_sub_dir_public.rtrim($_domain_host_base_dir_tokens_for_blog, '/').'/'.$_domain_host_token_for_blog);
- $htmlc_cache_dirs[] = $self->wpContentBaseDirTo($self->htmlc_cache_sub_dir_private.rtrim($_domain_host_base_dir_tokens_for_blog, '/').'/'.$_domain_host_token_for_blog);
+ foreach ($this->domainMappingBlogDomains() as $_domain_mapping_blog_domain) {
+ if (($_domain_host_token_for_blog = $this->hostTokenForBlog(true, true, $_domain_mapping_blog_domain))) { // Dashify.
+ $_domain_host_base_dir_tokens_for_blog = $this->hostBaseDirTokensForBlog(true, true); // Dashify. This is only a formality.
+ $htmlc_cache_dirs[] = $this->wpContentBaseDirTo($this->htmlc_cache_sub_dir_public.rtrim($_domain_host_base_dir_tokens_for_blog, '/').'/'.$_domain_host_token_for_blog);
+ $htmlc_cache_dirs[] = $this->wpContentBaseDirTo($this->htmlc_cache_sub_dir_private.rtrim($_domain_host_base_dir_tokens_for_blog, '/').'/'.$_domain_host_token_for_blog);
+ }
}
+ unset($_domain_mapping_blog_domain, $_domain_host_token_for_blog, $_domain_host_base_dir_tokens_for_blog); // Housekeeping.
}
- unset($_domain_mapping_blog_domain, $_domain_host_token_for_blog, $_domain_host_base_dir_tokens_for_blog); // Housekeeping.
- }
- foreach (array_unique($htmlc_cache_dirs) as $_htmlc_cache_dir) {
- $counter += $self->deleteAllFilesDirsIn($_htmlc_cache_dir);
- }
- unset($_htmlc_cache_dir); // Just a little housekeeping.
+ foreach (array_unique($htmlc_cache_dirs) as $_htmlc_cache_dir) {
+ $counter += $this->deleteAllFilesDirsIn($_htmlc_cache_dir);
+ }
+ unset($_htmlc_cache_dir); // Just a little housekeeping.
- return $counter;
-};
+ return $counter;
+ }
+}
/*[/pro]*/
diff --git a/src/includes/traits/Plugin/WcpJetpackUtils.php b/src/includes/traits/Plugin/WcpJetpackUtils.php
index a24a4866..b33e0106 100644
--- a/src/includes/traits/Plugin/WcpJetpackUtils.php
+++ b/src/includes/traits/Plugin/WcpJetpackUtils.php
@@ -1,24 +1,27 @@
autoClearCacheOnJetpackCustomCss = function ($args) use ($self) {
- $counter = 0; // Initialize.
+trait WcpJetpackUtils {
+ /*
+ * Automatically clears all cache files for current blog when JetPack Custom CSS is saved.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `safecss_save_pre` hook.
+ *
+ * @param array $args Args passed in by hook.
+ */
+ public function autoClearCacheOnJetpackCustomCss($args)
+ {
+ $counter = 0; // Initialize.
- if (!is_null($done = &$self->cacheKey('autoClearCacheOnJetpackCustomCss', $args))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
+ if (!is_null($done = &$this->cacheKey('autoClearCacheOnJetpackCustomCss', $args))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- if (empty($args['is_preview']) && class_exists('\\Jetpack')) {
- $counter += $self->autoClearCache();
+ if (empty($args['is_preview']) && class_exists('\\Jetpack')) {
+ $counter += $this->autoClearCache();
+ }
}
-};
+}
diff --git a/src/includes/traits/Plugin/WcpOpcacheUtils.php b/src/includes/traits/Plugin/WcpOpcacheUtils.php
index 25c49e84..0a9ac4b1 100644
--- a/src/includes/traits/Plugin/WcpOpcacheUtils.php
+++ b/src/includes/traits/Plugin/WcpOpcacheUtils.php
@@ -1,69 +1,74 @@
wipeOpcache = function ($manually = false, $maybe = true, $files = array()) use ($self) {
- $counter = 0; // Initialize counter.
+trait WcpOpcacheUtils {
+ /*
+ * Wipe (i.e., reset) OPCache.
+ *
+ * @since 151002 Adding OPCache support.
+ *
+ * @param bool $manually True if wiping is done manually.
+ * @param boolean $maybe Defaults to a true value.
+ * @param array $files Optional; wipe only specific files?
+ *
+ * @return integer Total keys wiped.
+ */
+ public function wipeOpcache($manually = false, $maybe = true, $files = [])
+ {
+ $counter = 0; // Initialize counter.
- if ($maybe && !$self->options['cache_clear_opcache_enable']) {
- return $counter; // Not enabled at this time.
+ if ($maybe && !$this->options['cache_clear_opcache_enable']) {
+ return $counter; // Not enabled at this time.
+ }
+ if (!$this->functionIsPossible('opcache_reset')) {
+ return $counter; // Not possible.
+ }
+ if (!($status = $this->sysOpcacheStatus())) {
+ return $counter; // Not possible.
+ }
+ if (empty($status->opcache_enabled)) {
+ return $counter; // Not necessary.
+ }
+ if (empty($status->opcache_statistics->num_cached_keys)) {
+ return $counter; // Not possible.
+ }
+ if ($files) { // Specific files?
+ foreach ($files as $_file) {
+ $counter += (int) opcache_invalidate($_file, true);
+ } // unset($_file); // Housekeeping.
+ } elseif (opcache_reset()) { // True if a reset occurs.
+ $counter += $status->opcache_statistics->num_cached_keys;
+ }
+ return $counter;
}
- if (!$self->functionIsPossible('opcache_reset')) {
- return $counter; // Not possible.
- }
- if (!($status = $self->sysOpcacheStatus())) {
- return $counter; // Not possible.
- }
- if (empty($status->opcache_enabled)) {
- return $counter; // Not necessary.
- }
- if (empty($status->opcache_statistics->num_cached_keys)) {
- return $counter; // Not possible.
- }
- if ($files) { // Specific files?
- foreach ($files as $_file) {
- $counter += (int) opcache_invalidate($_file, true);
- } // unset($_file); // Housekeeping.
- } elseif (opcache_reset()) { // True if a reset occurs.
- $counter += $status->opcache_statistics->num_cached_keys;
- }
- return $counter;
-};
-/*
- * Clear (i.e., reset) OPCache.
- *
- * @since 151002 Adding OPCache support.
- *
- * @param bool $manually True if clearing is done manually.
- * @param boolean $maybe Defaults to a true value.
- *
- * @return integer Total keys cleared.
- */
-$self->clearOpcache = function ($manually = false, $maybe = true) use ($self) {
- if (!is_multisite() || is_main_site() || current_user_can($self->network_cap)) {
- return $self->wipeOpcache($manually, $maybe);
+ /*
+ * Clear (i.e., reset) OPCache.
+ *
+ * @since 151002 Adding OPCache support.
+ *
+ * @param bool $manually True if clearing is done manually.
+ * @param boolean $maybe Defaults to a true value.
+ *
+ * @return integer Total keys cleared.
+ */
+ public function clearOpcache($manually = false, $maybe = true)
+ {
+ if (!is_multisite() || is_main_site() || current_user_can($this->network_cap)) {
+ return $this->wipeOpcache($manually, $maybe);
+ }
+ return 0; // Not applicable.
}
- return 0; // Not applicable.
-};
-/*
- * Clear AC class file from Opcache (by force).
- *
- * @since 151215 Adding OPCache support.
- *
- * @return integer Total keys cleared.
- */
-$self->clearAcDropinFromOpcacheByForce = function () use ($self) {
- return $self->wipeOpcache(false, false, array(WP_CONTENT_DIR.'/advanced-cache.php'));
-};
+ /*
+ * Clear AC class file from Opcache (by force).
+ *
+ * @since 151215 Adding OPCache support.
+ *
+ * @return integer Total keys cleared.
+ */
+ public function clearAcDropinFromOpcacheByForce()
+ {
+ return $this->wipeOpcache(false, false, [WP_CONTENT_DIR.'/advanced-cache.php']);
+ }
+}
diff --git a/src/includes/traits/Plugin/WcpPluginUtils.php b/src/includes/traits/Plugin/WcpPluginUtils.php
index fac46edb..a2506360 100644
--- a/src/includes/traits/Plugin/WcpPluginUtils.php
+++ b/src/includes/traits/Plugin/WcpPluginUtils.php
@@ -1,22 +1,25 @@
autoClearOnPluginActivationDeactivation = function ($plugin, $network_wide = false) use ($self) {
- if (!$self->applyWpFilters(GLOBAL_NS.'_auto_clear_on_plugin_activation_deactivation', true)) {
- return 0; // Nothing to do here.
- }
- return $self->{($network_wide ? 'autoWipeCache' : 'autoClearCache')}();
-};
+trait WcpPluginUtils {
+ /*
+ * Automatically wipes/clears on plugin activation/deactivation.
+ *
+ * @since 151220 Adding auto-wipe|clear on plugin activations/deactivations.
+ *
+ * @attaches-to `activated_plugin` hook.
+ * @attaches-to `deactivated_plugin` hook.
+ *
+ * @param string $plugin Plugin basename.
+ * @param bool True if activating|deactivating network-wide. Defaults to boolean `FALSE` in case parameter is not passed to hook.
+ *
+ * @return int Total files wiped|cleared by this routine (if any).
+ */
+ public function autoClearOnPluginActivationDeactivation($plugin, $network_wide = false)
+ {
+ if (!$this->applyWpFilters(GLOBAL_NS.'_auto_clear_on_plugin_activation_deactivation', true)) {
+ return 0; // Nothing to do here.
+ }
+ return $this->{($network_wide ? 'autoWipeCache' : 'autoClearCache')}();
+ }
+}
diff --git a/src/includes/traits/Plugin/WcpPostTypeUtils.php b/src/includes/traits/Plugin/WcpPostTypeUtils.php
index 5865905a..4589f5ee 100644
--- a/src/includes/traits/Plugin/WcpPostTypeUtils.php
+++ b/src/includes/traits/Plugin/WcpPostTypeUtils.php
@@ -1,66 +1,71 @@
autoClearCustomPostTypeArchiveCache = function ($post_id) use ($self) {
- $counter = 0; // Initialize.
+trait WcpPostTypeUtils {
+ /*
+ * Automatically clears cache files for a custom post type archive view.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param int $post_id A WordPress post ID.
+ *
+ * @throws \Exception If a clear failure occurs.
+ *
+ * @return int Total files cleared by this routine (if any).
+ *
+ * @note Unlike many of the other `auto_` methods, this one is NOT currently
+ * attached to any hooks. However, it is called upon by {@link autoClearPostCache()}.
+ */
+ public function autoClearCustomPostTypeArchiveCache($post_id)
+ {
+ $counter = 0; // Initialize.
- if (!($post_id = (integer) $post_id)) {
- return $counter; // Nothing to do.
- }
- if (!is_null($done = &$self->cacheKey('autoClearCustomPostTypeArchiveCache', $post_id))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
+ if (!($post_id = (integer) $post_id)) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_null($done = &$this->cacheKey('autoClearCustomPostTypeArchiveCache', $post_id))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if (!$self->options['cache_clear_custom_post_type_enable']) {
- return $counter; // Nothing to do.
- }
- if (!is_dir($cache_dir = $self->cacheDir())) {
- return $counter; // Nothing to do.
- }
- if (!($post_type = get_post_type($post_id))) {
- return $counter; // Nothing to do.
- }
- if (!($all_custom_post_types = get_post_types(array('_builtin' => false)))) {
- return $counter; // No custom post types.
- }
- if (!in_array($post_type, array_keys($all_custom_post_types), true)) {
- return $counter; // This is NOT a custom post type.
- }
- if (!($custom_post_type = get_post_type_object($post_type))) {
- return $counter; // Unable to retrieve post type.
- }
- if (empty($custom_post_type->labels->name) || !($custom_post_type_name = $custom_post_type->labels->name)) {
- $custom_post_type_name = __('Untitled', SLUG_TD);
- }
- if (!($custom_post_type_archive_link = get_post_type_archive_link($post_type))) {
- return $counter; // Nothing to do; no link to work from in this case.
- }
- $regex = $self->buildHostCachePathRegex($custom_post_type_archive_link);
- $counter += $self->clearFilesFromHostCacheDir($regex);
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!$this->options['cache_clear_custom_post_type_enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_dir($cache_dir = $this->cacheDir())) {
+ return $counter; // Nothing to do.
+ }
+ if (!($post_type = get_post_type($post_id))) {
+ return $counter; // Nothing to do.
+ }
+ if (!($all_custom_post_types = get_post_types(['_builtin' => false]))) {
+ return $counter; // No custom post types.
+ }
+ if (!in_array($post_type, array_keys($all_custom_post_types), true)) {
+ return $counter; // This is NOT a custom post type.
+ }
+ if (!($custom_post_type = get_post_type_object($post_type))) {
+ return $counter; // Unable to retrieve post type.
+ }
+ if (empty($custom_post_type->labels->name) || !($custom_post_type_name = $custom_post_type->labels->name)) {
+ $custom_post_type_name = __('Untitled', SLUG_TD);
+ }
+ if (!($custom_post_type_archive_link = get_post_type_archive_link($post_type))) {
+ return $counter; // Nothing to do; no link to work from in this case.
+ }
+ $regex = $this->buildHostCachePathRegex($custom_post_type_archive_link);
+ $counter += $this->clearFilesFromHostCacheDir($regex);
- if ($counter && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected changes. Found %2$s in the cache for Custom Post Type: %3$s
; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($counter)), esc_html($custom_post_type_name)));
- }
- $counter += $self->autoClearXmlFeedsCache('custom-post-type', $post_id);
+ if ($counter && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected changes. Found %2$s in the cache for Custom Post Type: %3$s
; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($counter)), esc_html($custom_post_type_name))
+ );
+ }
+ $counter += $this->autoClearXmlFeedsCache('custom-post-type', $post_id);
- return $counter;
-};
+ return $counter;
+ }
+}
diff --git a/src/includes/traits/Plugin/WcpPostUtils.php b/src/includes/traits/Plugin/WcpPostUtils.php
index 793274c1..bb446934 100644
--- a/src/includes/traits/Plugin/WcpPostUtils.php
+++ b/src/includes/traits/Plugin/WcpPostUtils.php
@@ -1,178 +1,184 @@
autoClearPostCache = function ($post_id, $force = false) use ($self) {
- $counter = 0; // Initialize.
+trait WcpPostUtils {
+ /*
+ * Automatically clears cache files for a particular post.
+ *
+ * @attaches-to `save_post` hook.
+ * @attaches-to `delete_post` hook.
+ * @attaches-to `clean_post_cache` hook.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param int $post_id A WordPress post ID.
+ * @param bool $force Defaults to a `FALSE` value.
+ * Pass as TRUE if clearing should be done for `draft`, `pending`,
+ * `future`, or `trash` post statuses.
+ *
+ * @throws \Exception If a clear failure occurs.
+ *
+ * @return int Total files cleared by this routine (if any).
+ *
+ * @note This is also called upon by other routines which listen for
+ * events that are indirectly associated with a post ID.
+ */
+ public function autoClearPostCache($post_id, $force = false)
+ {
+ $counter = 0; // Initialize.
- if (!is_null($allow = &$self->cacheKey('autoClearPostCache_allow'))) {
- if ($allow === false) { // Disallow?
- $allow = true; // Reset flag.
- return $counter;
+ if (!is_null($allow = &$this->cacheKey('autoClearPostCache_allow'))) {
+ if ($allow === false) { // Disallow?
+ $allow = true; // Reset flag.
+ return $counter;
+ }
}
- }
- if (!($post_id = (integer) $post_id)) {
- return $counter; // Nothing to do.
- }
- if (!is_null($done = &$self->cacheKey('autoClearPostCache', array($post_id, $force)))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
+ if (!($post_id = (integer) $post_id)) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_null($done = &$this->cacheKey('autoClearPostCache', [$post_id, $force]))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
- return $counter; // Nothing to do.
- }
- if (!is_dir($cache_dir = $self->cacheDir())) {
- return $counter; // Nothing to do.
- }
- if (!($post_type = get_post_type($post_id))) {
- return $counter; // Nothing to do.
- }
- $post_statuses = $self->postStatuses();
- $unpublished_post_statuses = array_diff($post_statuses, array('publish'));
- $is_bbpress_post_type = in_array($post_type, $self->bbPressPostTypes(), true);
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_dir($cache_dir = $this->cacheDir())) {
+ return $counter; // Nothing to do.
+ }
+ if (!($post_type = get_post_type($post_id))) {
+ return $counter; // Nothing to do.
+ }
+ $post_statuses = $this->postStatuses();
+ $unpublished_post_statuses = array_diff($post_statuses, ['publish']);
+ $is_bbpress_post_type = in_array($post_type, $this->bbPressPostTypes(), true);
- if (!empty($self->pre_post_update_post_permalink[$post_id])) {
- $permalink = $self->pre_post_update_post_permalink[$post_id];
- $self->pre_post_update_post_permalink[$post_id] = ''; // Reset; only used for post status transitions.
- } elseif (!($permalink = get_permalink($post_id))) {
- return $counter; // Nothing we can do.
- }
- if (!($post_status = get_post_status($post_id))) {
- return $counter; // Nothing to do.
- }
- if ($post_status === 'draft' && isset($GLOBALS['pagenow'], $_POST['publish'])
- && is_admin() && $GLOBALS['pagenow'] === 'post.php' && current_user_can('publish_posts')
- && strpos(wp_get_referer(), '/post-new.php') !== false
- ) {
- $post_status = 'publish'; // A new post being published now.
- }
- if (in_array($post_status, array('inherit', 'auto-draft'), true)) {
- return $counter; // Nothing to do. Note: `inherit` = revision.
- }
- if (in_array($post_status, array('draft', 'pending', 'future', 'trash'), true) && !$force) {
- return $counter; // Nothing to do; i.e., NOT forcing in this case.
- }
- if (($post_type_obj = get_post_type_object($post_type)) && !empty($post_type_obj->labels->singular_name)) {
- $post_type_singular_name = $post_type_obj->labels->singular_name; // Singular name for the post type.
- } else {
- $post_type_singular_name = __('Post', SLUG_TD); // Default value.
- }
- $regex = $self->buildHostCachePathRegex($permalink);
- $counter += $self->clearFilesFromHostCacheDir($regex);
+ if (!empty($this->pre_post_update_post_permalink[$post_id])) {
+ $permalink = $this->pre_post_update_post_permalink[$post_id];
+ $this->pre_post_update_post_permalink[$post_id] = ''; // Reset; only used for post status transitions.
+ } elseif (!($permalink = get_permalink($post_id))) {
+ return $counter; // Nothing we can do.
+ }
+ if (!($post_status = get_post_status($post_id))) {
+ return $counter; // Nothing to do.
+ }
+ if ($post_status === 'draft' && isset($GLOBALS['pagenow'], $_POST['publish'])
+ && is_admin() && $GLOBALS['pagenow'] === 'post.php' && current_user_can('publish_posts')
+ && strpos(wp_get_referer(), '/post-new.php') !== false
+ ) {
+ $post_status = 'publish'; // A new post being published now.
+ }
+ if (in_array($post_status, ['inherit', 'auto-draft'], true)) {
+ return $counter; // Nothing to do. Note: `inherit` = revision.
+ }
+ if (in_array($post_status, ['draft', 'pending', 'future', 'trash'], true) && !$force) {
+ return $counter; // Nothing to do; i.e., NOT forcing in this case.
+ }
+ if (($post_type_obj = get_post_type_object($post_type)) && !empty($post_type_obj->labels->singular_name)) {
+ $post_type_singular_name = $post_type_obj->labels->singular_name; // Singular name for the post type.
+ } else {
+ $post_type_singular_name = __('Post', SLUG_TD); // Default value.
+ }
+ $regex = $this->buildHostCachePathRegex($permalink);
+ $counter += $this->clearFilesFromHostCacheDir($regex);
- if ($counter && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected changes. Found %2$s in the cache for %3$s ID: %4$s
; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($counter)), esc_html($post_type_singular_name), esc_html($post_id)));
- }
- $counter += $self->autoClearXmlFeedsCache('blog');
- $counter += $self->autoClearXmlFeedsCache('post-terms', $post_id);
- $counter += $self->autoClearXmlFeedsCache('post-authors', $post_id);
+ if ($counter && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected changes. Found %2$s in the cache for %3$s ID: %4$s
; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($counter)), esc_html($post_type_singular_name), esc_html($post_id))
+ );
+ }
+ $counter += $this->autoClearXmlFeedsCache('blog');
+ $counter += $this->autoClearXmlFeedsCache('post-terms', $post_id);
+ $counter += $this->autoClearXmlFeedsCache('post-authors', $post_id);
- $counter += $self->autoClearXmlSitemapsCache();
- $counter += $self->autoClearHomePageCache();
- $counter += $self->autoClearPostsPageCache();
- $counter += $self->autoClearPostTermsCache($post_id, $force);
- $counter += $self->autoClearCustomPostTypeArchiveCache($post_id);
- /*[pro strip-from="lite"]*/
- $counter += $self->autoClearUrlsCache();
- /*[/pro]*/
+ $counter += $this->autoClearXmlSitemapsCache();
+ $counter += $this->autoClearHomePageCache();
+ $counter += $this->autoClearPostsPageCache();
+ $counter += $this->autoClearPostTermsCache($post_id, $force);
+ $counter += $this->autoClearCustomPostTypeArchiveCache($post_id);
+ /*[pro strip-from="lite"]*/
+ $counter += $this->autoClearUrlsCache();
+ /*[/pro]*/
- if ($post_type !== 'page' && ($parent_post_id = wp_get_post_parent_id($post_id))) {
- // Recursion: i.e., nested post types like bbPress forums/topic/replies.
- $counter += $self->autoClearPostCache($parent_post_id, $force);
+ if ($post_type !== 'page' && ($parent_post_id = wp_get_post_parent_id($post_id))) {
+ // Recursion: i.e., nested post types like bbPress forums/topic/replies.
+ $counter += $this->autoClearPostCache($parent_post_id, $force);
+ }
+ return $counter;
}
- return $counter;
-};
-$self->auto_clear_post_cache = $self->autoClearPostCache; // Back compat.
+$this->auto_clear_post_cache = $this->autoClearPostCache; // Back compat.
-/*
- * Handles post status transitioning.
- *
- * @attaches-to `pre_post_update` hook.
- *
- * @since 150422 Rewrite.
- *
- * @param int $post_id Post ID.
- * @param array $data Array of unslashed post data.
- *
- * @throws \Exception If a clear failure occurs.
- *
- * @return int Total files cleared by this routine (if any).
- *
- * @note This is also called upon by other routines which listen for
- * events that are indirectly associated with a post ID.
- */
-$self->autoClearPostCacheTransition = function ($post_id, $data) use ($self) {
- $counter = 0; // Initialize.
-
- $old_status = (string) get_post_status($post_id);
- $new_status = (string) $data['post_status'];
/*
- * When a post has a status of `pending` or `draft`, the `get_permalink()` function
- * does not return a friendly permalink and therefore `autoClearPostCache()` will
- * have no way of building a path to the cache file that should be cleared as part of
- * this post status transition. To get around this, we temporarily store the permalink
- * in $self->pre_post_update_post_permalink for `autoClearPostCache()` to use.
+ * Handles post status transitioning.
+ *
+ * @attaches-to `pre_post_update` hook.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param int $post_id Post ID.
+ * @param array $data Array of unslashed post data.
+ *
+ * @throws \Exception If a clear failure occurs.
*
- * See also:
+ * @return int Total files cleared by this routine (if any).
+ *
+ * @note This is also called upon by other routines which listen for
+ * events that are indirectly associated with a post ID.
*/
- if (in_array($new_status, array('pending', 'draft'), true)) {
- $self->pre_post_update_post_permalink[$post_id] = get_permalink($post_id);
- }
- // Begin post status transition sub-routine now.
+ public function autoClearPostCacheTransition($post_id, $data)
+ {
+ $counter = 0; // Initialize.
- if (!is_null($done = &$self->cacheKey('autoClearPostCacheTransition', array($old_status, $new_status, $post_id)))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
+ $old_status = (string) get_post_status($post_id);
+ $new_status = (string) $data['post_status'];
+ /*
+ * When a post has a status of `pending` or `draft`, the `get_permalink()` function
+ * does not return a friendly permalink and therefore `autoClearPostCache()` will
+ * have no way of building a path to the cache file that should be cleared as part of
+ * this post status transition. To get around this, we temporarily store the permalink
+ * in $this->pre_post_update_post_permalink for `autoClearPostCache()` to use.
+ *
+ * See also:
+ */
+ if (in_array($new_status, ['pending', 'draft'], true)) {
+ $this->pre_post_update_post_permalink[$post_id] = get_permalink($post_id);
+ }
+ // Begin post status transition sub-routine now.
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if ($new_status === $old_status) {
- return $counter; // Nothing to do.
- }
- if (!($post_type = get_post_type($post_id))) {
- return $counter; // Nothing to do.
- }
- $post_statuses = $self->postStatuses();
- $unpublished_post_statuses = array_diff($post_statuses, array('publish'));
- $is_bbpress_post_type = in_array($post_type, $self->bbPressPostTypes(), true);
+ if (!is_null($done = &$this->cacheKey('autoClearPostCacheTransition', [$old_status, $new_status, $post_id]))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- if ($is_bbpress_post_type) {
- if (in_array($old_status, array('publish', 'private', 'closed', 'spam', 'hidden'), true)) {
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if ($new_status === $old_status) {
+ return $counter; // Nothing to do.
+ }
+ if (!($post_type = get_post_type($post_id))) {
+ return $counter; // Nothing to do.
+ }
+ $post_statuses = $this->postStatuses();
+ $unpublished_post_statuses = array_diff($post_statuses, ['publish']);
+ $is_bbpress_post_type = in_array($post_type, $this->bbPressPostTypes(), true);
+
+ if ($is_bbpress_post_type) {
+ if (in_array($old_status, ['publish', 'private', 'closed', 'spam', 'hidden'], true)) {
+ if (in_array($new_status, $unpublished_post_statuses, true)) {
+ $counter += $this->autoClearPostCache($post_id, true);
+ }
+ }
+ } elseif (in_array($old_status, ['publish', 'private'], true)) {
if (in_array($new_status, $unpublished_post_statuses, true)) {
- $counter += $self->autoClearPostCache($post_id, true);
+ $counter += $this->autoClearPostCache($post_id, true);
}
}
- } elseif (in_array($old_status, array('publish', 'private'), true)) {
- if (in_array($new_status, $unpublished_post_statuses, true)) {
- $counter += $self->autoClearPostCache($post_id, true);
- }
+ return $counter;
}
- return $counter;
-};
+}
diff --git a/src/includes/traits/Plugin/WcpS2cleanUtils.php b/src/includes/traits/Plugin/WcpS2cleanUtils.php
index 12be0108..955d50db 100644
--- a/src/includes/traits/Plugin/WcpS2cleanUtils.php
+++ b/src/includes/traits/Plugin/WcpS2cleanUtils.php
@@ -2,44 +2,48 @@
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Traits\Plugin;
-/*
- * Wipe (i.e., reset) s2Clean cache.
- *
- * @since 151002 While adding OPCache support.
- *
- * @param bool $manually True if wiping is done manually.
- * @param boolean $maybe Defaults to a true value.
- *
- * @return integer Total files wiped in s2Clean.
- */
-$self->wipeS2CleanCache = function ($manually = false, $maybe = true) use ($self) {
- $counter = 0; // Initialize counter.
+trait WcpS2cleanUtils {
+ /*
+ * Wipe (i.e., reset) s2Clean cache.
+ *
+ * @since 151002 While adding OPCache support.
+ *
+ * @param bool $manually True if wiping is done manually.
+ * @param boolean $maybe Defaults to a true value.
+ *
+ * @return integer Total files wiped in s2Clean.
+ */
+ public function wipeS2CleanCache($manually = false, $maybe = true)
+ {
+ $counter = 0; // Initialize counter.
- if ($maybe && !$self->options['cache_clear_s2clean_enable']) {
- return $counter; // Not enabled at this time.
- }
- if (!$self->functionIsPossible('s2clean')) {
- return $counter; // Not possible.
- }
- $counter += s2clean()->md_cache_clear();
+ if ($maybe && !$this->options['cache_clear_s2clean_enable']) {
+ return $counter; // Not enabled at this time.
+ }
+ if (!$this->functionIsPossible('s2clean')) {
+ return $counter; // Not possible.
+ }
+ $counter += s2clean()->md_cache_clear();
- return $counter;
-};
+ return $counter;
+ }
-/*
- * Clear (i.e., reset) s2Clean cache.
- *
- * @since 151002 While adding OPCache support.
- *
- * @param bool $manually True if clearing is done manually.
- * @param boolean $maybe Defaults to a true value.
- *
- * @return integer Total files cleared in s2Clean.
- */
-$self->clearS2CleanCache = function ($manually = false, $maybe = true) use ($self) {
- if (!is_multisite() || is_main_site() || current_user_can($self->network_cap)) {
- return $self->wipeS2CleanCache($manually, $maybe);
+ /*
+ * Clear (i.e., reset) s2Clean cache.
+ *
+ * @since 151002 While adding OPCache support.
+ *
+ * @param bool $manually True if clearing is done manually.
+ * @param boolean $maybe Defaults to a true value.
+ *
+ * @return integer Total files cleared in s2Clean.
+ */
+ public function clearS2CleanCache($manually = false, $maybe = true)
+ {
+ if (!is_multisite() || is_main_site() || current_user_can($this->network_cap)) {
+ return $this->wipeS2CleanCache($manually, $maybe);
+ }
+ return 0; // Not applicable.
}
- return 0; // Not applicable.
-};
+}
/*[/pro]*/
diff --git a/src/includes/traits/Plugin/WcpSettingUtils.php b/src/includes/traits/Plugin/WcpSettingUtils.php
index b66a6504..329679fe 100644
--- a/src/includes/traits/Plugin/WcpSettingUtils.php
+++ b/src/includes/traits/Plugin/WcpSettingUtils.php
@@ -1,31 +1,34 @@
autoClearCacheOnSettingChanges = function () use ($self) {
- $counter = 0; // Initialize.
- $pagenow = !empty($GLOBALS['pagenow']) ? $GLOBALS['pagenow'] : '';
- $settings_updated = !empty($_REQUEST['settings-updated']);
+trait WcpSettingUtils {
+ /*
+ * Automatically clears all cache files for current blog under various conditions;
+ * used to check for conditions that don't have a hook that we can attach to.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `admin_init` hook.
+ */
+ public function autoClearCacheOnSettingChanges()
+ {
+ $counter = 0; // Initialize.
+ $pagenow = !empty($GLOBALS['pagenow']) ? $GLOBALS['pagenow'] : '';
+ $settings_updated = !empty($_REQUEST['settings-updated']);
- if (!is_null($done = &$self->cacheKey('autoClearCacheOnSettingChanges', array($pagenow, $settings_updated)))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
+ if (!is_null($done = &$this->cacheKey('autoClearCacheOnSettingChanges', [$pagenow, $settings_updated]))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- if ($pagenow === 'options-general.php' && $settings_updated) {
- $counter += $self->autoClearCache();
- } elseif ($pagenow === 'options-reading.php' && $settings_updated) {
- $counter += $self->autoClearCache();
- } elseif ($pagenow === 'options-discussion.php' && $settings_updated) {
- $counter += $self->autoClearCache();
- } elseif ($pagenow === 'options-permalink.php' && $settings_updated) {
- $counter += $self->autoClearCache();
+ if ($pagenow === 'options-general.php' && $settings_updated) {
+ $counter += $this->autoClearCache();
+ } elseif ($pagenow === 'options-reading.php' && $settings_updated) {
+ $counter += $this->autoClearCache();
+ } elseif ($pagenow === 'options-discussion.php' && $settings_updated) {
+ $counter += $this->autoClearCache();
+ } elseif ($pagenow === 'options-permalink.php' && $settings_updated) {
+ $counter += $this->autoClearCache();
+ }
}
-};
+}
diff --git a/src/includes/traits/Plugin/WcpSitemapUtils.php b/src/includes/traits/Plugin/WcpSitemapUtils.php
index 92a19e9c..38088bf3 100644
--- a/src/includes/traits/Plugin/WcpSitemapUtils.php
+++ b/src/includes/traits/Plugin/WcpSitemapUtils.php
@@ -1,47 +1,53 @@
autoClearXmlSitemapsCache = function () use ($self) {
- $counter = 0; // Initialize.
+trait WcpSitemapUtils {
- if (!is_null($done = &$self->cacheKey('autoClearXmlSitemapsCache'))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
+ /*
+ * Automatically clears cache files related to XML sitemaps.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @throws \Exception If a clear failure occurs.
+ *
+ * @return int Total files cleared by this routine (if any).
+ *
+ * @note Unlike many of the other `auto_` methods, this one is NOT currently
+ * attached to any hooks. However, it is called upon by {@link autoClearPostCache()}.
+ */
+ public function autoClearXmlSitemapsCache()
+ {
+ $counter = 0; // Initialize.
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if (!$self->options['cache_clear_xml_sitemaps_enable']) {
- return $counter; // Nothing to do.
- }
- if (!$self->options['cache_clear_xml_sitemap_patterns']) {
- return $counter; // Nothing to do.
- }
- if (!is_dir($cache_dir = $self->cacheDir())) {
- return $counter; // Nothing to do.
- }
- if (!($regex_frags = $self->buildHostCachePathRegexFragsFromWcUris($self->options['cache_clear_xml_sitemap_patterns'], ''))) {
- return $counter; // There are no patterns to look for.
- }
- $regex = $self->buildHostCachePathRegex('', '\/'.$regex_frags.'\.');
- $counter += $self->clearFilesFromHostCacheDir($regex);
+ if (!is_null($done = &$this->cacheKey('autoClearXmlSitemapsCache'))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
+
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!$this->options['cache_clear_xml_sitemaps_enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!$this->options['cache_clear_xml_sitemap_patterns']) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_dir($cache_dir = $this->cacheDir())) {
+ return $counter; // Nothing to do.
+ }
+ if (!($regex_frags = $this->buildHostCachePathRegexFragsFromWcUris($this->options['cache_clear_xml_sitemap_patterns'], ''))) {
+ return $counter; // There are no patterns to look for.
+ }
+ $regex = $this->buildHostCachePathRegex('', '\/'.$regex_frags.'\.');
+ $counter += $this->clearFilesFromHostCacheDir($regex);
- if ($counter && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected changes. Found %2$s in the cache for XML sitemaps; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($counter))));
+ if ($counter && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected changes. Found %2$s in the cache for XML sitemaps; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($counter)))
+ );
+ }
+ return $counter;
}
- return $counter;
-};
+}
diff --git a/src/includes/traits/Plugin/WcpTermUtils.php b/src/includes/traits/Plugin/WcpTermUtils.php
index 7b469c3d..4f4ecdd1 100644
--- a/src/includes/traits/Plugin/WcpTermUtils.php
+++ b/src/includes/traits/Plugin/WcpTermUtils.php
@@ -1,139 +1,144 @@
autoClearPostTermsCache = function ($post_id, $force = false) use ($self) {
- $counter = 0; // Initialize.
- $enqueued_notices = 0; // Initialize.
-
- if (!($post_id = (integer) $post_id)) {
- return $counter; // Nothing to do.
- }
- if (!is_null($done = &$self->cacheKey('autoClearPostTermsCache', array($post_id, $force)))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
-
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
- return $counter; // Nothing to do.
- }
- if (!$self->options['cache_clear_term_category_enable'] && !$self->options['cache_clear_term_post_tag_enable'] && !$self->options['cache_clear_term_other_enable']) {
- return $counter; // Nothing to do.
- }
- if (!is_dir($cache_dir = $self->cacheDir())) {
- return $counter; // Nothing to do.
- }
- $post_status = get_post_status($post_id); // Cache this.
-
- if ($post_status === 'draft' && isset($GLOBALS['pagenow'], $_POST['publish'])
- && is_admin() && $GLOBALS['pagenow'] === 'post.php' && current_user_can('publish_posts')
- && strpos(wp_get_referer(), '/post-new.php') !== false
- ) {
- $post_status = 'publish'; // A new post being published now.
- }
- if (in_array($post_status, array('inherit', 'auto-draft'), true)) {
- return $counter; // Nothing to do. Note: `inherit` = revision.
- }
- if (in_array($post_status, array('draft', 'pending', 'future'), true) && !$force) {
- return $counter; // Nothing to do; i.e., NOT forcing in this case.
- }
+trait WcpTermUtils {
/*
- * Build an array of available taxonomies for this post (as taxonomy objects).
+ * Automatically clears cache files for terms associated with a post.
+ *
+ * @attaches-to `added_term_relationship` hook.
+ * @attaches-to `delete_term_relationships` hook.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param int $post_id A WordPress post ID.
+ * @param bool $force Defaults to a `FALSE` value.
+ * Pass as TRUE if clearing should be done for `draft`, `pending`,
+ * or `future` post statuses.
+ *
+ * @throws \Exception If a clear failure occurs.
+ *
+ * @return int Total files cleared by this routine (if any).
+ *
+ * @note In addition to the hooks this is attached to, it is also
+ * called upon by {@link autoClearPostCache()}.
*/
- $taxonomies = get_object_taxonomies(get_post($post_id), 'objects');
+ public function autoClearPostTermsCache($post_id, $force = false)
+ {
+ $counter = 0; // Initialize.
+ $enqueued_notices = 0; // Initialize.
- if (!is_array($taxonomies)) {
- return $counter; // Nothing to do.
- }
- /*
- * Build an array of terms associated with this post for each taxonomy.
- * Also save taxonomy label information for Dashboard messaging later.
- */
- $terms = array();
- $taxonomy_labels = array();
+ if (!($post_id = (integer) $post_id)) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_null($done = &$this->cacheKey('autoClearPostTermsCache', [$post_id, $force]))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- foreach ($taxonomies as $_taxonomy) {
- if (// Check if this is a taxonomy/term that we should clear.
- ($_taxonomy->name === 'category' && !$self->options['cache_clear_term_category_enable'])
- || ($_taxonomy->name === 'post_tag' && !$self->options['cache_clear_term_post_tag_enable'])
- || ($_taxonomy->name !== 'category' && $_taxonomy->name !== 'post_tag' && !$self->options['cache_clear_term_other_enable'])
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
+ return $counter; // Nothing to do.
+ }
+ if (!$this->options['cache_clear_term_category_enable'] && !$this->options['cache_clear_term_post_tag_enable'] && !$this->options['cache_clear_term_other_enable']) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_dir($cache_dir = $this->cacheDir())) {
+ return $counter; // Nothing to do.
+ }
+ $post_status = get_post_status($post_id); // Cache this.
+
+ if ($post_status === 'draft' && isset($GLOBALS['pagenow'], $_POST['publish'])
+ && is_admin() && $GLOBALS['pagenow'] === 'post.php' && current_user_can('publish_posts')
+ && strpos(wp_get_referer(), '/post-new.php') !== false
) {
- continue; // Continue; nothing to do for this taxonomy.
+ $post_status = 'publish'; // A new post being published now.
+ }
+ if (in_array($post_status, ['inherit', 'auto-draft'], true)) {
+ return $counter; // Nothing to do. Note: `inherit` = revision.
+ }
+ if (in_array($post_status, ['draft', 'pending', 'future'], true) && !$force) {
+ return $counter; // Nothing to do; i.e., NOT forcing in this case.
+ }
+ /*
+ * Build an array of available taxonomies for this post (as taxonomy objects).
+ */
+ $taxonomies = get_object_taxonomies(get_post($post_id), 'objects');
+
+ if (!is_array($taxonomies)) {
+ return $counter; // Nothing to do.
}
- if (is_array($_terms = wp_get_post_terms($post_id, $_taxonomy->name))) {
- $terms = array_merge($terms, $_terms);
- if (empty($_taxonomy->labels->singular_name) || $_taxonomy->labels->singular_name === '') {
- $taxonomy_labels[$_taxonomy->name] = $_taxonomy->name;
- } else {
- $taxonomy_labels[$_taxonomy->name] = $_taxonomy->labels->singular_name;
+ /*
+ * Build an array of terms associated with this post for each taxonomy.
+ * Also save taxonomy label information for Dashboard messaging later.
+ */
+ $terms = [];
+ $taxonomy_labels = [];
+
+ foreach ($taxonomies as $_taxonomy) {
+ if (// Check if this is a taxonomy/term that we should clear.
+ ($_taxonomy->name === 'category' && !$this->options['cache_clear_term_category_enable'])
+ || ($_taxonomy->name === 'post_tag' && !$this->options['cache_clear_term_post_tag_enable'])
+ || ($_taxonomy->name !== 'category' && $_taxonomy->name !== 'post_tag' && !$this->options['cache_clear_term_other_enable'])
+ ) {
+ continue; // Continue; nothing to do for this taxonomy.
+ }
+ if (is_array($_terms = wp_get_post_terms($post_id, $_taxonomy->name))) {
+ $terms = array_merge($terms, $_terms);
+ if (empty($_taxonomy->labels->singular_name) || $_taxonomy->labels->singular_name === '') {
+ $taxonomy_labels[$_taxonomy->name] = $_taxonomy->name;
+ } else {
+ $taxonomy_labels[$_taxonomy->name] = $_taxonomy->labels->singular_name;
+ }
}
}
- }
- unset($_taxonomy, $_terms);
+ unset($_taxonomy, $_terms);
- if (empty($terms)) {
- return $counter; // Nothing to do.
- }
- /*
- * Build an array of terms with term names,
- * permalinks, and associated taxonomy labels.
- */
- $terms_to_clear = array();
- $_i = 0;
+ if (empty($terms)) {
+ return $counter; // Nothing to do.
+ }
+ /*
+ * Build an array of terms with term names,
+ * permalinks, and associated taxonomy labels.
+ */
+ $terms_to_clear = [];
+ $_i = 0;
- foreach ($terms as $_term) {
- if (($_link = get_term_link($_term))) {
- $terms_to_clear[$_i]['permalink'] = $_link;
- $terms_to_clear[$_i]['term_name'] = $_term->name;
- if (!empty($taxonomy_labels[$_term->taxonomy])) {
- $terms_to_clear[$_i]['taxonomy_label'] = $taxonomy_labels[$_term->taxonomy];
- } else {
- $terms_to_clear[$_i]['taxonomy_label'] = $_term->taxonomy;
+ foreach ($terms as $_term) {
+ if (($_link = get_term_link($_term))) {
+ $terms_to_clear[$_i]['permalink'] = $_link;
+ $terms_to_clear[$_i]['term_name'] = $_term->name;
+ if (!empty($taxonomy_labels[$_term->taxonomy])) {
+ $terms_to_clear[$_i]['taxonomy_label'] = $taxonomy_labels[$_term->taxonomy];
+ } else {
+ $terms_to_clear[$_i]['taxonomy_label'] = $_term->taxonomy;
+ }
}
+ ++$_i; // Array index counter.
}
- ++$_i; // Array index counter.
- }
- unset($_term, $_link, $_i);
+ unset($_term, $_link, $_i);
- if (empty($terms_to_clear)) {
- return $counter; // Nothing to do.
- }
- foreach ($terms_to_clear as $_term) {
- $_term_regex = $self->buildHostCachePathRegex($_term['permalink']);
- $_term_counter = $self->clearFilesFromHostCacheDir($_term_regex);
- $counter += $_term_counter; // Add to overall counter.
+ if (empty($terms_to_clear)) {
+ return $counter; // Nothing to do.
+ }
+ foreach ($terms_to_clear as $_term) {
+ $_term_regex = $this->buildHostCachePathRegex($_term['permalink']);
+ $_term_counter = $this->clearFilesFromHostCacheDir($_term_regex);
+ $counter += $_term_counter; // Add to overall counter.
- if ($_term_counter && $enqueued_notices < 100 && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected changes. Found %2$s in the cache for %3$s: %4$s
; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($_term_counter)), esc_html($_term['taxonomy_label']), esc_html($_term['term_name'])));
- ++$enqueued_notices; // Increment enqueued notices counter.
+ if ($_term_counter && $enqueued_notices < 100 && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected changes. Found %2$s in the cache for %3$s: %4$s
; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($_term_counter)), esc_html($_term['taxonomy_label']), esc_html($_term['term_name']))
+ );
+ ++$enqueued_notices; // Increment enqueued notices counter.
+ }
}
- }
- unset($_term, $_term_regex, $_term_counter); // Housekeeping.
+ unset($_term, $_term_regex, $_term_counter); // Housekeeping.
- $counter += $self->autoClearXmlFeedsCache('post-terms', $post_id);
+ $counter += $this->autoClearXmlFeedsCache('post-terms', $post_id);
- return $counter;
-};
+ return $counter;
+ }
+}
diff --git a/src/includes/traits/Plugin/WcpTransientUtils.php b/src/includes/traits/Plugin/WcpTransientUtils.php
index fe1000e1..f331c123 100644
--- a/src/includes/traits/Plugin/WcpTransientUtils.php
+++ b/src/includes/traits/Plugin/WcpTransientUtils.php
@@ -2,99 +2,104 @@
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Traits\Plugin;
-/*
-* Automatically wipes expired transients.
-*
-* @since 151220 Adding support for expired transients.
-*
-* @param bool $manually True if wiping is done manually.
-* @param boolean $maybe Defaults to a true value.
-*
-* @throws \Exception If a wipe failure occurs.
-*
-* @return int Total DB rows wiped by this routine (if any).
-*/
-$self->wipeExpiredTransients = function ($manually = false, $maybe = true) use ($self) {
- if (!is_multisite()) {
- return $self->clearExpiredTransients();
- }
- $counter = 0; // Initialize.
+trait WcpTransientUtils
+{
+ /*
+ * Automatically wipes expired transients.
+ *
+ * @since 151220 Adding support for expired transients.
+ *
+ * @param bool $manually True if wiping is done manually.
+ * @param boolean $maybe Defaults to a true value.
+ *
+ * @throws \Exception If a wipe failure occurs.
+ *
+ * @return int Total DB rows wiped by this routine (if any).
+ */
+ public function wipeExpiredTransients($manually = false, $maybe = true)
+ {
+ if (!is_multisite()) {
+ return $this->clearExpiredTransients();
+ }
+ $counter = 0; // Initialize.
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if ($maybe && !$self->options['cache_clear_transients_enable']) {
- return $counter; // Not enabled at this time.
- }
- $time = time(); // Current UTC time.
- $wpdb = $self->wpdb(); // WP database class.
- $_transient_timeout_ = $wpdb->esc_like('_transient_timeout_');
- $_site_transient_timeout_ = $wpdb->esc_like('_site_transient_timeout_');
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if ($maybe && !$this->options['cache_clear_transients_enable']) {
+ return $counter; // Not enabled at this time.
+ }
+ $time = time(); // Current UTC time.
+ $wpdb = $this->wpdb(); // WP database class.
+ $_transient_timeout_ = $wpdb->esc_like('_transient_timeout_');
+ $_site_transient_timeout_ = $wpdb->esc_like('_site_transient_timeout_');
- switch_to_blog(get_current_site()->blog_id);
- $sql = '
+ switch_to_blog(get_current_site()->blog_id);
+ $sql = '
DELETE FROM `timeouts`, `transients`
USING `'.esc_sql($wpdb->options).'` AS `timeouts`
JOIN `'.esc_sql($wpdb->options).'` `transients` ON `transients`.`option_name` = REPLACE(`timeouts`.`option_name`, \'_timeout\', \'\')
WHERE (`timeouts`.`option_name` LIKE \''.esc_sql($_transient_timeout_).'%\' OR `timeouts`.`option_name` LIKE \''.esc_sql($_site_transient_timeout_).'%\')
AND CAST(`timeouts`.`option_value` AS UNSIGNED) < \''.esc_sql($time).'\'';
- $counter += (int) $wpdb->query(trim($sql));
+ $counter += (int) $wpdb->query(trim($sql));
- $child_blogs = wp_get_sites();
- $child_blogs = is_array($child_blogs) ? $child_blogs : array();
+ $child_blogs = wp_get_sites();
+ $child_blogs = is_array($child_blogs) ? $child_blogs : [];
- foreach ($child_blogs as $_child_blog) {
- switch_to_blog($_child_blog['blog_id']);
- $_sql = '
+ foreach ($child_blogs as $_child_blog) {
+ switch_to_blog($_child_blog['blog_id']);
+ $_sql = '
DELETE FROM `timeouts`, `transients`
USING `'.esc_sql($wpdb->options).'` AS `timeouts`
JOIN `'.esc_sql($wpdb->options).'` `transients` ON `transients`.`option_name` = REPLACE(`timeouts`.`option_name`, \'_timeout\', \'\')
WHERE (`timeouts`.`option_name` LIKE \''.esc_sql($_transient_timeout_).'%\' OR `timeouts`.`option_name` LIKE \''.esc_sql($_site_transient_timeout_).'%\')
AND CAST(`timeouts`.`option_value` AS UNSIGNED) < \''.esc_sql($time).'\'';
- $counter += (int) $wpdb->query(trim($_sql));
- }
- unset($_child_blog, $_sql); // Housekeeping.
+ $counter += (int) $wpdb->query(trim($_sql));
+ }
+ unset($_child_blog, $_sql); // Housekeeping.
- restore_current_blog();
+ restore_current_blog();
- return $counter;
-};
+ return $counter;
+ }
-/*
-* Automatically clears expired transients.
-*
-* @since 151220 Adding support for expired transients.
-*
-* @param bool $manually True if clearing is done manually.
-* @param boolean $maybe Defaults to a true value.
-*
-* @throws \Exception If a clear failure occurs.
-*
-* @return int Total DB rows cleared by this routine (if any).
-*/
-$self->clearExpiredTransients = function ($manually = false, $maybe = true) use($self) {
- $counter = 0; // Initialize.
+ /*
+ * Automatically clears expired transients.
+ *
+ * @since 151220 Adding support for expired transients.
+ *
+ * @param bool $manually True if clearing is done manually.
+ * @param boolean $maybe Defaults to a true value.
+ *
+ * @throws \Exception If a clear failure occurs.
+ *
+ * @return int Total DB rows cleared by this routine (if any).
+ */
+ public function clearExpiredTransients($manually = false, $maybe = true)
+ {
+ $counter = 0; // Initialize.
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if ($maybe && !$self->options['cache_clear_transients_enable']) {
- return $counter; // Not enabled at this time.
- }
- $time = time(); // Current UTC time.
- $wpdb = $self->wpdb(); // WP database class.
- $_transient_timeout_ = $wpdb->esc_like('_transient_timeout_');
- $_site_transient_timeout_ = $wpdb->esc_like('_site_transient_timeout_');
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if ($maybe && !$this->options['cache_clear_transients_enable']) {
+ return $counter; // Not enabled at this time.
+ }
+ $time = time(); // Current UTC time.
+ $wpdb = $this->wpdb(); // WP database class.
+ $_transient_timeout_ = $wpdb->esc_like('_transient_timeout_');
+ $_site_transient_timeout_ = $wpdb->esc_like('_site_transient_timeout_');
- $sql = '
+ $sql = '
DELETE FROM `timeouts`, `transients`
USING `'.esc_sql($wpdb->options).'` AS `timeouts`
JOIN `'.esc_sql($wpdb->options).'` `transients` ON `transients`.`option_name` = REPLACE(`timeouts`.`option_name`, \'_timeout\', \'\')
WHERE (`timeouts`.`option_name` LIKE \''.esc_sql($_transient_timeout_).'%\' OR `timeouts`.`option_name` LIKE \''.esc_sql($_site_transient_timeout_).'%\')
AND CAST(`timeouts`.`option_value` AS UNSIGNED) < \''.esc_sql($time).'\'';
- $counter += (int) $wpdb->query(trim($sql));
+ $counter += (int) $wpdb->query(trim($sql));
- return $counter;
-};
+ return $counter;
+ }
+}
/*[/pro]*/
diff --git a/src/includes/traits/Plugin/WcpUpdaterUtils.php b/src/includes/traits/Plugin/WcpUpdaterUtils.php
index 470113bf..f30d498d 100644
--- a/src/includes/traits/Plugin/WcpUpdaterUtils.php
+++ b/src/includes/traits/Plugin/WcpUpdaterUtils.php
@@ -1,99 +1,102 @@
autoClearOnUpgraderProcessComplete = function (\WP_Upgrader $upgrader_instance, array $data) use ($self) {
- $counter = 0; // Initialize.
+trait WcpUpdaterUtils {
+ /*
+ * Automatically clears all cache files for current blog when WordPress core, or an active component, is upgraded.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `upgrader_process_complete` hook.
+ *
+ * @param \WP_Upgrader $upgrader_instance An instance of \WP_Upgrader.
+ * Or, any class that extends \WP_Upgrader.
+ * @param array $data Array of bulk item update data.
+ *
+ * This array may include one or more of the following keys:
+ *
+ * - `string` `$action` Type of action. Default 'update'.
+ * - `string` `$type` Type of update process; e.g. 'plugin', 'theme', 'core'.
+ * - `boolean` `$bulk` Whether the update process is a bulk update. Default true.
+ * - `array` `$packages` Array of plugin, theme, or core packages to update.
+ */
+ public function autoClearOnUpgraderProcessComplete(\WP_Upgrader $upgrader_instance, array $data)
+ {
+ $counter = 0; // Initialize.
- switch (!empty($data['type']) ? $data['type'] : '') {
- case 'plugin': // Plugin upgrade.
+ switch (!empty($data['type']) ? $data['type'] : '') {
+ case 'plugin': // Plugin upgrade.
- $multi_plugin_update = $single_plugin_update = false;
- $upgrading_active_plugin = false; // Initialize.
+ $multi_plugin_update = $single_plugin_update = false;
+ $upgrading_active_plugin = false; // Initialize.
- if (!empty($data['bulk']) && !empty($data['plugins']) && is_array($data['plugins'])) {
- $multi_plugin_update = true;
- } elseif (!empty($data['plugin']) && is_string($data['plugin'])) {
- $single_plugin_update = true;
- }
- if ($multi_plugin_update) {
- foreach ($data['plugins'] as $_plugin) {
- if ($_plugin && is_string($_plugin) && is_plugin_active($_plugin)) {
- $upgrading_active_plugin = true;
- break; // Got what we need here.
+ if (!empty($data['bulk']) && !empty($data['plugins']) && is_array($data['plugins'])) {
+ $multi_plugin_update = true;
+ } elseif (!empty($data['plugin']) && is_string($data['plugin'])) {
+ $single_plugin_update = true;
+ }
+ if ($multi_plugin_update) {
+ foreach ($data['plugins'] as $_plugin) {
+ if ($_plugin && is_string($_plugin) && is_plugin_active($_plugin)) {
+ $upgrading_active_plugin = true;
+ break; // Got what we need here.
+ }
}
+ unset($_plugin); // Housekeeping.
+ } elseif ($single_plugin_update && is_plugin_active($data['plugin'])) {
+ $upgrading_active_plugin = true;
+ }
+ if ($upgrading_active_plugin) {
+ $counter += $this->autoClearCache();
}
- unset($_plugin); // Housekeeping.
- } elseif ($single_plugin_update && is_plugin_active($data['plugin'])) {
- $upgrading_active_plugin = true;
- }
- if ($upgrading_active_plugin) {
- $counter += $self->autoClearCache();
- }
- break; // Break switch.
+ break; // Break switch.
- case 'theme': // Theme upgrade.
+ case 'theme': // Theme upgrade.
- $current_active_theme = wp_get_theme();
- $current_active_theme_parent = $current_active_theme->parent();
- $multi_theme_update = $single_theme_update = false;
- $upgrading_active_parent_theme = $upgrading_active_theme = false;
+ $current_active_theme = wp_get_theme();
+ $current_active_theme_parent = $current_active_theme->parent();
+ $multi_theme_update = $single_theme_update = false;
+ $upgrading_active_parent_theme = $upgrading_active_theme = false;
- if (!empty($data['bulk']) && !empty($data['themes']) && is_array($data['themes'])) {
- $multi_theme_update = true;
- } elseif (!empty($data['theme']) && is_string($data['theme'])) {
- $single_theme_update = true;
- }
- if ($multi_theme_update) {
- foreach ($data['themes'] as $_theme) {
- if (!$_theme || !is_string($_theme) || !($_theme_obj = wp_get_theme($_theme))) {
- continue; // Unable to acquire theme object instance.
+ if (!empty($data['bulk']) && !empty($data['themes']) && is_array($data['themes'])) {
+ $multi_theme_update = true;
+ } elseif (!empty($data['theme']) && is_string($data['theme'])) {
+ $single_theme_update = true;
+ }
+ if ($multi_theme_update) {
+ foreach ($data['themes'] as $_theme) {
+ if (!$_theme || !is_string($_theme) || !($_theme_obj = wp_get_theme($_theme))) {
+ continue; // Unable to acquire theme object instance.
+ }
+ if ($current_active_theme_parent && $current_active_theme_parent->get_stylesheet() === $_theme_obj->get_stylesheet()) {
+ $upgrading_active_parent_theme = true;
+ break; // Got what we needed here.
+ } elseif ($current_active_theme->get_stylesheet() === $_theme_obj->get_stylesheet()) {
+ $upgrading_active_theme = true;
+ break; // Got what we needed here.
+ }
}
+ unset($_theme, $_theme_obj); // Housekeeping.
+ } elseif ($single_theme_update && ($_theme_obj = wp_get_theme($data['theme']))) {
if ($current_active_theme_parent && $current_active_theme_parent->get_stylesheet() === $_theme_obj->get_stylesheet()) {
$upgrading_active_parent_theme = true;
- break; // Got what we needed here.
} elseif ($current_active_theme->get_stylesheet() === $_theme_obj->get_stylesheet()) {
$upgrading_active_theme = true;
- break; // Got what we needed here.
}
}
- unset($_theme, $_theme_obj); // Housekeeping.
- } elseif ($single_theme_update && ($_theme_obj = wp_get_theme($data['theme']))) {
- if ($current_active_theme_parent && $current_active_theme_parent->get_stylesheet() === $_theme_obj->get_stylesheet()) {
- $upgrading_active_parent_theme = true;
- } elseif ($current_active_theme->get_stylesheet() === $_theme_obj->get_stylesheet()) {
- $upgrading_active_theme = true;
- }
- }
- unset($_theme_obj); // Housekeeping.
+ unset($_theme_obj); // Housekeeping.
- if ($upgrading_active_theme || $upgrading_active_parent_theme) {
- $counter += $self->autoClearCache();
- }
- break; // Break switch.
+ if ($upgrading_active_theme || $upgrading_active_parent_theme) {
+ $counter += $this->autoClearCache();
+ }
+ break; // Break switch.
- case 'core': // Core upgrade.
- default: // Or any other sort of upgrade.
+ case 'core': // Core upgrade.
+ default: // Or any other sort of upgrade.
- $counter += $self->autoClearCache();
+ $counter += $this->autoClearCache();
- break; // Break switch.
+ break; // Break switch.
+ }
}
-};
+}
diff --git a/src/includes/traits/Plugin/WcpUrlUtils.php b/src/includes/traits/Plugin/WcpUrlUtils.php
index 34e6fe44..b885b6f6 100644
--- a/src/includes/traits/Plugin/WcpUrlUtils.php
+++ b/src/includes/traits/Plugin/WcpUrlUtils.php
@@ -2,46 +2,52 @@
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Traits\Plugin;
-/*
-* Automatically clears cache files for a list of custom URLs.
-*
-* @since 151114 Adding support for a custom list of URLs.
-*
-* @throws \Exception If a clear failure occurs.
-*
-* @return int Total files cleared by this routine (if any).
-*
-* @note Unlike many of the other `auto_` methods, this one is NOT currently
-* attached to any hooks. However, it is called upon by other routines attached to hooks.
-*/
-$self->autoClearUrlsCache = function () use ($self) {
- $counter = 0; // Initialize.
+trait WcpUtlUtils {
+ /*
+ * Automatically clears cache files for a list of custom URLs.
+ *
+ * @since 151114 Adding support for a custom list of URLs.
+ *
+ * @throws \Exception If a clear failure occurs.
+ *
+ * @return int Total files cleared by this routine (if any).
+ *
+ * @note Unlike many of the other `auto_` methods, this one is NOT currently
+ * attached to any hooks. However, it is called upon by other routines attached to hooks.
+ */
+ public function autoClearUrlsCache()
+ {
+ $counter = 0; // Initialize.
- if (!is_null($done = &$self->cacheKey('autoClearUrlsCache'))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
+ if (!is_null($done = &$this->cacheKey('autoClearUrlsCache'))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if (!$self->options['cache_clear_urls']) {
- return $counter; // Nothing to do.
- }
- if (!is_dir($cache_dir = $self->cacheDir())) {
- return $counter; // Nothing to do.
- }
- foreach (preg_split('/['."\r\n".']+/', $self->options['cache_clear_urls'], -1, PREG_SPLIT_NO_EMPTY) as $_url) {
- if (stripos($_url, 'http') === 0) {
- $_regex = $self->buildCachePathRegexFromWcUrl($_url);
- $counter += $self->deleteFilesFromCacheDir($_regex);
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
}
- } unset($_url, $_regex); // Housekeeping.
+ if (!$this->options['cache_clear_urls']) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_dir($cache_dir = $this->cacheDir())) {
+ return $counter; // Nothing to do.
+ }
+ foreach (preg_split('/['."\r\n".']+/', $this->options['cache_clear_urls'], -1, PREG_SPLIT_NO_EMPTY) as $_url) {
+ if (stripos($_url, 'http') === 0) {
+ $_regex = $this->buildCachePathRegexFromWcUrl($_url);
+ $counter += $this->deleteFilesFromCacheDir($_regex);
+ }
+ }
+ unset($_url, $_regex); // Housekeeping.
- if ($counter && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected changes. Found %2$s in the cache matching a custom list of URLs; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($counter))));
+ if ($counter && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected changes. Found %2$s in the cache matching a custom list of URLs; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($counter)))
+ );
+ }
+ return $counter;
}
- return $counter;
-};
+}
/*[/pro]*/
diff --git a/src/includes/traits/Plugin/WcpUserUtils.php b/src/includes/traits/Plugin/WcpUserUtils.php
index 356f42ce..d11e69ce 100644
--- a/src/includes/traits/Plugin/WcpUserUtils.php
+++ b/src/includes/traits/Plugin/WcpUserUtils.php
@@ -2,121 +2,131 @@
/*[pro strip-from="lite"]*/
namespace WebSharks\CometCache\Pro\Traits\Plugin;
-/*
- * Clears cache files associated with a particular user.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `profile_update` hook.
- * @attaches-to `add_user_metadata` filter.
- * @attaches-to `updated_user_meta` hook.
- * @attaches-to `delete_user_metadata` filter.
- * @attaches-to `set_auth_cookie` hook.
- * @attaches-to `clear_auth_cookie` hook.
- *
- * @param int $user_id A WordPress user ID.
- *
- * @return int Total files cleared.
- */
-$self->autoClearUserCache = function ($user_id) use ($self) {
- $counter = 0; // Initialize.
+trait WcpUserUtils {
+ /*
+ * Clears cache files associated with a particular user.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `profile_update` hook.
+ * @attaches-to `add_user_metadata` filter.
+ * @attaches-to `updated_user_meta` hook.
+ * @attaches-to `delete_user_metadata` filter.
+ * @attaches-to `set_auth_cookie` hook.
+ * @attaches-to `clear_auth_cookie` hook.
+ *
+ * @param int $user_id A WordPress user ID.
+ *
+ * @return int Total files cleared.
+ */
+ public function autoClearUserCache($user_id)
+ {
+ $counter = 0; // Initialize.
- if (!($user_id = (integer) $user_id)) {
- return $counter; // Nothing to do.
- }
- if (!is_null($done = &$self->cacheKey('autoClearUserCache', $user_id))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
+ if (!($user_id = (integer) $user_id)) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_null($done = &$this->cacheKey('autoClearUserCache', $user_id))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if ($self->options['when_logged_in'] !== 'postload') {
- return $counter; // Nothing to do.
- }
- $regex = $self->assembleCachePathRegex('', '.*?\.u\/'.preg_quote($user_id, '/').'[.\/]');
- $counter += $self->wipeFilesFromCacheDir($regex); // Clear matching files.
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if ($this->options['when_logged_in'] !== 'postload') {
+ return $counter; // Nothing to do.
+ }
+ $regex = $this->assembleCachePathRegex('', '.*?\.u\/'.preg_quote($user_id, '/').'[.\/]');
+ $counter += $this->wipeFilesFromCacheDir($regex); // Clear matching files.
- if ($counter && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected changes. Found %2$s in the cache for user ID: %3$s
; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($counter)), esc_html($user_id)));
+ if ($counter && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected changes. Found %2$s in the cache for user ID: %3$s
; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($counter)), esc_html($user_id))
+ );
+ }
+ return $counter;
}
- return $counter;
-};
-$self->auto_clear_user_cache = $self->autoClearUserCache; // Back compat.
+$this->auto_clear_user_cache = $this->autoClearUserCache; // Back compat.
-/*
- * Automatically clears cache files associated with a particular user.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `profile_update` hook.
- *
- * @param int $user_id A WordPress user ID.
- */
-$self->autoClearUserCacheA1 = function ($user_id) use ($self) {
- $self->autoClearUserCache($user_id);
-};
+ /*
+ * Automatically clears cache files associated with a particular user.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `profile_update` hook.
+ *
+ * @param int $user_id A WordPress user ID.
+ */
+ public function autoClearUserCacheA1($user_id)
+ {
+ $this->autoClearUserCache($user_id);
+ }
-/*
-* Automatically clears cache files associated with a particular user.
-*
-* @since 151220 Using `updated_user_meta` instead of `update_user_metadata`
-*
-* @attaches-to `updated_user_meta` hook.
-*
-* @param int $meta_id ID of updated metadata entry.
-* @param int $object_id Object ID.
-*/
-$self->autoClearUserCacheA2 = function ($meta_id, $object_id) use ($self) {
- $self->autoClearUserCache($object_id);
-};
+ /*
+ * Automatically clears cache files associated with a particular user.
+ *
+ * @since 151220 Using `updated_user_meta` instead of `update_user_metadata`
+ *
+ * @attaches-to `updated_user_meta` hook.
+ *
+ * @param int $meta_id ID of updated metadata entry.
+ * @param int $object_id Object ID.
+ */
+ public function autoClearUserCacheA2($meta_id, $object_id)
+ {
+ $this->autoClearUserCache($object_id);
+ }
-/*
- * Automatically clears cache files associated with a particular user.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `add_user_metadata` filter.
- * @attaches-to `updated_user_meta` hook.
- * @attaches-to `delete_user_metadata` filter.
- *
- * @param mixed $value Filter value (passes through).
- * @param int $user_id A WordPress user ID.
- *
- * @return mixed The same `$value` (passes through).
- */
-$self->autoClearUserCacheFA2 = function ($value, $user_id) use ($self) {
- $self->autoClearUserCache($user_id);
- return $value; // Filter.
-};
+ /*
+ * Automatically clears cache files associated with a particular user.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `add_user_metadata` filter.
+ * @attaches-to `updated_user_meta` hook.
+ * @attaches-to `delete_user_metadata` filter.
+ *
+ * @param mixed $value Filter value (passes through).
+ * @param int $user_id A WordPress user ID.
+ *
+ * @return mixed The same `$value` (passes through).
+ */
+ public function autoClearUserCacheFA2($value, $user_id)
+ {
+ $this->autoClearUserCache($user_id);
+ return $value; // Filter.
+ }
-/*
- * Automatically clears cache files associated with a particular user.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `set_auth_cookie` hook.
- *
- * @param mixed $_ Irrelevant hook argument value.
- * @param mixed $__ Irrelevant hook argument value.
- * @param mixed $___ Irrelevant hook argument value.
- * @param int $user_id A WordPress user ID.
- */
-$self->autoClearUserCacheA4 = function ($_, $__, $___, $user_id) use ($self) {
- $self->autoClearUserCache($user_id);
-};
+ /*
+ * Automatically clears cache files associated with a particular user.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `set_auth_cookie` hook.
+ *
+ * @param mixed $_ Irrelevant hook argument value.
+ * @param mixed $__ Irrelevant hook argument value.
+ * @param mixed $___ Irrelevant hook argument value.
+ * @param int $user_id A WordPress user ID.
+ */
+ public function autoClearUserCacheA4($_, $__, $___, $user_id)
+ {
+ $this->autoClearUserCache($user_id);
+ }
-/*
- * Automatically clears cache files associated with current user.
- *
- * @since 150422 Rewrite.
- *
- * @attaches-to `clear_auth_cookie` hook.
- */
-$self->autoClearUserCacheCur = function () use ($self) {
- $self->autoClearUserCache(get_current_user_id());
-};
-$self->auto_clear_user_cache_cur = $self->autoClearUserCacheCur; // Back compat.
+ /*
+ * Automatically clears cache files associated with current user.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @attaches-to `clear_auth_cookie` hook.
+ */
+ public function autoClearUserCacheCur()
+ {
+ $this->autoClearUserCache(get_current_user_id());
+ }
+$this->auto_clear_user_cache_cur = $this->autoClearUserCacheCur; // Back compat.
+}
/*[/pro]*/
diff --git a/src/includes/traits/Plugin/WcpUtils.php b/src/includes/traits/Plugin/WcpUtils.php
index 035098fc..76e0dc06 100644
--- a/src/includes/traits/Plugin/WcpUtils.php
+++ b/src/includes/traits/Plugin/WcpUtils.php
@@ -1,377 +1,404 @@
wipeCache = function ($manually = false) use ($self) {
- $counter = 0; // Initialize.
-
- if (!$manually && $self->disableAutoWipeCacheRoutines()) {
- return $counter; // Nothing to do.
- }
- @set_time_limit(1800); // @TODO Display a warning.
-
- if (is_dir($cache_dir = $self->cacheDir())) {
- $regex = $self->assembleCachePathRegex('', '.+');
- $counter += $self->wipeFilesFromCacheDir($regex);
- }
- /*[pro strip-from="lite"]*/
- $counter += $self->wipeHtmlCCache($manually);
- /*[/pro]*/
-
- /*[pro strip-from="lite"]*/
- if (!$manually) {
- $self->wipeS2CleanCache();
- $self->wipeEvalCode();
- $self->wipeOpcache();
- }
- /*[/pro]*/
-
- /*[pro strip-from="lite"]*/
- if ($self->options['stats_enable']) {
- $dir_stats = DirStats::instance();
- $dir_stats->wipeCache();
- }
- /*[/pro]*/
- return $counter;
-};
-$self->wipe_cache = $self->wipeCache; // Back compat.
-
-/*
- * Clears cache files (current blog).
- *
- * @since 150422 Rewrite.
- *
- * @param bool $manually TRUE if clearing is done manually.
- *
- * @throws \Exception If a clearing failure occurs.
- *
- * @return int Total files cleared by this routine.
- */
-$self->clearCache = function ($manually = false) use ($self) {
- $counter = 0; // Initialize.
-
- if (!$manually && $self->disableAutoClearCacheRoutines()) {
- return $counter; // Nothing to do.
- }
- @set_time_limit(1800); // @TODO Display a warning.
-
- if (is_dir($cache_dir = $self->cacheDir())) {
- $regex = $self->buildHostCachePathRegex('', '.+');
- $counter += $self->clearFilesFromHostCacheDir($regex);
- }
- /*[pro strip-from="lite"]*/
- $counter += $self->clearHtmlCCache($manually);
- /*[/pro]*/
-
- /*[pro strip-from="lite"]*/
- if (!$manually) {
- $self->clearS2CleanCache();
- $self->clearEvalCode();
- $self->clearOpcache();
- }
- /*[/pro]*/
-
- /*[pro strip-from="lite"]*/
- if ($self->options['stats_enable']) {
- $dir_stats = DirStats::instance();
- $dir_stats->clearHostCache();
- }
- /*[/pro]*/
- return $counter;
-};
-$self->clear_cache = $self->clearCache; // Back compat.
-
-/*
- * Purges expired cache files (current blog).
- *
- * @since 150422 Rewrite.
- *
- * @param bool $manually TRUE if purging is done manually.
- *
- * @throws \Exception If a purge failure occurs.
- *
- * @return int Total files purged by this routine.
- */
-$self->purgeCache = function ($manually = false) use ($self) {
- $counter = 0; // Initialize.
-
- if (!$manually && $self->disableAutoPurgeCacheRoutines()) {
- return $counter; // Nothing to do.
- }
- @set_time_limit(1800); // @TODO Display a warning.
-
- if (is_dir($cache_dir = $self->cacheDir())) {
- $regex = $self->buildHostCachePathRegex('', '.+');
- $counter += $self->purgeFilesFromHostCacheDir($regex);
- }
- /*[pro strip-from="lite"]*/
- if ($self->options['stats_enable']) {
- $dir_stats = DirStats::instance();
- $dir_stats->clearHostCache();
- }
- /*[/pro]*/
- return $counter;
-};
-$self->purge_cache = $self->purgeCache; // Back compat.
-
-/*
- * Wurges (purges) all expired cache files; like wipe, but expired files only.
- *
- * @since 151002 Look at entire cache directory.
- *
- * @param bool $manually TRUE if wurging is done manually.
- *
- * @throws \Exception If a wurge failure occurs.
- *
- * @return int Total files wurged by this routine.
- */
-$self->wurgeCache = function ($manually = false) use ($self) {
- $counter = 0; // Initialize.
-
- if (!$manually && $self->disableAutoPurgeCacheRoutines()) {
- return $counter; // Nothing to do.
- }
- @set_time_limit(1800); // @TODO Display a warning.
-
- if (is_dir($cache_dir = $self->cacheDir())) {
- $regex = $self->assembleCachePathRegex('', '.+');
- $counter += $self->wurgeFilesFromCacheDir($regex);
- }
- /*[pro strip-from="lite"]*/
- if ($self->options['stats_enable']) {
- $dir_stats = DirStats::instance();
- $dir_stats->wipeCache();
- }
- /*[/pro]*/
- return $counter;
-};
-
-/*
- * Automatically wipes out all cache files.
- *
- * @attaches-to Nothing at this time.
- *
- * @since 150422 Rewrite.
- *
- * @return int Total files wiped by this routine (if any).
- *
- * @note Unlike many of the other `auto_` methods, this one is NOT currently attached to any hooks.
- * This is called upon whenever options are saved and/or restored though.
- */
-$self->autoWipeCache = function () use ($self) {
- $counter = 0; // Initialize.
-
- if (!is_null($done = &$self->cacheKey('autoWipeCache'))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
-
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if ($self->disableAutoWipeCacheRoutines()) {
- return $counter; // Nothing to do.
- }
- $counter += $self->wipeCache();
-
- if ($counter && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected significant changes. Found %2$s in the cache; auto-wiping.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($counter))));
- }
- return $counter;
-};
-
-/*
- * Automatically clears all cache files (current host).
- *
- * @attaches-to `switch_theme` hook.
- *
- * @attaches-to `wp_create_nav_menu` hook.
- * @attaches-to `wp_update_nav_menu` hook.
- * @attaches-to `wp_delete_nav_menu` hook.
- *
- * @attaches-to `create_term` hook.
- * @attaches-to `edit_terms` hook.
- * @attaches-to `delete_term` hook.
- *
- * @attaches-to `add_link` hook.
- * @attaches-to `edit_link` hook.
- * @attaches-to `delete_link` hook.
- *
- * @since 150422 Rewrite.
- *
- * @return int Total files cleared by this routine (if any).
- *
- * @note This is also called upon during plugin activation.
- */
-$self->autoClearCache = function () use ($self) {
- $counter = 0; // Initialize.
-
- if (!is_null($done = &$self->cacheKey('autoClearCache'))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
-
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if ($self->disableAutoClearCacheRoutines()) {
- return $counter; // Nothing to do.
- }
- $counter += $self->clearCache();
-
- if ($counter && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected important site changes. Found %2$s in the cache for this site; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($counter))));
- }
- return $counter;
-};
-
-/*
- * Automatically purges all cache files (current host).
- *
- * @attaches-to Nothing at this time.
- *
- * @since 151002 While working on directory stats.
- *
- * @return int Total files purged by this routine.
- *
- * @note Unlike many of the other `auto_` methods, this one is NOT currently attached to any hooks.
- */
-$self->autoPurgeCache = function () use ($self) {
- $counter = 0; // Initialize.
-
- if (!is_null($done = &$self->cacheKey('autoPurgeCache'))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
-
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if ($self->disableAutoPurgeCacheRoutines()) {
- return $counter; // Nothing to do.
- }
- $counter += $self->purgeCache();
-
- if ($counter && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected important site changes. Found %2$s in the cache for this site that were expired; auto-purging.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($counter))));
- }
- return $counter;
-};
-
-/*
- * Automatically wurges all cache files.
- *
- * @attaches-to Nothing at this time.
- *
- * @since 151002 While working on directory stats.
- *
- * @return int Total files wurged by this routine.
- *
- * @note Unlike many of the other `auto_` methods, this one is NOT currently attached to any hooks.
- */
-$self->autoWurgeCache = function () use ($self) {
- $counter = 0; // Initialize.
-
- if (!is_null($done = &$self->cacheKey('autoWurgeCache'))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
-
- if (!$self->options['enable']) {
- return $counter; // Nothing to do.
- }
- if ($self->disableAutoPurgeCacheRoutines()) {
- return $counter; // Nothing to do.
- }
- $counter += $self->wurgeCache();
-
- if ($counter && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueNotice(''.
- sprintf(__('%1$s: detected important site changes. Found %2$s in the cache that were expired; auto-purging.', SLUG_TD), esc_html(NAME), esc_html($self->i18nFiles($counter))));
- }
- return $counter;
-};
-
-/*
- * Allows a site owner to disable the automatic cache wiping routines.
- *
- * This is done by filtering `'.__GLOBAL_NS__.'_disable_auto_wipe_cache_routines` to return TRUE,
- * in which case this method returns TRUE, otherwise it returns FALSE.
- *
- * @since 150422 Rewrite.
- *
- * @return bool `TRUE` if disabled; and this also creates a dashboard notice in some cases.
- */
-$self->disableAutoWipeCacheRoutines = function () use ($self) {
- $is_disabled = (boolean) $self->applyWpFilters(GLOBAL_NS.'_disable_auto_wipe_cache_routines', false);
-
- if ($is_disabled && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueMainNotice(''.
- sprintf(__('%1$s: detected significant changes that would normally trigger cache wiping routines. However, cache wiping routines have been disabled by a site administrator. [?]', SLUG_TD), esc_html(NAME)));
- }
- return $is_disabled;
-};
-
-/*
- * Allows a site owner to disable the automatic cache clearing routines.
- *
- * This is done by filtering `'.__GLOBAL_NS__.'_disable_auto_clear_cache_routines` to return TRUE,
- * in which case this method returns TRUE, otherwise it returns FALSE.
- *
- * @since 150422 Rewrite.
- *
- * @return bool `TRUE` if disabled; and this also creates a dashboard notice in some cases.
- */
-$self->disableAutoClearCacheRoutines = function () use ($self) {
- $is_disabled = (boolean) $self->applyWpFilters(GLOBAL_NS.'_disable_auto_clear_cache_routines', false);
-
- if ($is_disabled && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueMainNotice(''.
- sprintf(__('%1$s: detected important site changes that would normally trigger cache clearing routines. However, cache clearing routines have been disabled by a site administrator. [?]', SLUG_TD), esc_html(NAME)));
- }
- return $is_disabled;
-};
-
-/*
- * Allows a site owner to disable the automatic cache purging routines.
- *
- * This is done by filtering `'.__GLOBAL_NS__.'_disable_auto_purge_cache_routines` to return TRUE,
- * in which case this method returns TRUE, otherwise it returns FALSE.
- *
- * @since 151002 While working on directory stats.
- *
- * @return bool `TRUE` if disabled; and this also creates a dashboard notice in some cases.
- */
-$self->disableAutoPurgeCacheRoutines = function () use ($self) {
- $is_disabled = (boolean) $self->applyWpFilters(GLOBAL_NS.'_disable_auto_purge_cache_routines', false);
-
- if ($is_disabled && is_admin() && (!IS_PRO || $self->options['change_notifications_enable'])) {
- $self->enqueueMainNotice(''.
- sprintf(__('%1$s: detected important site changes that would normally trigger cache purging routines. However, cache purging routines have been disabled by a site administrator. [?]', SLUG_TD), esc_html(NAME)));
- }
- return $is_disabled;
-};
+trait WcpUtils {
+ /*
+ * Used for temporarily storing the permalink for posts transitioning from
+ * `publish` or `private` post status to `pending` or `draft` post status.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @type array An associative array with the Post ID as the named key containing
+ * the post permalink before the post has been transitioned.
+ */
+ public $pre_post_update_post_permalink = [];
+
+ /*
+ * Wipes out all cache files.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param bool $manually TRUE if wiping is done manually.
+ *
+ * @throws \Exception If a wipe failure occurs.
+ *
+ * @return int Total files wiped by this routine.
+ */
+ public function wipeCache($manually = false)
+ {
+ $counter = 0; // Initialize.
+
+ if (!$manually && $this->disableAutoWipeCacheRoutines()) {
+ return $counter; // Nothing to do.
+ }
+ @set_time_limit(1800); // @TODO Display a warning.
+
+ if (is_dir($cache_dir = $this->cacheDir())) {
+ $regex = $this->assembleCachePathRegex('', '.+');
+ $counter += $this->wipeFilesFromCacheDir($regex);
+ }
+ /*[pro strip-from="lite"]*/
+ $counter += $this->wipeHtmlCCache($manually);
+ /*[/pro]*/
+
+ /*[pro strip-from="lite"]*/
+ if (!$manually) {
+ $this->wipeS2CleanCache();
+ $this->wipeEvalCode();
+ $this->wipeOpcache();
+ }
+ /*[/pro]*/
+
+ /*[pro strip-from="lite"]*/
+ if ($this->options['stats_enable']) {
+ $dir_stats = DirStats::instance();
+ $dir_stats->wipeCache();
+ }
+ /*[/pro]*/
+ return $counter;
+ }
+$this->wipe_cache = $this->wipeCache; // Back compat.
+
+ /*
+ * Clears cache files (current blog).
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param bool $manually TRUE if clearing is done manually.
+ *
+ * @throws \Exception If a clearing failure occurs.
+ *
+ * @return int Total files cleared by this routine.
+ */
+ public function clearCache($manually = false)
+ {
+ $counter = 0; // Initialize.
+
+ if (!$manually && $this->disableAutoClearCacheRoutines()) {
+ return $counter; // Nothing to do.
+ }
+ @set_time_limit(1800); // @TODO Display a warning.
+
+ if (is_dir($cache_dir = $this->cacheDir())) {
+ $regex = $this->buildHostCachePathRegex('', '.+');
+ $counter += $this->clearFilesFromHostCacheDir($regex);
+ }
+ /*[pro strip-from="lite"]*/
+ $counter += $this->clearHtmlCCache($manually);
+ /*[/pro]*/
+
+ /*[pro strip-from="lite"]*/
+ if (!$manually) {
+ $this->clearS2CleanCache();
+ $this->clearEvalCode();
+ $this->clearOpcache();
+ }
+ /*[/pro]*/
+
+ /*[pro strip-from="lite"]*/
+ if ($this->options['stats_enable']) {
+ $dir_stats = DirStats::instance();
+ $dir_stats->clearHostCache();
+ }
+ /*[/pro]*/
+ return $counter;
+ }
+$this->clear_cache = $this->clearCache; // Back compat.
+
+ /*
+ * Purges expired cache files (current blog).
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param bool $manually TRUE if purging is done manually.
+ *
+ * @throws \Exception If a purge failure occurs.
+ *
+ * @return int Total files purged by this routine.
+ */
+ public function purgeCache($manually = false)
+ {
+ $counter = 0; // Initialize.
+
+ if (!$manually && $this->disableAutoPurgeCacheRoutines()) {
+ return $counter; // Nothing to do.
+ }
+ @set_time_limit(1800); // @TODO Display a warning.
+
+ if (is_dir($cache_dir = $this->cacheDir())) {
+ $regex = $this->buildHostCachePathRegex('', '.+');
+ $counter += $this->purgeFilesFromHostCacheDir($regex);
+ }
+ /*[pro strip-from="lite"]*/
+ if ($this->options['stats_enable']) {
+ $dir_stats = DirStats::instance();
+ $dir_stats->clearHostCache();
+ }
+ /*[/pro]*/
+ return $counter;
+ }
+$this->purge_cache = $this->purgeCache; // Back compat.
+
+ /*
+ * Wurges (purges) all expired cache files; like wipe, but expired files only.
+ *
+ * @since 151002 Look at entire cache directory.
+ *
+ * @param bool $manually TRUE if wurging is done manually.
+ *
+ * @throws \Exception If a wurge failure occurs.
+ *
+ * @return int Total files wurged by this routine.
+ */
+ public function wurgeCache($manually = false)
+ {
+ $counter = 0; // Initialize.
+
+ if (!$manually && $this->disableAutoPurgeCacheRoutines()) {
+ return $counter; // Nothing to do.
+ }
+ @set_time_limit(1800); // @TODO Display a warning.
+
+ if (is_dir($cache_dir = $this->cacheDir())) {
+ $regex = $this->assembleCachePathRegex('', '.+');
+ $counter += $this->wurgeFilesFromCacheDir($regex);
+ }
+ /*[pro strip-from="lite"]*/
+ if ($this->options['stats_enable']) {
+ $dir_stats = DirStats::instance();
+ $dir_stats->wipeCache();
+ }
+ /*[/pro]*/
+ return $counter;
+ }
+
+ /*
+ * Automatically wipes out all cache files.
+ *
+ * @attaches-to Nothing at this time.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return int Total files wiped by this routine (if any).
+ *
+ * @note Unlike many of the other `auto_` methods, this one is NOT currently attached to any hooks.
+ * This is called upon whenever options are saved and/or restored though.
+ */
+ public function autoWipeCache()
+ {
+ $counter = 0; // Initialize.
+
+ if (!is_null($done = &$this->cacheKey('autoWipeCache'))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
+
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if ($this->disableAutoWipeCacheRoutines()) {
+ return $counter; // Nothing to do.
+ }
+ $counter += $this->wipeCache();
+
+ if ($counter && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected significant changes. Found %2$s in the cache; auto-wiping.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($counter)))
+ );
+ }
+ return $counter;
+ }
+
+ /*
+ * Automatically clears all cache files (current host).
+ *
+ * @attaches-to `switch_theme` hook.
+ *
+ * @attaches-to `wp_create_nav_menu` hook.
+ * @attaches-to `wp_update_nav_menu` hook.
+ * @attaches-to `wp_delete_nav_menu` hook.
+ *
+ * @attaches-to `create_term` hook.
+ * @attaches-to `edit_terms` hook.
+ * @attaches-to `delete_term` hook.
+ *
+ * @attaches-to `add_link` hook.
+ * @attaches-to `edit_link` hook.
+ * @attaches-to `delete_link` hook.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return int Total files cleared by this routine (if any).
+ *
+ * @note This is also called upon during plugin activation.
+ */
+ public function autoClearCache()
+ {
+ $counter = 0; // Initialize.
+
+ if (!is_null($done = &$this->cacheKey('autoClearCache'))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
+
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if ($this->disableAutoClearCacheRoutines()) {
+ return $counter; // Nothing to do.
+ }
+ $counter += $this->clearCache();
+
+ if ($counter && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected important site changes. Found %2$s in the cache for this site; auto-clearing.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($counter)))
+ );
+ }
+ return $counter;
+ }
+
+ /*
+ * Automatically purges all cache files (current host).
+ *
+ * @attaches-to Nothing at this time.
+ *
+ * @since 151002 While working on directory stats.
+ *
+ * @return int Total files purged by this routine.
+ *
+ * @note Unlike many of the other `auto_` methods, this one is NOT currently attached to any hooks.
+ */
+ public function autoPurgeCache()
+ {
+ $counter = 0; // Initialize.
+
+ if (!is_null($done = &$this->cacheKey('autoPurgeCache'))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
+
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if ($this->disableAutoPurgeCacheRoutines()) {
+ return $counter; // Nothing to do.
+ }
+ $counter += $this->purgeCache();
+
+ if ($counter && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected important site changes. Found %2$s in the cache for this site that were expired; auto-purging.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($counter)))
+ );
+ }
+ return $counter;
+ }
+
+ /*
+ * Automatically wurges all cache files.
+ *
+ * @attaches-to Nothing at this time.
+ *
+ * @since 151002 While working on directory stats.
+ *
+ * @return int Total files wurged by this routine.
+ *
+ * @note Unlike many of the other `auto_` methods, this one is NOT currently attached to any hooks.
+ */
+ public function autoWurgeCache()
+ {
+ $counter = 0; // Initialize.
+
+ if (!is_null($done = &$this->cacheKey('autoWurgeCache'))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
+
+ if (!$this->options['enable']) {
+ return $counter; // Nothing to do.
+ }
+ if ($this->disableAutoPurgeCacheRoutines()) {
+ return $counter; // Nothing to do.
+ }
+ $counter += $this->wurgeCache();
+
+ if ($counter && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueNotice(
+ ''.
+ sprintf(__('%1$s: detected important site changes. Found %2$s in the cache that were expired; auto-purging.', SLUG_TD), esc_html(NAME), esc_html($this->i18nFiles($counter)))
+ );
+ }
+ return $counter;
+ }
+
+ /*
+ * Allows a site owner to disable the automatic cache wiping routines.
+ *
+ * This is done by filtering `'.__GLOBAL_NS__.'_disable_auto_wipe_cache_routines` to return TRUE,
+ * in which case this method returns TRUE, otherwise it returns FALSE.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return bool `TRUE` if disabled; and this also creates a dashboard notice in some cases.
+ */
+ public function disableAutoWipeCacheRoutines()
+ {
+ $is_disabled = (boolean) $this->applyWpFilters(GLOBAL_NS.'_disable_auto_wipe_cache_routines', false);
+
+ if ($is_disabled && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueMainNotice(
+ ''.
+ sprintf(__('%1$s: detected significant changes that would normally trigger cache wiping routines. However, cache wiping routines have been disabled by a site administrator. [?]', SLUG_TD), esc_html(NAME))
+ );
+ }
+ return $is_disabled;
+ }
+
+ /*
+ * Allows a site owner to disable the automatic cache clearing routines.
+ *
+ * This is done by filtering `'.__GLOBAL_NS__.'_disable_auto_clear_cache_routines` to return TRUE,
+ * in which case this method returns TRUE, otherwise it returns FALSE.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return bool `TRUE` if disabled; and this also creates a dashboard notice in some cases.
+ */
+ public function disableAutoClearCacheRoutines()
+ {
+ $is_disabled = (boolean) $this->applyWpFilters(GLOBAL_NS.'_disable_auto_clear_cache_routines', false);
+
+ if ($is_disabled && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueMainNotice(
+ ''.
+ sprintf(__('%1$s: detected important site changes that would normally trigger cache clearing routines. However, cache clearing routines have been disabled by a site administrator. [?]', SLUG_TD), esc_html(NAME))
+ );
+ }
+ return $is_disabled;
+ }
+
+ /*
+ * Allows a site owner to disable the automatic cache purging routines.
+ *
+ * This is done by filtering `'.__GLOBAL_NS__.'_disable_auto_purge_cache_routines` to return TRUE,
+ * in which case this method returns TRUE, otherwise it returns FALSE.
+ *
+ * @since 151002 While working on directory stats.
+ *
+ * @return bool `TRUE` if disabled; and this also creates a dashboard notice in some cases.
+ */
+ public function disableAutoPurgeCacheRoutines()
+ {
+ $is_disabled = (boolean) $this->applyWpFilters(GLOBAL_NS.'_disable_auto_purge_cache_routines', false);
+
+ if ($is_disabled && is_admin() && (!IS_PRO || $this->options['change_notifications_enable'])) {
+ $this->enqueueMainNotice(
+ ''.
+ sprintf(__('%1$s: detected important site changes that would normally trigger cache purging routines. However, cache purging routines have been disabled by a site administrator. [?]', SLUG_TD), esc_html(NAME))
+ );
+ }
+ return $is_disabled;
+ }
+}
diff --git a/src/includes/traits/Plugin/WcpWooCommerceUtils.php b/src/includes/traits/Plugin/WcpWooCommerceUtils.php
index 9e53609e..797e0536 100644
--- a/src/includes/traits/Plugin/WcpWooCommerceUtils.php
+++ b/src/includes/traits/Plugin/WcpWooCommerceUtils.php
@@ -1,24 +1,27 @@
autoClearPostCacheOnWooCommerceSetStock = function ($product) use ($self) {
- $counter = 0; // Initialize.
+trait WcpWooCommerceUtils {
+ /*
+ * Automatically clears cache file for a WooCommerce Product when its stock is changed.
+ *
+ * @since 151220 Improving WooCommerce Compatibility.
+ *
+ * @attaches-to `woocommerce_product_set_stock` hook.
+ *
+ * @param \WC_Product $product A WooCommerce WC_Product object
+ */
+ public function autoClearPostCacheOnWooCommerceSetStock($product)
+ {
+ $counter = 0; // Initialize.
- if (!is_null($done = &$self->cacheKey('autoClearPostCacheOnWooCommerceSetStock'))) {
- return $counter; // Already did this.
- }
- $done = true; // Flag as having been done.
+ if (!is_null($done = &$this->cacheKey('autoClearPostCacheOnWooCommerceSetStock'))) {
+ return $counter; // Already did this.
+ }
+ $done = true; // Flag as having been done.
- if(class_exists('\\WooCommerce')) {
- $counter += $self->autoClearPostCache($product->id);
+ if (class_exists('\\WooCommerce')) {
+ $counter += $this->autoClearPostCache($product->id);
+ }
}
-};
+}
diff --git a/src/includes/traits/Shared/BlogUtils.php b/src/includes/traits/Shared/BlogUtils.php
index 5e03bf6b..ee6fc576 100644
--- a/src/includes/traits/Shared/BlogUtils.php
+++ b/src/includes/traits/Shared/BlogUtils.php
@@ -1,31 +1,34 @@
blogDetails = function ($blog_id = 0) use ($self) {
- if (!is_multisite() || $self->isAdvancedCache()) {
- return null; // Not possible.
- }
- if (($blog_id = (integer) $blog_id) < 0) {
- $blog_id = (integer) get_current_site()->blog_id;
- }
- if (!$blog_id) {
- $blog_id = (integer) get_current_blog_id();
- }
- if (!$blog_id || $blog_id < 0) {
- return null; // Not possible.
- }
- $details = get_blog_details($blog_id);
+trait BlogUtils {
+ /*
+ * Get blog details.
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @param integer $blog_id For which blog ID?
+ *
+ * @return \stdClass|null Blog details if possible.
+ *
+ * @note The return value of this function is NOT cached in support of `switch_to_blog()`.
+ */
+ public function blogDetails($blog_id = 0)
+ {
+ if (!is_multisite() || $this->isAdvancedCache()) {
+ return null; // Not possible.
+ }
+ if (($blog_id = (integer) $blog_id) < 0) {
+ $blog_id = (integer) get_current_site()->blog_id;
+ }
+ if (!$blog_id) {
+ $blog_id = (integer) get_current_blog_id();
+ }
+ if (!$blog_id || $blog_id < 0) {
+ return null; // Not possible.
+ }
+ $details = get_blog_details($blog_id);
- return is_object($details) ? $details : null;
-};
+ return is_object($details) ? $details : null;
+ }
+}
diff --git a/src/includes/traits/Shared/CacheDirUtils.php b/src/includes/traits/Shared/CacheDirUtils.php
index 0e9bcc81..fe9e4d26 100644
--- a/src/includes/traits/Shared/CacheDirUtils.php
+++ b/src/includes/traits/Shared/CacheDirUtils.php
@@ -1,326 +1,165 @@
cacheDir = function ($rel_path = '') use ($self) {
- $rel_path = (string) $rel_path;
-
- if ($self->isAdvancedCache()) {
- $cache_dir = defined('COMET_CACHE_DIR') ? COMET_CACHE_DIR : '';
- } elseif (!empty($self->cache_sub_dir)) {
- $cache_dir = $self->wpContentBaseDirTo($self->cache_sub_dir);
- }
- if (empty($cache_dir)) {
- throw new \Exception(__('Unable to determine cache directory location.', SLUG_TD));
- }
- return rtrim($cache_dir, '/').($rel_path ? '/'.ltrim($rel_path) : '');
-};
-
-/*
- * Wipe files from the cache directory (for all hosts/blogs);
- * i.e., those that match a specific regex pattern.
- *
- * @since 151002 While working on directory stats.
- *
- * @param string $regex A regex pattern; see {@link deleteFilesFromCacheDir()}.
- *
- * @return integer Total files wiped by this routine.
- */
-$self->wipeFilesFromCacheDir = function ($regex) use ($self) {
- return $self->deleteFilesFromCacheDir($regex);
-};
-
-/*
- * Clear files from the cache directory (for the current host);
- * i.e., those that match a specific regex pattern.
- *
- * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
- *
- * @param string $regex A regex pattern; see {@link deleteFilesFromHostCacheDir()}.
- *
- * @return integer Total files cleared by this routine (if any).
- */
-$self->clearFilesFromHostCacheDir = function ($regex) use ($self) {
- return $self->deleteFilesFromHostCacheDir($regex);
-};
-
-/*
- * Wurge (purge) files from the cache directory (for all hosts/blogs);
- * i.e., those that match a specific regex pattern.
- *
- * @since 151002 While working on directory stats.
- *
- * @param string $regex A regex pattern; see {@link deleteFilesFromCacheDir()}.
- *
- * @return integer Total files wurged by this routine.
- */
-$self->wurgeFilesFromCacheDir = function ($regex) use ($self) {
- return $self->deleteFilesFromCacheDir($regex, true);
-};
-
-/*
- * Purge files from the cache directory (for the current host);
- * i.e., those that match a specific regex pattern.
- *
- * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
- *
- * @param string $regex A regex pattern; see {@link deleteFilesFromHostCacheDir()}.
- *
- * @return integer Total files purged by this routine (if any).
- */
-$self->purgeFilesFromHostCacheDir = function ($regex) use ($self) {
- return $self->deleteFilesFromHostCacheDir($regex, true);
-};
-
-/*
- * Delete files from the cache directory (for all hosts/blogs);
- * i.e., those that match a specific regex pattern.
- *
- * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
- *
- * @param string $regex A `/[regex pattern]/`; relative to the cache directory.
- * e.g. `/^http\/example\.com\/my\-slug(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])/`
- *
- * Or, this can also be a full/absolute regex pattern against an absolute path;
- * provided that it always starts with `/^`; including the full absolute cache/host directory path.
- * e.g. `/^\/cache\/dir\/http\/example\.com\/my\-slug(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])/`
- *
- * @param boolean $check_max_age Check max age? i.e., use purge behavior?
- *
- * @return integer Total files deleted by this routine (if any).
- *
- * @throws \Exception If unable to delete a file for any reason.
- *
- * @TODO Optimize this for multisite networks w/ a LOT of child blogs.
- * @TODO Optimize this for extremely large sites. A LOT of files here could slow things down.
- * This class member is currently used in wiping and purging for a network. So there is the potential for a LOT of files in a single scan.
- * See also:
- */
-$self->deleteFilesFromCacheDir = function ($regex, $check_max_age = false) use ($self) {
- $counter = 0; // Initialize.
-
- if (!($regex = (string) $regex)) {
- return $counter; // Nothing to do.
- }
- if (!is_dir($cache_dir = $self->cacheDir())) {
- return $counter; // Nothing to do.
+trait CacheDirUtils {
+ /*
+ * Cache directory path.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $rel_path Relative path inside cache directory.
+ *
+ * @throws \Exception If unable to get cache directory.
+ *
+ * @return string Absolute path to cache directory.
+ */
+ public function cacheDir($rel_path = '')
+ {
+ $rel_path = (string) $rel_path;
+
+ if ($this->isAdvancedCache()) {
+ $cache_dir = defined('COMET_CACHE_DIR') ? COMET_CACHE_DIR : '';
+ } elseif (!empty($this->cache_sub_dir)) {
+ $cache_dir = $this->wpContentBaseDirTo($this->cache_sub_dir);
+ }
+ if (empty($cache_dir)) {
+ throw new \Exception(__('Unable to determine cache directory location.', SLUG_TD));
+ }
+ return rtrim($cache_dir, '/').($rel_path ? '/'.ltrim($rel_path) : '');
}
- $cache_dir = $self->nDirSeps($cache_dir);
- if ($check_max_age && $self->isAdvancedCache()) {
- throw new \Exception(__('Invalid argument; isAdvancedCache!', SLUG_TD));
- }
- if ($check_max_age && !($max_age = strtotime('-'.$self->options['cache_max_age']))) {
- return $counter; // Invalid cache expiration time.
+ /*
+ * Wipe files from the cache directory (for all hosts/blogs);
+ * i.e., those that match a specific regex pattern.
+ *
+ * @since 151002 While working on directory stats.
+ *
+ * @param string $regex A regex pattern; see {@link deleteFilesFromCacheDir()}.
+ *
+ * @return integer Total files wiped by this routine.
+ */
+ public function wipeFilesFromCacheDir($regex)
+ {
+ return $this->deleteFilesFromCacheDir($regex);
}
- /* ------- Begin lock state... ----------- */
- $cache_lock = $self->cacheLock(); // Lock cache writes.
-
- clearstatcache(); // Clear stat cache to be sure we have a fresh start below.
-
- $cache_dir_tmp = $self->addTmpSuffix($cache_dir); // Temporary directory.
-
- $cache_dir_tmp_regex = $regex; // Initialize host-specific regex pattern for the tmp directory.
- $cache_dir_tmp_regex = '\\/'.ltrim($cache_dir_tmp_regex, '^\\/'); // Make sure it begins with an escaped `/`.
- $cache_dir_tmp_regex = $self->strIreplaceOnce(preg_quote($cache_dir.'/', '/'), '', $cache_dir_tmp_regex);
-
- $cache_dir_tmp_regex = ltrim($cache_dir_tmp_regex, '^\\/');
- if (strpos($cache_dir_tmp_regex, '(?:\/') === 0 || strpos($cache_dir_tmp_regex, '(\/') === 0) {
- $cache_dir_tmp_regex = '/^'.preg_quote($cache_dir_tmp, '/').$cache_dir_tmp_regex;
- } else {
- $cache_dir_tmp_regex = '/^'.preg_quote($cache_dir_tmp.'/', '/').$cache_dir_tmp_regex;
+ /*
+ * Clear files from the cache directory (for the current host);
+ * i.e., those that match a specific regex pattern.
+ *
+ * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
+ *
+ * @param string $regex A regex pattern; see {@link deleteFilesFromHostCacheDir()}.
+ *
+ * @return integer Total files cleared by this routine (if any).
+ */
+ public function clearFilesFromHostCacheDir($regex)
+ {
+ return $this->deleteFilesFromHostCacheDir($regex);
}
- # if(WP_DEBUG) file_put_contents(WP_CONTENT_DIR.'/'.strtolower(SHORT_NAME).'-debug.log', print_r($regex, TRUE)."\n".print_r($cache_dir_tmp_regex, TRUE)."\n\n", FILE_APPEND);
- // Uncomment the above line to debug regex pattern matching used by this routine; and others that call upon it.
-
- if (!rename($cache_dir, $cache_dir_tmp)) {
- throw new \Exception(sprintf(__('Unable to delete files. Rename failure on directory: `%1$s`.', SLUG_TD), $cache_dir));
- }
- foreach (($_dir_regex_iteration = $self->dirRegexIteration($cache_dir_tmp, $cache_dir_tmp_regex)) as $_resource) {
- $_resource_type = $_resource->getType();
- $_sub_path_name = $_resource->getSubpathname();
- $_path_name = $_resource->getPathname();
-
- if ($_resource_type !== 'dir' && strpos($_sub_path_name, '/') === false) {
- continue; // Don't delete links/files in the immediate directory; e.g. `[SHORT_NAME]-advanced-cache` or `.htaccess`, etc.
- // Actual `http|https/...` cache links/files are nested. Links/files in the immediate directory are for other purposes.
- }
- switch ($_resource_type) {// Based on type; i.e., `link`, `file`, `dir`.
-
- case 'link': // Symbolic links; i.e., 404 errors.
-
- if ($check_max_age && !empty($max_age) && is_file($_resource->getLinkTarget())) {
- if (($_lstat = lstat($_path_name)) && !empty($_lstat['mtime'])) {
- if ($_lstat['mtime'] >= $max_age) {
- break; // Break switch.
- }
- }
- }
- if (!unlink($_path_name)) {
- $self->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
- throw new \Exception(sprintf(__('Unable to delete symlink: `%1$s`.', SLUG_TD), $_path_name));
- }
- ++$counter; // Increment counter for each link we delete.
-
- break; // Break switch handler.
- case 'file': // Regular files; i.e., not symlinks.
-
- if ($check_max_age && !empty($max_age)) {
- if ($_resource->getMTime() >= $max_age) {
- break; // Break switch.
- }
- }
- if (!unlink($_path_name)) {
- $self->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
- throw new \Exception(sprintf(__('Unable to delete file: `%1$s`.', SLUG_TD), $_path_name));
- }
- ++$counter; // Increment counter for each file we delete.
-
- break; // Break switch handler.
-
- case 'dir': // A regular directory; i.e., not a symlink.
-
- if ($regex !== '/^.+/i') {
- break; // Not deleting everything.
- }
- if ($check_max_age && !empty($max_age)) {
- break; // Not deleting everything.
- }
- if (!rmdir($_path_name)) {
- $self->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
- throw new \Exception(sprintf(__('Unable to delete dir: `%1$s`.', SLUG_TD), $_path_name));
- }
- # $counter++; // Increment counter for each directory we delete. ~ NO don't do that here.
-
- break; // Break switch handler.
-
- default: // Something else that is totally unexpected here.
- $self->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
- throw new \Exception(sprintf(__('Unexpected resource type: `%1$s`.', SLUG_TD), $_resource_type));
- }
+ /*
+ * Wurge (purge) files from the cache directory (for all hosts/blogs);
+ * i.e., those that match a specific regex pattern.
+ *
+ * @since 151002 While working on directory stats.
+ *
+ * @param string $regex A regex pattern; see {@link deleteFilesFromCacheDir()}.
+ *
+ * @return integer Total files wurged by this routine.
+ */
+ public function wurgeFilesFromCacheDir($regex)
+ {
+ return $this->deleteFilesFromCacheDir($regex, true);
}
- unset($_dir_regex_iteration, $_resource, $_resource_type, $_sub_path_name, $_path_name, $_lstat); // Housekeeping.
- if (!rename($cache_dir_tmp, $cache_dir)) {
- $self->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
- throw new \Exception(sprintf(__('Unable to delete files. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $cache_dir_tmp));
- }
- /* ------- End lock state... ------------- */
-
- $self->cacheUnlock($cache_lock); // Release.
-
- return $counter;
-};
-
-/*
- * Delete files from the cache directory (for the current host);
- * i.e., those that match a specific regex pattern.
- *
- * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
- *
- * @param string $regex A `/[regex pattern]/`; relative to the host cache directory.
- * e.g. `/^my\-slug(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])/`
- *
- * Or, this can also be a full/absolute regex pattern against an absolute path;
- * provided that it always starts with `/^`; including the full absolute cache/host directory path.
- * e.g. `/^\/cache\/dir\/http\/example\.com\/my\-slug(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])/`
- *
- * @param boolean $check_max_age Check max age? i.e., use purge behavior?
- *
- * @param boolean $___considering_domain_mapping For internal use only.
- * @param boolean $___consider_domain_mapping_host_token For internal use only.
- * @param boolean $___consider_domain_mapping_host_base_dir_tokens For internal use only.
- *
- * @return integer Total files deleted by this routine (if any).
- *
- * @throws \Exception If unable to delete a file for any reason.
- */
-$self->deleteFilesFromHostCacheDir = function (
- $regex,
- $check_max_age = false,
- $___considering_domain_mapping = false,
- $___consider_domain_mapping_host_token = null,
- $___consider_domain_mapping_host_base_dir_tokens = null
-) use ($self) {
- $counter = 0; // Initialize.
-
- if (!($regex = (string) $regex)) {
- return $counter; // Nothing to do.
+ /*
+ * Purge files from the cache directory (for the current host);
+ * i.e., those that match a specific regex pattern.
+ *
+ * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
+ *
+ * @param string $regex A regex pattern; see {@link deleteFilesFromHostCacheDir()}.
+ *
+ * @return integer Total files purged by this routine (if any).
+ */
+ public function purgeFilesFromHostCacheDir($regex)
+ {
+ return $this->deleteFilesFromHostCacheDir($regex, true);
}
- if (!is_dir($cache_dir = $self->cacheDir())) {
- return $counter; // Nothing to do.
- }
- $cache_dir = $self->nDirSeps($cache_dir); // Normalize.
- $host_token = $current_host_token = $self->hostToken();
- $host_base_dir_tokens = $current_host_base_dir_tokens = $self->hostBaseDirTokens();
- if ($___considering_domain_mapping && isset($___consider_domain_mapping_host_token, $___consider_domain_mapping_host_base_dir_tokens)) {
- $host_token = (string) $___consider_domain_mapping_host_token;
- $host_base_dir_tokens = (string) $___consider_domain_mapping_host_base_dir_tokens;
- }
- if (!$host_token) { // Must have a host in the sub-routine below.
- throw new \Exception(__('Invalid argument; host token empty!', SLUG_TD));
- }
- if ($check_max_age && $self->isAdvancedCache()) {
- throw new \Exception(__('Invalid argument; isAdvancedCache!', SLUG_TD));
- }
- if ($check_max_age && !($max_age = strtotime('-'.$self->options['cache_max_age']))) {
- return $counter; // Invalid cache expiration time.
- }
- /* ------- Begin lock state... ----------- */
+ /*
+ * Delete files from the cache directory (for all hosts/blogs);
+ * i.e., those that match a specific regex pattern.
+ *
+ * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
+ *
+ * @param string $regex A `/[regex pattern]/`; relative to the cache directory.
+ * e.g. `/^http\/example\.com\/my\-slug(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])/`
+ *
+ * Or, this can also be a full/absolute regex pattern against an absolute path;
+ * provided that it always starts with `/^`; including the full absolute cache/host directory path.
+ * e.g. `/^\/cache\/dir\/http\/example\.com\/my\-slug(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])/`
+ *
+ * @param boolean $check_max_age Check max age? i.e., use purge behavior?
+ *
+ * @return integer Total files deleted by this routine (if any).
+ *
+ * @throws \Exception If unable to delete a file for any reason.
+ *
+ * @TODO Optimize this for multisite networks w/ a LOT of child blogs.
+ * @TODO Optimize this for extremely large sites. A LOT of files here could slow things down.
+ * This class member is currently used in wiping and purging for a network. So there is the potential for a LOT of files in a single scan.
+ * See also:
+ */
+ public function deleteFilesFromCacheDir($regex, $check_max_age = false)
+ {
+ $counter = 0; // Initialize.
+
+ if (!($regex = (string) $regex)) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_dir($cache_dir = $this->cacheDir())) {
+ return $counter; // Nothing to do.
+ }
+ $cache_dir = $this->nDirSeps($cache_dir);
- $cache_lock = $self->cacheLock(); // Lock cache writes.
+ if ($check_max_age && $this->isAdvancedCache()) {
+ throw new \Exception(__('Invalid argument; isAdvancedCache!', SLUG_TD));
+ }
+ if ($check_max_age && !($max_age = strtotime('-'.$this->options['cache_max_age']))) {
+ return $counter; // Invalid cache expiration time.
+ }
+ /* ------- Begin lock state... ----------- */
- clearstatcache(); // Clear stat cache to be sure we have a fresh start below.
+ $cache_lock = $this->cacheLock(); // Lock cache writes.
- foreach (array('http', 'https') as $_host_scheme) {
- $_host_url = $_host_scheme.'://'.$host_token.$host_base_dir_tokens;
- $_host_cache_path_flags = CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
- $_host_cache_path = $self->buildCachePath($_host_url, '', '', $_host_cache_path_flags);
- $_host_cache_dir = $self->nDirSeps($cache_dir.'/'.$_host_cache_path); // Normalize.
+ clearstatcache(); // Clear stat cache to be sure we have a fresh start below.
- if (!$_host_cache_dir || !is_dir($_host_cache_dir)) {
- // On a multisite install this may have a cache sub-directory.
- // e.g., `http/example-com[[-base]-child1][[/base]/child1]` instead of `http/example-com`.
- continue; // Nothing to do.
- }
- $_host_cache_dir_tmp = $self->addTmpSuffix($_host_cache_dir); // Temporary directory.
+ $cache_dir_tmp = $this->addTmpSuffix($cache_dir); // Temporary directory.
- $_host_cache_dir_tmp_regex = $regex; // Initialize host-specific regex pattern for the tmp directory.
- $_host_cache_dir_tmp_regex = '\\/'.ltrim($_host_cache_dir_tmp_regex, '^\\/'); // Make sure it begins with an escaped `/`.
- $_host_cache_dir_tmp_regex = $self->strIreplaceOnce(preg_quote($_host_cache_path.'/', '/'), '', $_host_cache_dir_tmp_regex);
- $_host_cache_dir_tmp_regex = $self->strIreplaceOnce(preg_quote($_host_cache_dir.'/', '/'), '', $_host_cache_dir_tmp_regex);
+ $cache_dir_tmp_regex = $regex; // Initialize host-specific regex pattern for the tmp directory.
+ $cache_dir_tmp_regex = '\\/'.ltrim($cache_dir_tmp_regex, '^\\/'); // Make sure it begins with an escaped `/`.
+ $cache_dir_tmp_regex = $this->strIreplaceOnce(preg_quote($cache_dir.'/', '/'), '', $cache_dir_tmp_regex);
- $_host_cache_dir_tmp_regex = ltrim($_host_cache_dir_tmp_regex, '^\\/');
- if (strpos($_host_cache_dir_tmp_regex, '(?:\/') === 0 || strpos($_host_cache_dir_tmp_regex, '(\/') === 0) {
- $_host_cache_dir_tmp_regex = '/^'.preg_quote($_host_cache_dir_tmp, '/').$_host_cache_dir_tmp_regex;
+ $cache_dir_tmp_regex = ltrim($cache_dir_tmp_regex, '^\\/');
+ if (strpos($cache_dir_tmp_regex, '(?:\/') === 0 || strpos($cache_dir_tmp_regex, '(\/') === 0) {
+ $cache_dir_tmp_regex = '/^'.preg_quote($cache_dir_tmp, '/').$cache_dir_tmp_regex;
} else {
- $_host_cache_dir_tmp_regex = '/^'.preg_quote($_host_cache_dir_tmp.'/', '/').$_host_cache_dir_tmp_regex;
+ $cache_dir_tmp_regex = '/^'.preg_quote($cache_dir_tmp.'/', '/').$cache_dir_tmp_regex;
}
- #if(WP_DEBUG) file_put_contents(WP_CONTENT_DIR.'/'.strtolower(SHORT_NAME).'-debug.log', print_r($regex, TRUE)."\n".print_r($_host_cache_dir_tmp_regex, TRUE)."\n\n", FILE_APPEND);
+ # if(WP_DEBUG) file_put_contents(WP_CONTENT_DIR.'/'.strtolower(SHORT_NAME).'-debug.log', print_r($regex, TRUE)."\n".print_r($cache_dir_tmp_regex, TRUE)."\n\n", FILE_APPEND);
// Uncomment the above line to debug regex pattern matching used by this routine; and others that call upon it.
- if (!rename($_host_cache_dir, $_host_cache_dir_tmp)) {
- throw new \Exception(sprintf(__('Unable to delete files. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $_host_cache_dir));
+ if (!rename($cache_dir, $cache_dir_tmp)) {
+ throw new \Exception(sprintf(__('Unable to delete files. Rename failure on directory: `%1$s`.', SLUG_TD), $cache_dir));
}
- foreach (($_dir_regex_iteration = $self->dirRegexIteration($_host_cache_dir_tmp, $_host_cache_dir_tmp_regex)) as $_resource) {
+ foreach (($_dir_regex_iteration = $this->dirRegexIteration($cache_dir_tmp, $cache_dir_tmp_regex)) as $_resource) {
$_resource_type = $_resource->getType();
$_sub_path_name = $_resource->getSubpathname();
$_path_name = $_resource->getPathname();
- if ($_host_cache_dir === $cache_dir && $_resource_type !== 'dir' && strpos($_sub_path_name, '/') === false) {
+ if ($_resource_type !== 'dir' && strpos($_sub_path_name, '/') === false) {
continue; // Don't delete links/files in the immediate directory; e.g. `[SHORT_NAME]-advanced-cache` or `.htaccess`, etc.
// Actual `http|https/...` cache links/files are nested. Links/files in the immediate directory are for other purposes.
}
@@ -336,7 +175,7 @@
}
}
if (!unlink($_path_name)) {
- $self->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
+ $this->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete symlink: `%1$s`.', SLUG_TD), $_path_name));
}
++$counter; // Increment counter for each link we delete.
@@ -347,11 +186,11 @@
if ($check_max_age && !empty($max_age)) {
if ($_resource->getMTime() >= $max_age) {
- break; // Break switch handler.
+ break; // Break switch.
}
}
if (!unlink($_path_name)) {
- $self->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
+ $this->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete file: `%1$s`.', SLUG_TD), $_path_name));
}
++$counter; // Increment counter for each file we delete.
@@ -367,7 +206,7 @@
break; // Not deleting everything.
}
if (!rmdir($_path_name)) {
- $self->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
+ $this->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unable to delete dir: `%1$s`.', SLUG_TD), $_path_name));
}
# $counter++; // Increment counter for each directory we delete. ~ NO don't do that here.
@@ -375,269 +214,441 @@
break; // Break switch handler.
default: // Something else that is totally unexpected here.
- $self->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
+ $this->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
throw new \Exception(sprintf(__('Unexpected resource type: `%1$s`.', SLUG_TD), $_resource_type));
}
}
unset($_dir_regex_iteration, $_resource, $_resource_type, $_sub_path_name, $_path_name, $_lstat); // Housekeeping.
- if (!rename($_host_cache_dir_tmp, $_host_cache_dir)) {
- $self->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
- throw new \Exception(sprintf(__('Unable to delete files. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $_host_cache_dir_tmp));
+ if (!rename($cache_dir_tmp, $cache_dir)) {
+ $this->tryErasingAllFilesDirsIn($cache_dir_tmp, true); // Cleanup if possible.
+ throw new \Exception(sprintf(__('Unable to delete files. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $cache_dir_tmp));
}
+ /* ------- End lock state... ------------- */
+
+ $this->cacheUnlock($cache_lock); // Release.
+
+ return $counter;
}
- unset($_host_scheme, $_host_url, $_host_cache_path_flags, $_host_cache_path, $_host_cache_dir, $_host_cache_dir_tmp, $_host_cache_dir_tmp_regex);
- /* ------- End lock state... ------------- */
+ /*
+ * Delete files from the cache directory (for the current host);
+ * i.e., those that match a specific regex pattern.
+ *
+ * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
+ *
+ * @param string $regex A `/[regex pattern]/`; relative to the host cache directory.
+ * e.g. `/^my\-slug(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])/`
+ *
+ * Or, this can also be a full/absolute regex pattern against an absolute path;
+ * provided that it always starts with `/^`; including the full absolute cache/host directory path.
+ * e.g. `/^\/cache\/dir\/http\/example\.com\/my\-slug(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])/`
+ *
+ * @param boolean $check_max_age Check max age? i.e., use purge behavior?
+ *
+ * @param boolean $___considering_domain_mapping For internal use only.
+ * @param boolean $___consider_domain_mapping_host_token For internal use only.
+ * @param boolean $___consider_domain_mapping_host_base_dir_tokens For internal use only.
+ *
+ * @return integer Total files deleted by this routine (if any).
+ *
+ * @throws \Exception If unable to delete a file for any reason.
+ */
+ public function deleteFilesFromHostCacheDir(
+ $regex,
+ $check_max_age = false,
+ $___considering_domain_mapping = false,
+ $___consider_domain_mapping_host_token = null,
+ $___consider_domain_mapping_host_base_dir_tokens = null
+ ) {
+ $counter = 0; // Initialize.
+
+ if (!($regex = (string) $regex)) {
+ return $counter; // Nothing to do.
+ }
+ if (!is_dir($cache_dir = $this->cacheDir())) {
+ return $counter; // Nothing to do.
+ }
+ $cache_dir = $this->nDirSeps($cache_dir); // Normalize.
+ $host_token = $current_host_token = $this->hostToken();
+ $host_base_dir_tokens = $current_host_base_dir_tokens = $this->hostBaseDirTokens();
- $self->cacheUnlock($cache_lock); // Release.
+ if ($___considering_domain_mapping && isset($___consider_domain_mapping_host_token, $___consider_domain_mapping_host_base_dir_tokens)) {
+ $host_token = (string) $___consider_domain_mapping_host_token;
+ $host_base_dir_tokens = (string) $___consider_domain_mapping_host_base_dir_tokens;
+ }
+ if (!$host_token) { // Must have a host in the sub-routine below.
+ throw new \Exception(__('Invalid argument; host token empty!', SLUG_TD));
+ }
+ if ($check_max_age && $this->isAdvancedCache()) {
+ throw new \Exception(__('Invalid argument; isAdvancedCache!', SLUG_TD));
+ }
+ if ($check_max_age && !($max_age = strtotime('-'.$this->options['cache_max_age']))) {
+ return $counter; // Invalid cache expiration time.
+ }
+ /* ------- Begin lock state... ----------- */
- /* ------- Include domain mapping variations also. ------- */
+ $cache_lock = $this->cacheLock(); // Lock cache writes.
- if (!$___considering_domain_mapping && is_multisite() && $self->canConsiderDomainMapping()) {
- $domain_mapping_variations = array(); // Initialize array of domain variations.
+ clearstatcache(); // Clear stat cache to be sure we have a fresh start below.
- if (($_host_token_for_blog = $self->hostTokenForBlog())) {
- $_host_base_dir_tokens_for_blog = $self->hostBaseDirTokensForBlog();
- $domain_mapping_variations[] = array('host_token' => $_host_token_for_blog, 'host_base_dir_tokens' => $_host_base_dir_tokens_for_blog);
- } // The original blog host; i.e., without domain mapping.
- unset($_host_token_for_blog, $_host_base_dir_tokens_for_blog); // Housekeeping.
+ foreach (['http', 'https'] as $_host_scheme) {
+ $_host_url = $_host_scheme.'://'.$host_token.$host_base_dir_tokens;
+ $_host_cache_path_flags = CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
+ $_host_cache_path = $this->buildCachePath($_host_url, '', '', $_host_cache_path_flags);
+ $_host_cache_dir = $this->nDirSeps($cache_dir.'/'.$_host_cache_path); // Normalize.
- foreach ($self->domainMappingBlogDomains() as $_domain_mapping_blog_domain) {
- if (($_domain_host_token_for_blog = $self->hostTokenForBlog(false, true, $_domain_mapping_blog_domain))) {
- $_domain_host_base_dir_tokens_for_blog = $self->hostBaseDirTokensForBlog(false, true); // This is only a formality.
- $domain_mapping_variations[] = array('host_token' => $_domain_host_token_for_blog, 'host_base_dir_tokens' => $_domain_host_base_dir_tokens_for_blog);
+ if (!$_host_cache_dir || !is_dir($_host_cache_dir)) {
+ // On a multisite install this may have a cache sub-directory.
+ // e.g., `http/example-com[[-base]-child1][[/base]/child1]` instead of `http/example-com`.
+ continue; // Nothing to do.
+ }
+ $_host_cache_dir_tmp = $this->addTmpSuffix($_host_cache_dir); // Temporary directory.
+
+ $_host_cache_dir_tmp_regex = $regex; // Initialize host-specific regex pattern for the tmp directory.
+ $_host_cache_dir_tmp_regex = '\\/'.ltrim($_host_cache_dir_tmp_regex, '^\\/'); // Make sure it begins with an escaped `/`.
+ $_host_cache_dir_tmp_regex = $this->strIreplaceOnce(preg_quote($_host_cache_path.'/', '/'), '', $_host_cache_dir_tmp_regex);
+ $_host_cache_dir_tmp_regex = $this->strIreplaceOnce(preg_quote($_host_cache_dir.'/', '/'), '', $_host_cache_dir_tmp_regex);
+
+ $_host_cache_dir_tmp_regex = ltrim($_host_cache_dir_tmp_regex, '^\\/');
+ if (strpos($_host_cache_dir_tmp_regex, '(?:\/') === 0 || strpos($_host_cache_dir_tmp_regex, '(\/') === 0) {
+ $_host_cache_dir_tmp_regex = '/^'.preg_quote($_host_cache_dir_tmp, '/').$_host_cache_dir_tmp_regex;
+ } else {
+ $_host_cache_dir_tmp_regex = '/^'.preg_quote($_host_cache_dir_tmp.'/', '/').$_host_cache_dir_tmp_regex;
}
- } // This includes all of the domain mappings configured for the current blog ID.
- unset($_domain_mapping_blog_domain, $_domain_host_token_for_blog, $_domain_host_base_dir_tokens_for_blog); // Housekeeping.
+ #if(WP_DEBUG) file_put_contents(WP_CONTENT_DIR.'/'.strtolower(SHORT_NAME).'-debug.log', print_r($regex, TRUE)."\n".print_r($_host_cache_dir_tmp_regex, TRUE)."\n\n", FILE_APPEND);
+ // Uncomment the above line to debug regex pattern matching used by this routine; and others that call upon it.
- foreach ($domain_mapping_variations as $_domain_mapping_variation) {
- if ($_domain_mapping_variation['host_token'] === $current_host_token && $_domain_mapping_variation['host_base_dir_tokens'] === $current_host_base_dir_tokens) {
- continue; // Exclude current tokens. They were already iterated above.
+ if (!rename($_host_cache_dir, $_host_cache_dir_tmp)) {
+ throw new \Exception(sprintf(__('Unable to delete files. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $_host_cache_dir));
}
- $counter += $self->deleteFilesFromHostCacheDir($regex, $check_max_age, true, $_domain_mapping_variation['host_token'], $_domain_mapping_variation['host_base_dir_tokens']);
- }
- unset($_domain_mapping_variation); // Housekeeping.
- }
- return $counter;
-};
-
-/*
- * Delete all files/dirs from a directory (for all schemes/hosts);
- * including `[SHORT_NAME]-` prefixed files; or anything else for that matter.
- *
- * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
- *
- * @param string $dir The directory from which to delete files/dirs.
- *
- * SECURITY: This directory MUST be located inside the `/wp-content/` directory.
- * Also, it MUST be a sub-directory of `/wp-content/`, NOT the directory itself.
- * Also, it cannot be: `mu-plugins`, `themes`, or `plugins`.
- *
- * @param boolean $delete_dir_too Delete parent? i.e., delete the `$dir` itself also?
- *
- * @return integer Total files/directories deleted by this routine (if any).
- *
- * @throws \Exception If unable to delete a file/directory for any reason.
- */
-$self->deleteAllFilesDirsIn = function ($dir, $delete_dir_too = false) use ($self) {
- $counter = 0; // Initialize.
-
- if (!($dir = trim((string) $dir)) || !is_dir($dir)) {
- return $counter; // Nothing to do.
- }
- $dir = $self->nDirSeps($dir);
- $dir_temp = $self->addTmpSuffix($dir);
- $wp_content_dir = $self->nDirSeps(WP_CONTENT_DIR);
- $wp_content_dir_regex = preg_quote($wp_content_dir, '/');
+ foreach (($_dir_regex_iteration = $this->dirRegexIteration($_host_cache_dir_tmp, $_host_cache_dir_tmp_regex)) as $_resource) {
+ $_resource_type = $_resource->getType();
+ $_sub_path_name = $_resource->getSubpathname();
+ $_path_name = $_resource->getPathname();
+
+ if ($_host_cache_dir === $cache_dir && $_resource_type !== 'dir' && strpos($_sub_path_name, '/') === false) {
+ continue; // Don't delete links/files in the immediate directory; e.g. `[SHORT_NAME]-advanced-cache` or `.htaccess`, etc.
+ // Actual `http|https/...` cache links/files are nested. Links/files in the immediate directory are for other purposes.
+ }
+ switch ($_resource_type) {// Based on type; i.e., `link`, `file`, `dir`.
- if (!preg_match('/^'.$wp_content_dir_regex.'\/[^\/]+/i', $dir)) {
- return $counter; // Security flag; do nothing in this case.
- }
- if (preg_match('/^'.$wp_content_dir_regex.'\/(?:mu\-plugins|themes|plugins)(?:\/|$)/i', $dir)) {
- return $counter; // Security flag; do nothing in this case.
- }
- /* ------- Begin lock state... ----------- */
+ case 'link': // Symbolic links; i.e., 404 errors.
- $cache_lock = $self->cacheLock(); // Lock cache writes.
+ if ($check_max_age && !empty($max_age) && is_file($_resource->getLinkTarget())) {
+ if (($_lstat = lstat($_path_name)) && !empty($_lstat['mtime'])) {
+ if ($_lstat['mtime'] >= $max_age) {
+ break; // Break switch.
+ }
+ }
+ }
+ if (!unlink($_path_name)) {
+ $this->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
+ throw new \Exception(sprintf(__('Unable to delete symlink: `%1$s`.', SLUG_TD), $_path_name));
+ }
+ ++$counter; // Increment counter for each link we delete.
- clearstatcache(); // Clear stat cache to be sure we have a fresh start below.
+ break; // Break switch handler.
- if (!rename($dir, $dir_temp)) {
- throw new \Exception(sprintf(__('Unable to delete all files/dirs. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $dir));
- }
- foreach (($_dir_regex_iteration = $self->dirRegexIteration($dir_temp, '/.+/')) as $_resource) {
- $_resource_type = $_resource->getType();
- $_sub_path_name = $_resource->getSubpathname();
- $_path_name = $_resource->getPathname();
+ case 'file': // Regular files; i.e., not symlinks.
- switch ($_resource_type) {// Based on type; i.e., `link`, `file`, `dir`.
+ if ($check_max_age && !empty($max_age)) {
+ if ($_resource->getMTime() >= $max_age) {
+ break; // Break switch handler.
+ }
+ }
+ if (!unlink($_path_name)) {
+ $this->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
+ throw new \Exception(sprintf(__('Unable to delete file: `%1$s`.', SLUG_TD), $_path_name));
+ }
+ ++$counter; // Increment counter for each file we delete.
- case 'link': // Symbolic links; i.e., 404 errors.
+ break; // Break switch handler.
- if (!unlink($_path_name)) {
- $self->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
- throw new \Exception(sprintf(__('Unable to delete symlink: `%1$s`.', SLUG_TD), $_path_name));
- }
- ++$counter; // Increment counter for each link we delete.
+ case 'dir': // A regular directory; i.e., not a symlink.
- break; // Break switch handler.
+ if ($regex !== '/^.+/i') {
+ break; // Not deleting everything.
+ }
+ if ($check_max_age && !empty($max_age)) {
+ break; // Not deleting everything.
+ }
+ if (!rmdir($_path_name)) {
+ $this->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
+ throw new \Exception(sprintf(__('Unable to delete dir: `%1$s`.', SLUG_TD), $_path_name));
+ }
+ # $counter++; // Increment counter for each directory we delete. ~ NO don't do that here.
- case 'file': // Regular files; i.e., not symlinks.
+ break; // Break switch handler.
- if (!unlink($_path_name)) {
- $self->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
- throw new \Exception(sprintf(__('Unable to delete file: `%1$s`.', SLUG_TD), $_path_name));
+ default: // Something else that is totally unexpected here.
+ $this->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
+ throw new \Exception(sprintf(__('Unexpected resource type: `%1$s`.', SLUG_TD), $_resource_type));
}
- ++$counter; // Increment counter for each file we delete.
+ }
+ unset($_dir_regex_iteration, $_resource, $_resource_type, $_sub_path_name, $_path_name, $_lstat); // Housekeeping.
- break; // Break switch handler.
+ if (!rename($_host_cache_dir_tmp, $_host_cache_dir)) {
+ $this->tryErasingAllFilesDirsIn($_host_cache_dir_tmp, true); // Cleanup if possible.
+ throw new \Exception(sprintf(__('Unable to delete files. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $_host_cache_dir_tmp));
+ }
+ }
+ unset($_host_scheme, $_host_url, $_host_cache_path_flags, $_host_cache_path, $_host_cache_dir, $_host_cache_dir_tmp, $_host_cache_dir_tmp_regex);
- case 'dir': // A regular directory; i.e., not a symlink.
+ /* ------- End lock state... ------------- */
- if (!rmdir($_path_name)) {
- $self->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
- throw new \Exception(sprintf(__('Unable to delete dir: `%1$s`.', SLUG_TD), $_path_name));
- }
- # ++$counter; // Increment counter for each directory we delete. ~ NO don't do that here.
+ $this->cacheUnlock($cache_lock); // Release.
+
+ /* ------- Include domain mapping variations also. ------- */
+
+ if (!$___considering_domain_mapping && is_multisite() && $this->canConsiderDomainMapping()) {
+ $domain_mapping_variations = []; // Initialize array of domain variations.
- break; // Break switch handler.
+ if (($_host_token_for_blog = $this->hostTokenForBlog())) {
+ $_host_base_dir_tokens_for_blog = $this->hostBaseDirTokensForBlog();
+ $domain_mapping_variations[] = ['host_token' => $_host_token_for_blog, 'host_base_dir_tokens' => $_host_base_dir_tokens_for_blog];
+ } // The original blog host; i.e., without domain mapping.
+ unset($_host_token_for_blog, $_host_base_dir_tokens_for_blog); // Housekeeping.
- default: // Something else that is totally unexpected here.
- $self->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
- throw new \Exception(sprintf(__('Unexpected resource type: `%1$s`.', SLUG_TD), $_resource_type));
+ foreach ($this->domainMappingBlogDomains() as $_domain_mapping_blog_domain) {
+ if (($_domain_host_token_for_blog = $this->hostTokenForBlog(false, true, $_domain_mapping_blog_domain))) {
+ $_domain_host_base_dir_tokens_for_blog = $this->hostBaseDirTokensForBlog(false, true); // This is only a formality.
+ $domain_mapping_variations[] = ['host_token' => $_domain_host_token_for_blog, 'host_base_dir_tokens' => $_domain_host_base_dir_tokens_for_blog];
+ }
+ } // This includes all of the domain mappings configured for the current blog ID.
+ unset($_domain_mapping_blog_domain, $_domain_host_token_for_blog, $_domain_host_base_dir_tokens_for_blog); // Housekeeping.
+
+ foreach ($domain_mapping_variations as $_domain_mapping_variation) {
+ if ($_domain_mapping_variation['host_token'] === $current_host_token && $_domain_mapping_variation['host_base_dir_tokens'] === $current_host_base_dir_tokens) {
+ continue; // Exclude current tokens. They were already iterated above.
+ }
+ $counter += $this->deleteFilesFromHostCacheDir($regex, $check_max_age, true, $_domain_mapping_variation['host_token'], $_domain_mapping_variation['host_base_dir_tokens']);
+ }
+ unset($_domain_mapping_variation); // Housekeeping.
}
+ return $counter;
}
- unset($_dir_regex_iteration, $_resource, $_resource_type, $_sub_path_name, $_path_name); // Housekeeping.
- if (!rename($dir_temp, $dir)) {
- $self->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
- throw new \Exception(sprintf(__('Unable to delete all files/dirs. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $dir_temp));
- }
- if ($delete_dir_too) {
- if (!rmdir($dir)) {
- throw new \Exception(sprintf(__('Unable to delete directory: `%1$s`.', SLUG_TD), $dir));
+ /*
+ * Delete all files/dirs from a directory (for all schemes/hosts);
+ * including `[SHORT_NAME]-` prefixed files; or anything else for that matter.
+ *
+ * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
+ *
+ * @param string $dir The directory from which to delete files/dirs.
+ *
+ * SECURITY: This directory MUST be located inside the `/wp-content/` directory.
+ * Also, it MUST be a sub-directory of `/wp-content/`, NOT the directory itself.
+ * Also, it cannot be: `mu-plugins`, `themes`, or `plugins`.
+ *
+ * @param boolean $delete_dir_too Delete parent? i.e., delete the `$dir` itself also?
+ *
+ * @return integer Total files/directories deleted by this routine (if any).
+ *
+ * @throws \Exception If unable to delete a file/directory for any reason.
+ */
+ public function deleteAllFilesDirsIn($dir, $delete_dir_too = false)
+ {
+ $counter = 0; // Initialize.
+
+ if (!($dir = trim((string) $dir)) || !is_dir($dir)) {
+ return $counter; // Nothing to do.
}
- ++$counter; // Increment counter for each directory we delete.
- }
- /* ------- End lock state... ------------- */
-
- $self->cacheUnlock($cache_lock); // Release.
-
- return $counter;
-};
-
-/*
- * Erase all files/dirs from a directory (for all schemes/hosts);
- * including `[SHORT_NAME]-` prefixed files; or anything else for that matter.
- *
- * WARNING: This does NO LOCKING and NO ATOMIC deletions.
- *
- * @since 150821 Improving recovery under stress.
- *
- * @param string $dir The directory from which to erase files/dirs.
- *
- * SECURITY: This directory MUST be located inside the `/wp-content/` directory.
- * Also, it MUST be a sub-directory of `/wp-content/`, NOT the directory itself.
- * Also, it cannot be: `mu-plugins`, `themes`, or `plugins`.
- *
- * @param boolean $erase_dir_too Erase parent? i.e., erase the `$dir` itself also?
- *
- * @return integer Total files/directories erased by this routine (if any).
- *
- * @throws \Exception If unable to erase a file/directory for any reason.
- */
-$self->eraseAllFilesDirsIn = function ($dir, $erase_dir_too = false) use ($self) {
- $counter = 0; // Initialize.
-
- if (!($dir = trim((string) $dir)) || !is_dir($dir)) {
- return $counter; // Nothing to do.
- }
- $dir = $self->nDirSeps($dir);
- $wp_content_dir = $self->nDirSeps(WP_CONTENT_DIR);
- $wp_content_dir_regex = preg_quote($wp_content_dir, '/');
+ $dir = $this->nDirSeps($dir);
+ $dir_temp = $this->addTmpSuffix($dir);
+ $wp_content_dir = $this->nDirSeps(WP_CONTENT_DIR);
+ $wp_content_dir_regex = preg_quote($wp_content_dir, '/');
- if (!preg_match('/^'.$wp_content_dir_regex.'\/[^\/]+/i', $dir)) {
- return $counter; // Security flag; do nothing in this case.
- }
- if (preg_match('/^'.$wp_content_dir_regex.'\/(?:mu\-plugins|themes|plugins)(?:\/|$)/i', $dir)) {
- return $counter; // Security flag; do nothing in this case.
- }
- clearstatcache(); // Clear stat cache to be sure we have a fresh start below.
+ if (!preg_match('/^'.$wp_content_dir_regex.'\/[^\/]+/i', $dir)) {
+ return $counter; // Security flag; do nothing in this case.
+ }
+ if (preg_match('/^'.$wp_content_dir_regex.'\/(?:mu\-plugins|themes|plugins)(?:\/|$)/i', $dir)) {
+ return $counter; // Security flag; do nothing in this case.
+ }
+ /* ------- Begin lock state... ----------- */
- foreach (($_dir_regex_iteration = $self->dirRegexIteration($dir, '/.+/')) as $_resource) {
- $_resource_type = $_resource->getType();
- $_sub_path_name = $_resource->getSubpathname();
- $_path_name = $_resource->getPathname();
+ $cache_lock = $this->cacheLock(); // Lock cache writes.
- switch ($_resource_type) {// Based on type; i.e., `link`, `file`, `dir`.
+ clearstatcache(); // Clear stat cache to be sure we have a fresh start below.
- case 'link': // Symbolic links; i.e., 404 errors.
+ if (!rename($dir, $dir_temp)) {
+ throw new \Exception(sprintf(__('Unable to delete all files/dirs. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $dir));
+ }
+ foreach (($_dir_regex_iteration = $this->dirRegexIteration($dir_temp, '/.+/')) as $_resource) {
+ $_resource_type = $_resource->getType();
+ $_sub_path_name = $_resource->getSubpathname();
+ $_path_name = $_resource->getPathname();
- if (!unlink($_path_name)) {
- throw new \Exception(sprintf(__('Unable to erase symlink: `%1$s`.', SLUG_TD), $_path_name));
- }
- ++$counter; // Increment counter for each link we erase.
+ switch ($_resource_type) {// Based on type; i.e., `link`, `file`, `dir`.
- break; // Break switch handler.
+ case 'link': // Symbolic links; i.e., 404 errors.
- case 'file': // Regular files; i.e., not symlinks.
+ if (!unlink($_path_name)) {
+ $this->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
+ throw new \Exception(sprintf(__('Unable to delete symlink: `%1$s`.', SLUG_TD), $_path_name));
+ }
+ ++$counter; // Increment counter for each link we delete.
- if (!unlink($_path_name)) {
- throw new \Exception(sprintf(__('Unable to erase file: `%1$s`.', SLUG_TD), $_path_name));
- }
- ++$counter; // Increment counter for each file we erase.
+ break; // Break switch handler.
- break; // Break switch handler.
+ case 'file': // Regular files; i.e., not symlinks.
- case 'dir': // A regular directory; i.e., not a symlink.
+ if (!unlink($_path_name)) {
+ $this->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
+ throw new \Exception(sprintf(__('Unable to delete file: `%1$s`.', SLUG_TD), $_path_name));
+ }
+ ++$counter; // Increment counter for each file we delete.
- if (!rmdir($_path_name)) {
- throw new \Exception(sprintf(__('Unable to erase dir: `%1$s`.', SLUG_TD), $_path_name));
- }
- # ++$counter; // Increment counter for each directory we erase. ~ NO don't do that here.
+ break; // Break switch handler.
+
+ case 'dir': // A regular directory; i.e., not a symlink.
+
+ if (!rmdir($_path_name)) {
+ $this->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
+ throw new \Exception(sprintf(__('Unable to delete dir: `%1$s`.', SLUG_TD), $_path_name));
+ }
+ # ++$counter; // Increment counter for each directory we delete. ~ NO don't do that here.
+
+ break; // Break switch handler.
- break; // Break switch handler.
+ default: // Something else that is totally unexpected here.
+ $this->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
+ throw new \Exception(sprintf(__('Unexpected resource type: `%1$s`.', SLUG_TD), $_resource_type));
+ }
+ }
+ unset($_dir_regex_iteration, $_resource, $_resource_type, $_sub_path_name, $_path_name); // Housekeeping.
- default: // Something else that is totally unexpected here.
- throw new \Exception(sprintf(__('Unexpected resource type: `%1$s`.', SLUG_TD), $_resource_type));
+ if (!rename($dir_temp, $dir)) {
+ $this->tryErasingAllFilesDirsIn($dir_temp, true); // Cleanup if possible.
+ throw new \Exception(sprintf(__('Unable to delete all files/dirs. Rename failure on tmp directory: `%1$s`.', SLUG_TD), $dir_temp));
}
+ if ($delete_dir_too) {
+ if (!rmdir($dir)) {
+ throw new \Exception(sprintf(__('Unable to delete directory: `%1$s`.', SLUG_TD), $dir));
+ }
+ ++$counter; // Increment counter for each directory we delete.
+ }
+ /* ------- End lock state... ------------- */
+
+ $this->cacheUnlock($cache_lock); // Release.
+
+ return $counter;
}
- unset($_dir_regex_iteration, $_resource, $_resource_type, $_sub_path_name, $_path_name); // Housekeeping.
- if ($erase_dir_too) {
- if (!rmdir($dir)) {
- throw new \Exception(sprintf(__('Unable to erase directory: `%1$s`.', SLUG_TD), $dir));
+ /*
+ * Erase all files/dirs from a directory (for all schemes/hosts);
+ * including `[SHORT_NAME]-` prefixed files; or anything else for that matter.
+ *
+ * WARNING: This does NO LOCKING and NO ATOMIC deletions.
+ *
+ * @since 150821 Improving recovery under stress.
+ *
+ * @param string $dir The directory from which to erase files/dirs.
+ *
+ * SECURITY: This directory MUST be located inside the `/wp-content/` directory.
+ * Also, it MUST be a sub-directory of `/wp-content/`, NOT the directory itself.
+ * Also, it cannot be: `mu-plugins`, `themes`, or `plugins`.
+ *
+ * @param boolean $erase_dir_too Erase parent? i.e., erase the `$dir` itself also?
+ *
+ * @return integer Total files/directories erased by this routine (if any).
+ *
+ * @throws \Exception If unable to erase a file/directory for any reason.
+ */
+ public function eraseAllFilesDirsIn($dir, $erase_dir_too = false)
+ {
+ $counter = 0; // Initialize.
+
+ if (!($dir = trim((string) $dir)) || !is_dir($dir)) {
+ return $counter; // Nothing to do.
+ }
+ $dir = $this->nDirSeps($dir);
+ $wp_content_dir = $this->nDirSeps(WP_CONTENT_DIR);
+ $wp_content_dir_regex = preg_quote($wp_content_dir, '/');
+
+ if (!preg_match('/^'.$wp_content_dir_regex.'\/[^\/]+/i', $dir)) {
+ return $counter; // Security flag; do nothing in this case.
}
- ++$counter; // Increment counter for each directory we erase.
+ if (preg_match('/^'.$wp_content_dir_regex.'\/(?:mu\-plugins|themes|plugins)(?:\/|$)/i', $dir)) {
+ return $counter; // Security flag; do nothing in this case.
+ }
+ clearstatcache(); // Clear stat cache to be sure we have a fresh start below.
+
+ foreach (($_dir_regex_iteration = $this->dirRegexIteration($dir, '/.+/')) as $_resource) {
+ $_resource_type = $_resource->getType();
+ $_sub_path_name = $_resource->getSubpathname();
+ $_path_name = $_resource->getPathname();
+
+ switch ($_resource_type) {// Based on type; i.e., `link`, `file`, `dir`.
+
+ case 'link': // Symbolic links; i.e., 404 errors.
+
+ if (!unlink($_path_name)) {
+ throw new \Exception(sprintf(__('Unable to erase symlink: `%1$s`.', SLUG_TD), $_path_name));
+ }
+ ++$counter; // Increment counter for each link we erase.
+
+ break; // Break switch handler.
+
+ case 'file': // Regular files; i.e., not symlinks.
+
+ if (!unlink($_path_name)) {
+ throw new \Exception(sprintf(__('Unable to erase file: `%1$s`.', SLUG_TD), $_path_name));
+ }
+ ++$counter; // Increment counter for each file we erase.
+
+ break; // Break switch handler.
+
+ case 'dir': // A regular directory; i.e., not a symlink.
+
+ if (!rmdir($_path_name)) {
+ throw new \Exception(sprintf(__('Unable to erase dir: `%1$s`.', SLUG_TD), $_path_name));
+ }
+ # ++$counter; // Increment counter for each directory we erase. ~ NO don't do that here.
+
+ break; // Break switch handler.
+
+ default: // Something else that is totally unexpected here.
+ throw new \Exception(sprintf(__('Unexpected resource type: `%1$s`.', SLUG_TD), $_resource_type));
+ }
+ }
+ unset($_dir_regex_iteration, $_resource, $_resource_type, $_sub_path_name, $_path_name); // Housekeeping.
+
+ if ($erase_dir_too) {
+ if (!rmdir($dir)) {
+ throw new \Exception(sprintf(__('Unable to erase directory: `%1$s`.', SLUG_TD), $dir));
+ }
+ ++$counter; // Increment counter for each directory we erase.
+ }
+ return $counter;
}
- return $counter;
-};
-
-/*
- * Try to erase all files/dirs from a directory (for all schemes/hosts);
- * including `[SHORT_NAME]-` prefixed files; or anything else for that matter.
- *
- * WARNING: This does NO LOCKING and NO ATOMIC deletions.
- *
- * @since 150821 Improving recovery under stress.
- *
- * @param string $dir The directory from which to erase files/dirs.
- *
- * SECURITY: This directory MUST be located inside the `/wp-content/` directory.
- * Also, it MUST be a sub-directory of `/wp-content/`, NOT the directory itself.
- * Also, it cannot be: `mu-plugins`, `themes`, or `plugins`.
- *
- * @param boolean $erase_dir_too Erase parent? i.e., erase the `$dir` itself also?
- *
- * @return integer Total files/directories erased by this routine (if any).
- */
-$self->tryErasingAllFilesDirsIn = function ($dir, $erase_dir_too = false) use ($self) {
- $counter = 0; // Initialize counter.
- try {
- $counter += $self->eraseAllFilesDirsIn($dir, $erase_dir_too);
- } catch (\Exception $exception) {
- // Fail softly.
+
+ /*
+ * Try to erase all files/dirs from a directory (for all schemes/hosts);
+ * including `[SHORT_NAME]-` prefixed files; or anything else for that matter.
+ *
+ * WARNING: This does NO LOCKING and NO ATOMIC deletions.
+ *
+ * @since 150821 Improving recovery under stress.
+ *
+ * @param string $dir The directory from which to erase files/dirs.
+ *
+ * SECURITY: This directory MUST be located inside the `/wp-content/` directory.
+ * Also, it MUST be a sub-directory of `/wp-content/`, NOT the directory itself.
+ * Also, it cannot be: `mu-plugins`, `themes`, or `plugins`.
+ *
+ * @param boolean $erase_dir_too Erase parent? i.e., erase the `$dir` itself also?
+ *
+ * @return integer Total files/directories erased by this routine (if any).
+ */
+ public function tryErasingAllFilesDirsIn($dir, $erase_dir_too = false)
+ {
+ $counter = 0; // Initialize counter.
+ try {
+ $counter += $this->eraseAllFilesDirsIn($dir, $erase_dir_too);
+ } catch (\Exception $exception) {
+ // Fail softly.
+ }
+ return $counter;
}
- return $counter;
-};
+}
diff --git a/src/includes/traits/Shared/CacheLockUtils.php b/src/includes/traits/Shared/CacheLockUtils.php
index a3557199..8fca15b8 100644
--- a/src/includes/traits/Shared/CacheLockUtils.php
+++ b/src/includes/traits/Shared/CacheLockUtils.php
@@ -1,80 +1,85 @@
cacheLock = function () use ($self) {
- if ($self->applyWpFilters(GLOBAL_NS.'\\share::disable_cache_locking', false)
- || $self->applyWpFilters(GLOBAL_NS.'_disable_cache_locking', false)) {
- return false; // Disabled cache locking.
- }
- if (!($wp_config_file = $self->findWpConfigFile())) {
- throw new \Exception(__('Unable to find the wp-config.php file.', SLUG_TD));
- }
- $lock_type = 'flock'; // Default lock type.
- $lock_type = $self->applyWpFilters(GLOBAL_NS.'\\share::cache_lock_lock_type', $lock_type);
- $lock_type = $self->applyWpFilters(GLOBAL_NS.'_cache_lock_type', $lock_type);
-
- if (!in_array($lock_type, array('flock', 'sem'), true)) {
+trait CacheLockUtils {
+ /*
+ * Get an exclusive lock on the cache directory.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return array Lock type & resource handle needed to unlock later or FALSE if disabled by filter.
+ *
+ * @throws \Exception If {@link \sem_get()} not available and there's
+ * no writable tmp directory for {@link \flock()} either.
+ *
+ * @throws \Exception If unable to obtain an exclusive lock by any available means.
+ *
+ * @note This call is blocking; i.e. it will not return a lock until a lock becomes possible.
+ * In short, this will block the caller until such time as write access becomes possible.
+ */
+ public function cacheLock()
+ {
+ if ($this->applyWpFilters(GLOBAL_NS.'\\share::disable_cache_locking', false)
+ || $this->applyWpFilters(GLOBAL_NS.'_disable_cache_locking', false)
+ ) {
+ return false; // Disabled cache locking.
+ }
+ if (!($wp_config_file = $this->findWpConfigFile())) {
+ throw new \Exception(__('Unable to find the wp-config.php file.', SLUG_TD));
+ }
$lock_type = 'flock'; // Default lock type.
- }
- if ($lock_type === 'sem' && $self->functionIsPossible('sem_get')) {
- if (($ipc_key = ftok($wp_config_file, 'w'))) {
- if (($resource = sem_get($ipc_key, 1)) && sem_acquire($resource)) {
- return array('type' => 'sem', 'resource' => $resource);
+ $lock_type = $this->applyWpFilters(GLOBAL_NS.'\\share::cache_lock_lock_type', $lock_type);
+ $lock_type = $this->applyWpFilters(GLOBAL_NS.'_cache_lock_type', $lock_type);
+
+ if (!in_array($lock_type, ['flock', 'sem'], true)) {
+ $lock_type = 'flock'; // Default lock type.
+ }
+ if ($lock_type === 'sem' && $this->functionIsPossible('sem_get')) {
+ if (($ipc_key = ftok($wp_config_file, 'w'))) {
+ if (($resource = sem_get($ipc_key, 1)) && sem_acquire($resource)) {
+ return ['type' => 'sem', 'resource' => $resource];
+ }
}
}
- }
- if (!($tmp_dir = $self->getTmpDir())) {
- throw new \Exception(__('No writable tmp directory.', SLUG_TD));
- }
- $inode_key = fileinode($wp_config_file);
- $mutex = $tmp_dir.'/'.SLUG_TD.'-'.$inode_key.'.lock';
-
- if (!($resource = fopen($mutex, 'wb')) || !flock($resource, LOCK_EX)) {
- throw new \Exception(__('Unable to obtain an exclusive lock.', SLUG_TD));
- }
+ if (!($tmp_dir = $this->getTmpDir())) {
+ throw new \Exception(__('No writable tmp directory.', SLUG_TD));
+ }
+ $inode_key = fileinode($wp_config_file);
+ $mutex = $tmp_dir.'/'.SLUG_TD.'-'.$inode_key.'.lock';
- @chmod($mutex, 0666); // See https://git.io/v2WAt
+ if (!($resource = fopen($mutex, 'wb')) || !flock($resource, LOCK_EX)) {
+ throw new \Exception(__('Unable to obtain an exclusive lock.', SLUG_TD));
+ }
- return array('type' => 'flock', 'resource' => $resource);
-};
+ @chmod($mutex, 0666); // See https://git.io/v2WAt
-/*
- * Release an exclusive lock on the cache directory.
- *
- * @since 150422 Rewrite. Updated 151002 to remove the `array` typecast.
- *
- * @param array|mixed $lock Type & resource.
- */
-$self->cacheUnlock = function ($lock) use ($self) {
- if (!is_array($lock)) {
- return; // Not possible.
- // Or, they disabled cache locking.
- }
- if (empty($lock['type']) || empty($lock['resource'])) {
- return; // Not possible.
- }
- if (!is_resource($lock['resource'])) {
- return; // Not possible.
+ return ['type' => 'flock', 'resource' => $resource];
}
- if ($lock['type'] === 'sem') {
- sem_release($lock['resource']);
- } elseif ($lock['type'] === 'flock') {
- flock($lock['resource'], LOCK_UN);
- fclose($lock['resource']);
+
+ /*
+ * Release an exclusive lock on the cache directory.
+ *
+ * @since 150422 Rewrite. Updated 151002 to remove the `array` typecast.
+ *
+ * @param array|mixed $lock Type & resource.
+ */
+ public function cacheUnlock($lock)
+ {
+ if (!is_array($lock)) {
+ return; // Not possible.
+ // Or, they disabled cache locking.
+ }
+ if (empty($lock['type']) || empty($lock['resource'])) {
+ return; // Not possible.
+ }
+ if (!is_resource($lock['resource'])) {
+ return; // Not possible.
+ }
+ if ($lock['type'] === 'sem') {
+ sem_release($lock['resource']);
+ } elseif ($lock['type'] === 'flock') {
+ flock($lock['resource'], LOCK_UN);
+ fclose($lock['resource']);
+ }
}
-};
+}
diff --git a/src/includes/traits/Shared/CachePathUtils.php b/src/includes/traits/Shared/CachePathUtils.php
index a23a9478..1e90284f 100644
--- a/src/includes/traits/Shared/CachePathUtils.php
+++ b/src/includes/traits/Shared/CachePathUtils.php
@@ -1,351 +1,361 @@
cachePathRegexSuffixFrag = function ($regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG) use ($self) {
- if ($regex_suffix_frag === CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG) {
- return $self->cachePathRegexDefaultSuffixFrag();
- }
- return (string) $regex_suffix_frag;
-};
-
-/*
-* Default cache-path suffix frag (regex).
-*
-* @since 151220 Enhancing translation support.
-*
-* @return string Default cache-path suffix frag (regex).
-*
-* @TODO Use conditional to detect the AMP plugin (e.g., `isAmpInstalled()`) to avoid edge cases with the `|\/amp` regex here
-*/
-$self->cachePathRegexDefaultSuffixFrag = function () use ($self) {
- if ($self->isPlugin() && !empty($GLOBALS['wp_rewrite'])){
- $pagination_base = $GLOBALS['wp_rewrite']->pagination_base;
- $comments_pagination_base = $GLOBALS['wp_rewrite']->comments_pagination_base;
- return '(?:\/index|\/amp)?(?:\.|\/(?:'.preg_quote($pagination_base, '/').'\/[0-9]+|'.preg_quote($comments_pagination_base, '/').'\-[0-9]+)[.\/])';
- } else {
- return '(?:\/index|\/amp)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])';
+trait CachePathUtils {
+ /*
+ * Cache-path suffix frag (regex).
+ *
+ * @since 151220 Enhancing translation support.
+ *
+ * @param string $regex_suffix_frag Existing regex suffix frag?
+ *
+ * @return string Cache-path suffix frag (regex).
+ */
+ public function cachePathRegexSuffixFrag($regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ {
+ if ($regex_suffix_frag === CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG) {
+ return $this->cachePathRegexDefaultSuffixFrag();
+ }
+ return (string) $regex_suffix_frag;
}
-};
-
-/*
- * Converts a URL into a `cache/path` based on input `$flags`.
- *
- * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
- *
- * @param string $url The input URL to convert.
- * @param string $with_user_token Optional user token (if applicable).
- * @param string $with_version_salt Optional version salt (if applicable).
- * @param int $flags Optional flags. A bitmask via `CACHE_PATH_*` constants.
- *
- * @return string The resulting `cache/path` based on the input `$url` & `$flags`.
- */
-$self->buildCachePath = function ($url, $with_user_token = '', $with_version_salt = '', $flags = CACHE_PATH_DEFAULT) use ($self) {
- # Force parameter types.
-
- $url = trim((string) $url);
- $with_user_token = trim((string) $with_user_token);
- $with_version_salt = trim((string) $with_version_salt);
-
- # Initialize variables.
-
- $is_multisite = is_multisite();
- $can_consider_domain_mapping = $is_multisite && $self->canConsiderDomainMapping();
- $cache_path = ''; // Initialize cache path being built here.
-
- # Deal w/ domain mapping considerations.
-
- if ($flags & CACHE_PATH_CONSIDER_DOMAIN_MAPPING && $is_multisite && $can_consider_domain_mapping) {
- if ($flags & CACHE_PATH_REVERSE_DOMAIN_MAPPING) {
- $url = $self->domainMappingReverseUrlFilter($url);
+
+ /*
+ * Default cache-path suffix frag (regex).
+ *
+ * @since 151220 Enhancing translation support.
+ *
+ * @return string Default cache-path suffix frag (regex).
+ *
+ * @TODO Use conditional to detect the AMP plugin (e.g., `isAmpInstalled()`) to avoid edge cases with the `|\/amp` regex here
+ */
+ public function cachePathRegexDefaultSuffixFrag()
+ {
+ if ($this->isPlugin() && !empty($GLOBALS['wp_rewrite'])) {
+ $pagination_base = $GLOBALS['wp_rewrite']->pagination_base;
+ $comments_pagination_base = $GLOBALS['wp_rewrite']->comments_pagination_base;
+ return '(?:\/index|\/amp)?(?:\.|\/(?:'.preg_quote($pagination_base, '/').'\/[0-9]+|'.preg_quote($comments_pagination_base, '/').'\-[0-9]+)[.\/])';
} else {
- $url = $self->domainMappingUrlFilter($url);
+ return '(?:\/index|\/amp)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])';
}
}
- # Validate the URL we have now.
- if (!$url || !($url_parts = $self->parseUrl($url))) {
- return ($cache_path = ''); // Not possible.
- }
- if (empty($url_parts['scheme']) || $url_parts['scheme'] === '//') {
- return ($cache_path = ''); // Not possible.
- }
- if (empty($url_parts['host'])) {
- return ($cache_path = ''); // Not possible.
- }
- # Initialize additional variables; based on the parsed URL.
+ /*
+ * Converts a URL into a `cache/path` based on input `$flags`.
+ *
+ * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
+ *
+ * @param string $url The input URL to convert.
+ * @param string $with_user_token Optional user token (if applicable).
+ * @param string $with_version_salt Optional version salt (if applicable).
+ * @param int $flags Optional flags. A bitmask via `CACHE_PATH_*` constants.
+ *
+ * @return string The resulting `cache/path` based on the input `$url` & `$flags`.
+ */
+ public function buildCachePath($url, $with_user_token = '', $with_version_salt = '', $flags = CACHE_PATH_DEFAULT)
+ {
+ # Force parameter types.
+
+ $url = trim((string) $url);
+ $with_user_token = trim((string) $with_user_token);
+ $with_version_salt = trim((string) $with_version_salt);
+
+ # Initialize variables.
+
+ $is_multisite = is_multisite();
+ $can_consider_domain_mapping = $is_multisite && $this->canConsiderDomainMapping();
+ $cache_path = ''; // Initialize cache path being built here.
+
+ # Deal w/ domain mapping considerations.
+
+ if ($flags & CACHE_PATH_CONSIDER_DOMAIN_MAPPING && $is_multisite && $can_consider_domain_mapping) {
+ if ($flags & CACHE_PATH_REVERSE_DOMAIN_MAPPING) {
+ $url = $this->domainMappingReverseUrlFilter($url);
+ } else {
+ $url = $this->domainMappingUrlFilter($url);
+ }
+ }
+ # Validate the URL we have now.
- $is_url_domain_mapped = $is_multisite && $can_consider_domain_mapping && $self->domainMappingBlogId($url);
- $host_base_dir_tokens = $self->hostBaseDirTokens(false, $is_url_domain_mapped, !empty($url_parts['path']) ? $url_parts['path'] : '/');
+ if (!$url || !($url_parts = $this->parseUrl($url))) {
+ return ($cache_path = ''); // Not possible.
+ }
+ if (empty($url_parts['scheme']) || $url_parts['scheme'] === '//') {
+ return ($cache_path = ''); // Not possible.
+ }
+ if (empty($url_parts['host'])) {
+ return ($cache_path = ''); // Not possible.
+ }
+ # Initialize additional variables; based on the parsed URL.
- $is_a_multisite_base_dir = $is_multisite && $host_base_dir_tokens && $host_base_dir_tokens !== '/' // Check?
- && stripos(!empty($url_parts['path']) ? rtrim($url_parts['path'], '/').'/' : '/', $host_base_dir_tokens) === 0;
+ $is_url_domain_mapped = $is_multisite && $can_consider_domain_mapping && $this->domainMappingBlogId($url);
+ $host_base_dir_tokens = $this->hostBaseDirTokens(false, $is_url_domain_mapped, !empty($url_parts['path']) ? $url_parts['path'] : '/');
- $is_a_multisite_base_dir_root = $is_multisite && $is_a_multisite_base_dir // Save time by using the previous check here.
- && strcasecmp(trim($host_base_dir_tokens, '/'), trim(!empty($url_parts['path']) ? $url_parts['path'] : '/', '/')) === 0;
+ $is_a_multisite_base_dir = $is_multisite && $host_base_dir_tokens && $host_base_dir_tokens !== '/' // Check?
+ && stripos(!empty($url_parts['path']) ? rtrim($url_parts['path'], '/').'/' : '/', $host_base_dir_tokens) === 0;
- # Build and return the cache path.
+ $is_a_multisite_base_dir_root = $is_multisite && $is_a_multisite_base_dir // Save time by using the previous check here.
+ && strcasecmp(trim($host_base_dir_tokens, '/'), trim(!empty($url_parts['path']) ? $url_parts['path'] : '/', '/')) === 0;
- if (!($flags & CACHE_PATH_NO_SCHEME)) {
- $cache_path .= $url_parts['scheme'].'/';
- }
- if (!($flags & CACHE_PATH_NO_HOST)) {
- $cache_path .= $url_parts['host'].'/';
-
- // Put multisite sub-roots into a host directory of their own.
- // e.g., `example-com[[-base]-child1]` instead of `example-com`.
- if ($is_a_multisite_base_dir && $host_base_dir_tokens && $host_base_dir_tokens !== '/') {
- $host_base_dir_suffix = preg_replace('/[^a-z0-9.]/i', '-', rtrim($host_base_dir_tokens, '/'));
- $cache_path = rtrim($cache_path, '/').$host_base_dir_suffix.'/';
+ # Build and return the cache path.
+
+ if (!($flags & CACHE_PATH_NO_SCHEME)) {
+ $cache_path .= $url_parts['scheme'].'/';
}
- }
- if (!($flags & CACHE_PATH_NO_PATH)) {
- if (isset($url_parts['path'][201])) {
- $_path_tmp = '/'; // Initialize tmp path.
- foreach (explode('/', $url_parts['path']) as $_path_component) {
- if (!isset($_path_component[0])) {
- continue; // Empty.
+ if (!($flags & CACHE_PATH_NO_HOST)) {
+ $cache_path .= $url_parts['host'].'/';
+
+ // Put multisite sub-roots into a host directory of their own.
+ // e.g., `example-com[[-base]-child1]` instead of `example-com`.
+ if ($is_a_multisite_base_dir && $host_base_dir_tokens && $host_base_dir_tokens !== '/') {
+ $host_base_dir_suffix = preg_replace('/[^a-z0-9.]/i', '-', rtrim($host_base_dir_tokens, '/'));
+ $cache_path = rtrim($cache_path, '/').$host_base_dir_suffix.'/';
+ }
+ }
+ if (!($flags & CACHE_PATH_NO_PATH)) {
+ if (isset($url_parts['path'][201])) {
+ $_path_tmp = '/'; // Initialize tmp path.
+ foreach (explode('/', $url_parts['path']) as $_path_component) {
+ if (!isset($_path_component[0])) {
+ continue; // Empty.
+ }
+ if (isset($_path_component[201])) {
+ $_path_component = 'lpc-'.sha1($_path_component);
+ }
+ $_path_tmp .= $_path_component.'/';
+ }
+ $url_parts['path'] = $_path_tmp; // Shorter components.
+ unset($_path_component, $_path_tmp); // Housekeeping.
+
+ if (isset($url_parts['path'][2001])) {
+ $url_parts['path'] = '/lp-'.sha1($url_parts['path']).'/';
}
- if (isset($_path_component[201])) {
- $_path_component = 'lpc-'.sha1($_path_component);
+ } // Now add the path and check for a possible root `index/` suffix.
+ if (!empty($url_parts['path']) && strlen($url_parts['path'] = trim($url_parts['path'], '\\/'." \t\n\r\0\x0B"))) {
+ $cache_path .= $url_parts['path'].'/'; // Add the path as it exists.
+
+ if (!($flags & CACHE_PATH_NO_PATH_INDEX) && $is_multisite && $is_a_multisite_base_dir_root) {
+ // We should build an `index/` when this ends with a multisite [[/base]/child1] root.
+ // e.g., `http/example-com[[-base]-child1][[/base]/child1]` is a root directory.
+ $cache_path .= 'index/'; // Use an index suffix.
}
- $_path_tmp .= $_path_component.'/';
+ } elseif (!($flags & CACHE_PATH_NO_PATH_INDEX)) {
+ $cache_path .= 'index/';
}
- $url_parts['path'] = $_path_tmp; // Shorter components.
- unset($_path_component, $_path_tmp); // Housekeeping.
+ }
+ if ($this->isExtensionLoaded('mbstring') && mb_check_encoding($cache_path, 'UTF-8')) {
+ $cache_path = mb_strtolower($cache_path, 'UTF-8');
+ }
+ $cache_path = str_replace('.', '-', strtolower($cache_path));
- if (isset($url_parts['path'][2001])) {
- $url_parts['path'] = '/lp-'.sha1($url_parts['path']).'/';
+ if (!($flags & CACHE_PATH_NO_QUV)) {
+ if (!($flags & CACHE_PATH_NO_QUERY)) {
+ if (isset($url_parts['query']) && $url_parts['query'] !== '') {
+ $cache_path = rtrim($cache_path, '/').'.q/'.md5($url_parts['query']).'/';
+ }
}
- } // Now add the path and check for a possible root `index/` suffix.
- if (!empty($url_parts['path']) && strlen($url_parts['path'] = trim($url_parts['path'], '\\/'." \t\n\r\0\x0B"))) {
- $cache_path .= $url_parts['path'].'/'; // Add the path as it exists.
-
- if (!($flags & CACHE_PATH_NO_PATH_INDEX) && $is_multisite && $is_a_multisite_base_dir_root) {
- // We should build an `index/` when this ends with a multisite [[/base]/child1] root.
- // e.g., `http/example-com[[-base]-child1][[/base]/child1]` is a root directory.
- $cache_path .= 'index/'; // Use an index suffix.
+ if (!($flags & CACHE_PATH_NO_USER)) {
+ if ($with_user_token !== '') {
+ $cache_path = rtrim($cache_path, '/').'.u/'.str_replace(['/', '\\'], '-', $with_user_token).'/';
+ }
}
- } elseif (!($flags & CACHE_PATH_NO_PATH_INDEX)) {
- $cache_path .= 'index/';
- }
- }
- if ($self->isExtensionLoaded('mbstring') && mb_check_encoding($cache_path, 'UTF-8')) {
- $cache_path = mb_strtolower($cache_path, 'UTF-8');
- }
- $cache_path = str_replace('.', '-', strtolower($cache_path));
-
- if (!($flags & CACHE_PATH_NO_QUV)) {
- if (!($flags & CACHE_PATH_NO_QUERY)) {
- if (isset($url_parts['query']) && $url_parts['query'] !== '') {
- $cache_path = rtrim($cache_path, '/').'.q/'.md5($url_parts['query']).'/';
+ if (!($flags & CACHE_PATH_NO_VSALT)) {
+ if ($with_version_salt !== '') {
+ $cache_path = rtrim($cache_path, '/').'.v/'.str_replace(['/', '\\'], '-', $with_version_salt).'/';
+ }
}
}
- if (!($flags & CACHE_PATH_NO_USER)) {
- if ($with_user_token !== '') {
- $cache_path = rtrim($cache_path, '/').'.u/'.str_replace(array('/', '\\'), '-', $with_user_token).'/';
- }
+ $cache_path = trim(preg_replace(['/\/+/', '/\.+/'], ['/', '.'], $cache_path), '/');
+
+ if ($flags & CACHE_PATH_ALLOW_WD_REGEX) {
+ $cache_path = preg_replace('/[^a-z0-9\/.*\^$]/i', '-', $cache_path);
+ } elseif ($flags & CACHE_PATH_ALLOW_WILDCARDS) {
+ $cache_path = preg_replace('/[^a-z0-9\/.*]/i', '-', $cache_path);
+ } else {
+ $cache_path = preg_replace('/[^a-z0-9\/.]/i', '-', $cache_path);
}
- if (!($flags & CACHE_PATH_NO_VSALT)) {
- if ($with_version_salt !== '') {
- $cache_path = rtrim($cache_path, '/').'.v/'.str_replace(array('/', '\\'), '-', $with_version_salt).'/';
- }
+ if (!($flags & CACHE_PATH_NO_EXT)) {
+ $cache_path .= '.html';
}
+ return $cache_path;
}
- $cache_path = trim(preg_replace(array('/\/+/', '/\.+/'), array('/', '.'), $cache_path), '/');
-
- if ($flags & CACHE_PATH_ALLOW_WD_REGEX) {
- $cache_path = preg_replace('/[^a-z0-9\/.*\^$]/i', '-', $cache_path);
- } elseif ($flags & CACHE_PATH_ALLOW_WILDCARDS) {
- $cache_path = preg_replace('/[^a-z0-9\/.*]/i', '-', $cache_path);
- } else {
- $cache_path = preg_replace('/[^a-z0-9\/.]/i', '-', $cache_path);
- }
- if (!($flags & CACHE_PATH_NO_EXT)) {
- $cache_path .= '.html';
- }
- return $cache_path;
-};
-
-/*
- * Regex pattern for a call to `deleteFilesFromCacheDir()`.
- *
- * @since 151114 Updated to support an arbitrary URL instead of a regex frag.
- *
- * @param string $url The input URL to convert. This CAN be left empty when necessary.
- * If empty, the final regex pattern will be `/^'.$regex_suffix_frag.'/i`.
- * If empty, it's a good idea to start `$regex_suffix_frag` with `.*?`.
- *
- * @param string $regex_suffix_frag Regex fragment to come after the `$regex_frag`.
- * Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
- * Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
- * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
- *
- * @return string Regex pattern for a call to `deleteFilesFromCacheDir()`.
- */
-$self->buildCachePathRegex = function ($url, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG) use ($self) {
- $url = trim((string) $url);
- $regex_suffix_frag = $self->cachePathRegexSuffixFrag($regex_suffix_frag);
- $cache_path_regex = ''; // Initialize regex.
-
- if ($url) {
- $flags = CACHE_PATH_NO_SCHEME // Scheme added below.
- | CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
- $cache_path = $self->buildCachePath($url, '', '', $flags); // Without the scheme.
- $cache_path_regex = isset($cache_path[0]) ? '\/https?\/'.preg_quote($cache_path, '/') : '';
- }
- return '/^'.$cache_path_regex.$regex_suffix_frag.'/i';
-};
-
-/*
- * Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
- *
- * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
- *
- * @param string $url The input URL to convert. This CAN be left empty when necessary.
- * If empty, the final regex pattern will be `/^'.$regex_suffix_frag.'/i`.
- * If empty, it's a good idea to start `$regex_suffix_frag` with `.*?`.
- *
- * @param string $regex_suffix_frag Regex fragment to come after the relative cache/path regex frag.
- * Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
- * Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
- * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
- *
- * @return string Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
- */
-$self->buildHostCachePathRegex = function ($url, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG) use ($self) {
- $url = trim((string) $url);
- $regex_suffix_frag = $self->cachePathRegexSuffixFrag($regex_suffix_frag);
- $abs_relative_cache_path_regex = ''; // Initialize regex.
- $is_url_domain_mapped = false; // Initialize.
-
- if ($url) {
- if (is_multisite() && $self->canConsiderDomainMapping()) {
- // Shortest possible URI; i.e., consider domain mapping.
- $url = $self->domainMappingUrlFilter($url);
- $is_url_domain_mapped = $url && $self->domainMappingBlogId($url);
+
+ /*
+ * Regex pattern for a call to `deleteFilesFromCacheDir()`.
+ *
+ * @since 151114 Updated to support an arbitrary URL instead of a regex frag.
+ *
+ * @param string $url The input URL to convert. This CAN be left empty when necessary.
+ * If empty, the final regex pattern will be `/^'.$regex_suffix_frag.'/i`.
+ * If empty, it's a good idea to start `$regex_suffix_frag` with `.*?`.
+ *
+ * @param string $regex_suffix_frag Regex fragment to come after the `$regex_frag`.
+ * Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
+ * Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
+ * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
+ *
+ * @return string Regex pattern for a call to `deleteFilesFromCacheDir()`.
+ */
+ public function buildCachePathRegex($url, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ {
+ $url = trim((string) $url);
+ $regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
+ $cache_path_regex = ''; // Initialize regex.
+
+ if ($url) {
+ $flags = CACHE_PATH_NO_SCHEME // Scheme added below.
+ | CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
+ $cache_path = $this->buildCachePath($url, '', '', $flags); // Without the scheme.
+ $cache_path_regex = isset($cache_path[0]) ? '\/https?\/'.preg_quote($cache_path, '/') : '';
}
- if ($url && ($url_parts = $self->parseUrl($url)) && !empty($url_parts['host'])) {
- $flags = CACHE_PATH_NO_SCHEME | CACHE_PATH_NO_HOST
- | CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
+ return '/^'.$cache_path_regex.$regex_suffix_frag.'/i';
+ }
- $host_base_dir_tokens = $self->hostBaseDirTokens(false, $is_url_domain_mapped, !empty($url_parts['path']) ? $url_parts['path'] : '/');
- $host_url = rtrim('http://'.$url_parts['host'].$host_base_dir_tokens, '/');
- $host_cache_path = $self->buildCachePath($host_url, '', '', $flags);
+ /*
+ * Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
+ *
+ * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
+ *
+ * @param string $url The input URL to convert. This CAN be left empty when necessary.
+ * If empty, the final regex pattern will be `/^'.$regex_suffix_frag.'/i`.
+ * If empty, it's a good idea to start `$regex_suffix_frag` with `.*?`.
+ *
+ * @param string $regex_suffix_frag Regex fragment to come after the relative cache/path regex frag.
+ * Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
+ * Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
+ * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
+ *
+ * @return string Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
+ */
+ public function buildHostCachePathRegex($url, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ {
+ $url = trim((string) $url);
+ $regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
+ $abs_relative_cache_path_regex = ''; // Initialize regex.
+ $is_url_domain_mapped = false; // Initialize.
+
+ if ($url) {
+ if (is_multisite() && $this->canConsiderDomainMapping()) {
+ // Shortest possible URI; i.e., consider domain mapping.
+ $url = $this->domainMappingUrlFilter($url);
+ $is_url_domain_mapped = $url && $this->domainMappingBlogId($url);
+ }
+ if ($url && ($url_parts = $this->parseUrl($url)) && !empty($url_parts['host'])) {
+ $flags = CACHE_PATH_NO_SCHEME | CACHE_PATH_NO_HOST
+ | CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
+
+ $host_base_dir_tokens = $this->hostBaseDirTokens(false, $is_url_domain_mapped, !empty($url_parts['path']) ? $url_parts['path'] : '/');
+ $host_url = rtrim('http://'.$url_parts['host'].$host_base_dir_tokens, '/');
+ $host_cache_path = $this->buildCachePath($host_url, '', '', $flags);
- $cache_path = $self->buildCachePath($url, '', '', $flags);
- $relative_cache_path = preg_replace('/^'.preg_quote($host_cache_path, '/').'(?:\/|$)/i', '', $cache_path);
+ $cache_path = $this->buildCachePath($url, '', '', $flags);
+ $relative_cache_path = preg_replace('/^'.preg_quote($host_cache_path, '/').'(?:\/|$)/i', '', $cache_path);
- $abs_relative_cache_path = isset($relative_cache_path[0]) ? '/'.$relative_cache_path : '';
- $abs_relative_cache_path_regex = isset($abs_relative_cache_path[0]) ? preg_quote($abs_relative_cache_path, '/') : '';
+ $abs_relative_cache_path = isset($relative_cache_path[0]) ? '/'.$relative_cache_path : '';
+ $abs_relative_cache_path_regex = isset($abs_relative_cache_path[0]) ? preg_quote($abs_relative_cache_path, '/') : '';
+ }
}
+ return '/^'.$abs_relative_cache_path_regex.$regex_suffix_frag.'/i';
}
- return '/^'.$abs_relative_cache_path_regex.$regex_suffix_frag.'/i';
-};
-
-/*
- * Regex pattern for a call to `deleteFilesFromCacheDir()`.
- *
- * @since 151114 Improving watered-down regex syntax.
- *
- * @param string $url The input URL to convert. This CAN be left empty when necessary.
- * This may also contain watered-down regex; i.e., `*^$` characters are OK here.
- * However, `^$` are discarded, as they are unnecessary in this context.
- *
- * If empty, the final regex pattern will be `/^'.$regex_suffix_frag.'/i`.
- * If empty, it's a good idea to start `$regex_suffix_frag` with `.*?`.
- *
- * @param string $regex_suffix_frag Regex fragment to come after the `$regex_frag`.
- * Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
- * Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
- * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
- *
- * @return string Regex pattern for a call to `deleteFilesFromCacheDir()`.
- */
-$self->buildCachePathRegexFromWcUrl = function ($url, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG) use ($self) {
- $url = trim((string) $url, '^$');
- $regex_suffix_frag = $self->cachePathRegexSuffixFrag($regex_suffix_frag);
- $cache_path_regex = ''; // Initialize regex.
-
- if ($url) { // After `^$` trimming above.
- $flags = CACHE_PATH_ALLOW_WILDCARDS | CACHE_PATH_NO_SCHEME
- | CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
- $cache_path = $self->buildCachePath($url, '', '', $flags); // Without the scheme.
- $cache_path_regex = isset($cache_path[0]) ? '\/https?\/'.$self->wdRegexToActualRegexFrag($cache_path) : '';
- }
- return '/^'.$cache_path_regex.$regex_suffix_frag.'/i';
-};
-
-/*
- * Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
- *
- * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
- *
- * @param string $uris A line-delimited list of URIs. These may contain `*^$` also.
- * However, `^$` are discarded, as they are unnecessary in this context.
- *
- * @param string $regex_suffix_frag Regex fragment to come after each relative cache/path.
- * Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
- * Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
- * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
- *
- * @return string Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
- */
-$self->buildHostCachePathRegexFragsFromWcUris = function ($uris, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG) use ($self) {
- $uris = trim((string) $uris);
- $regex_suffix_frag = $self->cachePathRegexSuffixFrag($regex_suffix_frag);
-
- $_self = $self; // Reference for the closure below.
- $flags = CACHE_PATH_ALLOW_WILDCARDS | CACHE_PATH_NO_SCHEME | CACHE_PATH_NO_HOST
- | CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
-
- $host = 'doesnt-matter.foo.bar';
- $host_url = rtrim('http://'.$host, '/');
- $host_cache_path = $self->buildCachePath($host_url, '', '', $flags);
- $uri_patterns = array_unique(preg_split('/['."\r\n".']+/', $uris, -1, PREG_SPLIT_NO_EMPTY));
-
- foreach ($uri_patterns as $_key => &$_uri_pattern) {
- if (($_uri_pattern = trim($_uri_pattern, '^$'))) {
- $_cache_path = $_self->buildCachePath($host_url.'/'.trim($_uri_pattern, '/'), '', '', $flags);
- $_relative_cache_path = preg_replace('/^'.preg_quote($host_cache_path, '/').'(?:\/|$)/i', '', $_cache_path);
- $_uri_pattern = $self->wdRegexToActualRegexFrag($_relative_cache_path);
+
+ /*
+ * Regex pattern for a call to `deleteFilesFromCacheDir()`.
+ *
+ * @since 151114 Improving watered-down regex syntax.
+ *
+ * @param string $url The input URL to convert. This CAN be left empty when necessary.
+ * This may also contain watered-down regex; i.e., `*^$` characters are OK here.
+ * However, `^$` are discarded, as they are unnecessary in this context.
+ *
+ * If empty, the final regex pattern will be `/^'.$regex_suffix_frag.'/i`.
+ * If empty, it's a good idea to start `$regex_suffix_frag` with `.*?`.
+ *
+ * @param string $regex_suffix_frag Regex fragment to come after the `$regex_frag`.
+ * Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
+ * Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
+ * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
+ *
+ * @return string Regex pattern for a call to `deleteFilesFromCacheDir()`.
+ */
+ public function buildCachePathRegexFromWcUrl($url, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ {
+ $url = trim((string) $url, '^$');
+ $regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
+ $cache_path_regex = ''; // Initialize regex.
+
+ if ($url) { // After `^$` trimming above.
+ $flags = CACHE_PATH_ALLOW_WILDCARDS | CACHE_PATH_NO_SCHEME
+ | CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
+ $cache_path = $this->buildCachePath($url, '', '', $flags); // Without the scheme.
+ $cache_path_regex = isset($cache_path[0]) ? '\/https?\/'.$this->wdRegexToActualRegexFrag($cache_path) : '';
}
- if (!$_uri_pattern) {
- unset($uri_patterns[$_key]); // Remove it.
+ return '/^'.$cache_path_regex.$regex_suffix_frag.'/i';
+ }
+
+ /*
+ * Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
+ *
+ * @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
+ *
+ * @param string $uris A line-delimited list of URIs. These may contain `*^$` also.
+ * However, `^$` are discarded, as they are unnecessary in this context.
+ *
+ * @param string $regex_suffix_frag Regex fragment to come after each relative cache/path.
+ * Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
+ * Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
+ * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
+ *
+ * @return string Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
+ */
+ public function buildHostCachePathRegexFragsFromWcUris($uris, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ {
+ $uris = trim((string) $uris);
+ $regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
+
+ $_self = $self; // Reference for the closure below.
+ $flags = CACHE_PATH_ALLOW_WILDCARDS | CACHE_PATH_NO_SCHEME | CACHE_PATH_NO_HOST
+ | CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
+
+ $host = 'doesnt-matter.foo.bar';
+ $host_url = rtrim('http://'.$host, '/');
+ $host_cache_path = $this->buildCachePath($host_url, '', '', $flags);
+ $uri_patterns = array_unique(preg_split('/['."\r\n".']+/', $uris, -1, PREG_SPLIT_NO_EMPTY));
+
+ foreach ($uri_patterns as $_key => &$_uri_pattern) {
+ if (($_uri_pattern = trim($_uri_pattern, '^$'))) {
+ $_cache_path = $_self->buildCachePath($host_url.'/'.trim($_uri_pattern, '/'), '', '', $flags);
+ $_relative_cache_path = preg_replace('/^'.preg_quote($host_cache_path, '/').'(?:\/|$)/i', '', $_cache_path);
+ $_uri_pattern = $this->wdRegexToActualRegexFrag($_relative_cache_path);
+ }
+ if (!$_uri_pattern) {
+ unset($uri_patterns[$_key]); // Remove it.
+ }
}
+ unset($_key, $_uri_pattern, $_cache_path, $_relative_cache_path); // Housekeeping.
+
+ return $uri_patterns ? '(?:'.implode('|', array_unique($uri_patterns)).')'.$regex_suffix_frag : '';
+ }
+
+ /*
+ * Regex pattern for a call to `deleteFilesFromCacheDir()`.
+ *
+ * @since 151114 Moving this low-level routine into a method of a different name.
+ *
+ * @param string $regex_frag A regex fragment. This CAN be left empty when necessary.
+ * If empty, the final regex pattern will be `/^'.$regex_suffix_frag.'/i`.
+ * If empty, it's a good idea to start `$regex_suffix_frag` with `.*?`.
+ *
+ * @param string $regex_suffix_frag Regex fragment to come after the `$regex_frag`.
+ * Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
+ * Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
+ * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
+ *
+ * @return string Regex pattern for a call to `deleteFilesFromCacheDir()`.
+ */
+ public function assembleCachePathRegex($regex_frag, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ {
+ $regex_frag = (string) $regex_frag;
+ $regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
+
+ return '/^'.$regex_frag.$regex_suffix_frag.'/i';
}
- unset($_key, $_uri_pattern, $_cache_path, $_relative_cache_path); // Housekeeping.
-
- return $uri_patterns ? '(?:'.implode('|', array_unique($uri_patterns)).')'.$regex_suffix_frag : '';
-};
-
-/*
- * Regex pattern for a call to `deleteFilesFromCacheDir()`.
- *
- * @since 151114 Moving this low-level routine into a method of a different name.
- *
- * @param string $regex_frag A regex fragment. This CAN be left empty when necessary.
- * If empty, the final regex pattern will be `/^'.$regex_suffix_frag.'/i`.
- * If empty, it's a good idea to start `$regex_suffix_frag` with `.*?`.
- *
- * @param string $regex_suffix_frag Regex fragment to come after the `$regex_frag`.
- * Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
- * Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
- * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
- *
- * @return string Regex pattern for a call to `deleteFilesFromCacheDir()`.
- */
-$self->assembleCachePathRegex = function ($regex_frag, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG) use ($self) {
- $regex_frag = (string) $regex_frag;
- $regex_suffix_frag = $self->cachePathRegexSuffixFrag($regex_suffix_frag);
-
- return '/^'.$regex_frag.$regex_suffix_frag.'/i';
-};
+}
diff --git a/src/includes/traits/Shared/ConditionalUtils.php b/src/includes/traits/Shared/ConditionalUtils.php
index 30d28400..31003526 100644
--- a/src/includes/traits/Shared/ConditionalUtils.php
+++ b/src/includes/traits/Shared/ConditionalUtils.php
@@ -1,379 +1,399 @@
'die',
- 'echo' => 'echo',
- 'empty' => 'empty',
- 'exit' => 'exit',
- 'eval' => 'eval',
- 'include' => 'include',
- 'include_once' => 'include_once',
- 'isset' => 'isset',
- 'list' => 'list',
- 'require' => 'require',
- 'require_once' => 'require_once',
- 'return' => 'return',
- 'print' => 'print',
- 'unset' => 'unset',
- '__halt_compiler' => '__halt_compiler',
-];
+trait ConditionalUtils {
+ /**
+ * PHP's language constructs.
+ *
+ * @type array PHP's language constructs.
+ * Keys are currently unimportant. Subject to change.
+ *
+ * @since 160222 First documented version.
+ */
+ public $php_constructs = [
+ 'die' => 'die',
+ 'echo' => 'echo',
+ 'empty' => 'empty',
+ 'exit' => 'exit',
+ 'eval' => 'eval',
+ 'include' => 'include',
+ 'include_once' => 'include_once',
+ 'isset' => 'isset',
+ 'list' => 'list',
+ 'require' => 'require',
+ 'require_once' => 'require_once',
+ 'return' => 'return',
+ 'print' => 'print',
+ 'unset' => 'unset',
+ '__halt_compiler' => '__halt_compiler',
+ ];
-/*
- * Is AdvancedCache class?
- *
- * @since 150821 Improving multisite compat.
- *
- * @return bool `TRUE` if this is the AdvancedCache class.
- */
-$self->isAdvancedCache = function () use ($self) {
- return $self instanceof AdvancedCache;
-};
-
-/*
- * Is Plugin class?
- *
- * @since 150821 Improving multisite compat.
- *
- * @return bool `TRUE` if this is the Plugin class.
- */
-$self->isPlugin = function () use ($self) {
- return $self instanceof Plugin;
-};
-
-/*
- * Is the current request method `POST`, `PUT` or `DELETE`?
- *
- * @since 150422 Rewrite.
- *
- * @return boolean `TRUE` if current request method is `POST`, `PUT` or `DELETE`.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->isPostPutDeleteRequest = function () use ($self) {
- if (!is_null($is = &$self->staticKey('isPostPutDeleteRequest'))) {
- return $is; // Already cached this.
+ /*
+ * Is AdvancedCache class?
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @return bool `TRUE` if this is the AdvancedCache class.
+ */
+ public function isAdvancedCache()
+ {
+ return $self instanceof AdvancedCache;
}
- if (!empty($_POST)) {
- return ($is = true);
+
+ /*
+ * Is Plugin class?
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @return bool `TRUE` if this is the Plugin class.
+ */
+ public function isPlugin()
+ {
+ return $self instanceof Plugin;
}
- if (!empty($_SERVER['REQUEST_METHOD']) && is_string($_SERVER['REQUEST_METHOD'])) {
- if (in_array(strtoupper($_SERVER['REQUEST_METHOD']), array('POST', 'PUT', 'DELETE'), true)) {
+
+ /*
+ * Is the current request method `POST`, `PUT` or `DELETE`?
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return boolean `TRUE` if current request method is `POST`, `PUT` or `DELETE`.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function isPostPutDeleteRequest()
+ {
+ if (!is_null($is = &$this->staticKey('isPostPutDeleteRequest'))) {
+ return $is; // Already cached this.
+ }
+ if (!empty($_POST)) {
return ($is = true);
}
+ if (!empty($_SERVER['REQUEST_METHOD']) && is_string($_SERVER['REQUEST_METHOD'])) {
+ if (in_array(strtoupper($_SERVER['REQUEST_METHOD']), ['POST', 'PUT', 'DELETE'], true)) {
+ return ($is = true);
+ }
+ }
+ return ($is = false);
}
- return ($is = false);
-};
-/*
- * Does the current request include an uncacheable query string?
- *
- * @since 151002 Improving Nginx support.
- *
- * @return boolean True if request includes an uncacheable query string.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->requestContainsUncacheableQueryVars = function () use ($self) {
- if (!is_null($is = &$self->staticKey('requestContainsUncacheableQueryVars'))) {
- return $is; // Already cached this.
- }
- if (!empty($_GET) || !empty($_SERVER['QUERY_STRING'])) {
- $_get_count = !empty($_GET) ? count($_GET) : 0;
- $is_abc_only = $_get_count === 1 && isset($_GET[strtolower(SHORT_NAME).'ABC']);
- $is_nginx_q_only = $_get_count === 1 && isset($_GET['q']) && $self->isNginx();
- $is_ac_get_var_true = isset($_GET[strtolower(SHORT_NAME).'AC']) && filter_var($_GET[strtolower(SHORT_NAME).'AC'], FILTER_VALIDATE_BOOLEAN);
+ /*
+ * Does the current request include an uncacheable query string?
+ *
+ * @since 151002 Improving Nginx support.
+ *
+ * @return boolean True if request includes an uncacheable query string.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function requestContainsUncacheableQueryVars()
+ {
+ if (!is_null($is = &$this->staticKey('requestContainsUncacheableQueryVars'))) {
+ return $is; // Already cached this.
+ }
+ if (!empty($_GET) || !empty($_SERVER['QUERY_STRING'])) {
+ $_get_count = !empty($_GET) ? count($_GET) : 0;
+ $is_abc_only = $_get_count === 1 && isset($_GET[strtolower(SHORT_NAME).'ABC']);
+ $is_nginx_q_only = $_get_count === 1 && isset($_GET['q']) && $this->isNginx();
+ $is_ac_get_var_true = isset($_GET[strtolower(SHORT_NAME).'AC']) && filter_var($_GET[strtolower(SHORT_NAME).'AC'], FILTER_VALIDATE_BOOLEAN);
- if (!$is_abc_only && !$is_nginx_q_only && !$is_ac_get_var_true) {
- return ($is = true);
+ if (!$is_abc_only && !$is_nginx_q_only && !$is_ac_get_var_true) {
+ return ($is = true);
+ }
}
+ return ($is = false);
}
- return ($is = false);
-};
-/*
- * Is the current request method is uncacheable?
- *
- * @since 150422 Rewrite.
- *
- * @return boolean `TRUE` if current request method is uncacheable.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->isUncacheableRequestMethod = function () use ($self) {
- if (!is_null($is = &$self->staticKey('isUncacheableRequestMethod'))) {
- return $is; // Already cached this.
- }
- if (!empty($_POST)) {
- return ($is = true);
- }
- if (!empty($_SERVER['REQUEST_METHOD']) && is_string($_SERVER['REQUEST_METHOD'])) {
- if (!in_array(strtoupper($_SERVER['REQUEST_METHOD']), array('GET'), true)) {
+ /*
+ * Is the current request method is uncacheable?
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return boolean `TRUE` if current request method is uncacheable.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function isUncacheableRequestMethod()
+ {
+ if (!is_null($is = &$this->staticKey('isUncacheableRequestMethod'))) {
+ return $is; // Already cached this.
+ }
+ if (!empty($_POST)) {
return ($is = true);
}
+ if (!empty($_SERVER['REQUEST_METHOD']) && is_string($_SERVER['REQUEST_METHOD'])) {
+ if (!in_array(strtoupper($_SERVER['REQUEST_METHOD']), ['GET'], true)) {
+ return ($is = true);
+ }
+ }
+ return ($is = false);
}
- return ($is = false);
-};
-/*
- * Should the current user should be considered a logged-in user?
- *
- * @since 150422 Rewrite.
- *
- * @return boolean `TRUE` if current user should be considered a logged-in user.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->isLikeUserLoggedIn = function () use ($self) {
- if (!is_null($is = &$self->staticKey('isLikeUserLoggedIn'))) {
- return $is; // Already cached this.
- }
- if (defined('SID') && SID) {
- return ($is = true); // Session ID.
- }
- if (empty($_COOKIE)) {
- return ($is = false); // No cookies.
- }
- $regex_logged_in_cookies = '/^'; // Initialize.
+ /*
+ * Should the current user should be considered a logged-in user?
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return boolean `TRUE` if current user should be considered a logged-in user.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function isLikeUserLoggedIn()
+ {
+ if (!is_null($is = &$this->staticKey('isLikeUserLoggedIn'))) {
+ return $is; // Already cached this.
+ }
+ if (defined('SID') && SID) {
+ return ($is = true); // Session ID.
+ }
+ if (empty($_COOKIE)) {
+ return ($is = false); // No cookies.
+ }
+ $regex_logged_in_cookies = '/^'; // Initialize.
- if (defined('LOGGED_IN_COOKIE') && LOGGED_IN_COOKIE) {
- $regex_logged_in_cookies .= preg_quote(LOGGED_IN_COOKIE, '/');
- } else { // Use the default hard-coded cookie prefix.
- $regex_logged_in_cookies .= 'wordpress_logged_in_';
- }
- $regex_logged_in_cookies .= '|comment_author_';
- $regex_logged_in_cookies .= '|wp[_\-]postpass_';
+ if (defined('LOGGED_IN_COOKIE') && LOGGED_IN_COOKIE) {
+ $regex_logged_in_cookies .= preg_quote(LOGGED_IN_COOKIE, '/');
+ } else { // Use the default hard-coded cookie prefix.
+ $regex_logged_in_cookies .= 'wordpress_logged_in_';
+ }
+ $regex_logged_in_cookies .= '|comment_author_';
+ $regex_logged_in_cookies .= '|wp[_\-]postpass_';
- $regex_logged_in_cookies .= '/'; // Close regex.
+ $regex_logged_in_cookies .= '/'; // Close regex.
- foreach ($_COOKIE as $_key => $_value) {
- if ($_value && preg_match($regex_logged_in_cookies, $_key)) {
- return ($is = true); // Like a logged-in user.
+ foreach ($_COOKIE as $_key => $_value) {
+ if ($_value && preg_match($regex_logged_in_cookies, $_key)) {
+ return ($is = true); // Like a logged-in user.
+ }
}
- } unset($_key, $_value); // Housekeeping.
-
- return ($is = false);
-};
+ unset($_key, $_value); // Housekeeping.
-/*
- * Are we in a LOCALHOST environment?
- *
- * @since 150422 Rewrite.
- *
- * @return boolean `TRUE` if we are in a LOCALHOST environment.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->isLocalhost = function () use ($self) {
- if (!is_null($is = &$self->staticKey('isLocalhost'))) {
- return $is; // Already cached this.
+ return ($is = false);
}
- if (defined('LOCALHOST')) {
- return ($is = (boolean) LOCALHOST);
- }
- if (preg_match('/\b(?:localhost|127\.0\.0\.1)\b/i', $self->hostToken())) {
- return ($is = true);
- }
- return ($is = false);
-};
-/*[pro strip-from="lite"]*/
-/*
- * Is the current request for the Auto-Cache Engine?
- *
- * @since 150422 Rewrite.
- *
- * @return boolean `TRUE` if the current request is for the Auto-Cache Engine.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->isAutoCacheEngine = function () use ($self) {
- if (!is_null($is = &$self->staticKey('isAutoCacheEngine'))) {
- return $is; // Already cached this.
- }
- if (!empty($_SERVER['HTTP_USER_AGENT']) && is_string($_SERVER['HTTP_USER_AGENT'])) {
- if (stripos($_SERVER['HTTP_USER_AGENT'], GLOBAL_NS) !== false) {
+ /*
+ * Are we in a LOCALHOST environment?
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return boolean `TRUE` if we are in a LOCALHOST environment.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function isLocalhost()
+ {
+ if (!is_null($is = &$this->staticKey('isLocalhost'))) {
+ return $is; // Already cached this.
+ }
+ if (defined('LOCALHOST')) {
+ return ($is = (boolean) LOCALHOST);
+ }
+ if (preg_match('/\b(?:localhost|127\.0\.0\.1)\b/i', $this->hostToken())) {
return ($is = true);
}
+ return ($is = false);
}
- return ($is = false);
-};
-/*[/pro]*/
-/*
- * Is the current request for a feed?
- *
- * @since 150422 Rewrite.
- *
- * @return boolean `TRUE` if the current request is for a feed.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->isFeed = function () use ($self) {
- if (!is_null($is = &$self->staticKey('isFeed'))) {
- return $is; // Already cached this.
- }
- if (isset($_REQUEST['feed'])) {
- return ($is = true);
+ /*[pro strip-from="lite"]*/
+ /*
+ * Is the current request for the Auto-Cache Engine?
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return boolean `TRUE` if the current request is for the Auto-Cache Engine.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function isAutoCacheEngine()
+ {
+ if (!is_null($is = &$this->staticKey('isAutoCacheEngine'))) {
+ return $is; // Already cached this.
+ }
+ if (!empty($_SERVER['HTTP_USER_AGENT']) && is_string($_SERVER['HTTP_USER_AGENT'])) {
+ if (stripos($_SERVER['HTTP_USER_AGENT'], GLOBAL_NS) !== false) {
+ return ($is = true);
+ }
+ }
+ return ($is = false);
}
- if (!empty($_SERVER['REQUEST_URI']) && is_string($_SERVER['REQUEST_URI'])) {
- if (preg_match('/\/feed(?:[\/?]|$)/', $_SERVER['REQUEST_URI'])) {
+ /*[/pro]*/
+
+ /*
+ * Is the current request for a feed?
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return boolean `TRUE` if the current request is for a feed.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function isFeed()
+ {
+ if (!is_null($is = &$this->staticKey('isFeed'))) {
+ return $is; // Already cached this.
+ }
+ if (isset($_REQUEST['feed'])) {
return ($is = true);
}
+ if (!empty($_SERVER['REQUEST_URI']) && is_string($_SERVER['REQUEST_URI'])) {
+ if (preg_match('/\/feed(?:[\/?]|$)/', $_SERVER['REQUEST_URI'])) {
+ return ($is = true);
+ }
+ }
+ return ($is = false);
}
- return ($is = false);
-};
-/*
- * Is a document/string an HTML/XML doc; or no?
- *
- * @since 150422 Rewrite.
- *
- * @param string $doc Input string/document to check.
- *
- * @return boolean True if `$doc` is an HTML/XML doc type.
- */
-$self->isHtmlXmlDoc = function ($doc) use ($self) {
- $doc = trim((string) $doc);
- $doc_hash = sha1($doc);
+ /*
+ * Is a document/string an HTML/XML doc; or no?
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $doc Input string/document to check.
+ *
+ * @return boolean True if `$doc` is an HTML/XML doc type.
+ */
+ public function isHtmlXmlDoc($doc)
+ {
+ $doc = trim((string) $doc);
+ $doc_hash = sha1($doc);
- if (!is_null($is = &$self->staticKey('isHtmlXmlDoc', $doc_hash))) {
- return $is; // Already cached this.
- }
- if (stripos($doc, '') !== false) {
- return ($is = true);
- }
- if (stripos($doc, 'staticKey('isHtmlXmlDoc', $doc_hash))) {
+ return $is; // Already cached this.
+ }
+ if (stripos($doc, '') !== false) {
+ return ($is = true);
+ }
+ if (stripos($doc, 'hasACacheableContentType = function () use ($self) {
- if (!is_null($is = &$self->staticKey('hasACacheableContentType'))) {
- return $is; // Already cached this.
- }
- foreach ($self->headersList() as $_key => $_header) {
- if (stripos($_header, 'Content-Type:') === 0) {
- $content_type = $_header; // Last one.
+ /*
+ * Does the current request have a cacheable content type?
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return boolean `TRUE` if the current request has a cacheable content type.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ *
+ * @warning Do NOT call upon this method until the end of a script execution.
+ */
+ public function hasACacheableContentType()
+ {
+ if (!is_null($is = &$this->staticKey('hasACacheableContentType'))) {
+ return $is; // Already cached this.
+ }
+ foreach ($this->headersList() as $_key => $_header) {
+ if (stripos($_header, 'Content-Type:') === 0) {
+ $content_type = $_header; // Last one.
+ }
}
- } unset($_key, $_header); // Housekeeping.
+ unset($_key, $_header); // Housekeeping.
- if (isset($content_type[0]) && stripos($content_type, 'html') === false
- && stripos($content_type, 'xml') === false && stripos($content_type, GLOBAL_NS) === false) {
- return ($is = false); // Do NOT cache data sent by scripts serving other MIME types.
+ if (isset($content_type[0]) && stripos($content_type, 'html') === false
+ && stripos($content_type, 'xml') === false && stripos($content_type, GLOBAL_NS) === false
+ ) {
+ return ($is = false); // Do NOT cache data sent by scripts serving other MIME types.
+ }
+ return ($is = true);
}
- return ($is = true);
-};
-/*
- * Does the current request have a cacheable HTTP status code?
- *
- * @since 150422 Rewrite.
- *
- * @return boolean `TRUE` if the current request has a cacheable HTTP status code.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- *
- * @warning Do NOT call upon this method until the end of a script execution.
- */
-$self->hasACacheableStatus = function () use ($self) {
- if (!is_null($is = &$self->staticKey('hasACacheableStatus'))) {
- return $is; // Already cached this.
- }
- if (($http_status = (string) $self->httpStatus()) && $http_status[0] !== '2' && $http_status !== '404') {
- return ($is = false); // A non-2xx & non-404 status code.
- }
- foreach ($self->headersList() as $_key => $_header) {
- if (preg_match('/^(?:Retry\-After\:\s+(?P.+)|Status\:\s+(?P[0-9]+)|HTTP\/[0-9]+(?:\.[0-9]+)?\s+(?P[0-9]+))/i', $_header, $_m)) {
- if (!empty($_m['retry']) || (!empty($_m['status']) && $_m['status'][0] !== '2' && $_m['status'] !== '404')
- || (!empty($_m['http_status']) && $_m['http_status'][0] !== '2' && $_m['http_status'] !== '404')
- ) {
- return ($is = false); // Not a cacheable status.
+ /*
+ * Does the current request have a cacheable HTTP status code?
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return boolean `TRUE` if the current request has a cacheable HTTP status code.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ *
+ * @warning Do NOT call upon this method until the end of a script execution.
+ */
+ public function hasACacheableStatus()
+ {
+ if (!is_null($is = &$this->staticKey('hasACacheableStatus'))) {
+ return $is; // Already cached this.
+ }
+ if (($http_status = (string) $this->httpStatus()) && $http_status[0] !== '2' && $http_status !== '404') {
+ return ($is = false); // A non-2xx & non-404 status code.
+ }
+ foreach ($this->headersList() as $_key => $_header) {
+ if (preg_match('/^(?:Retry\-After\:\s+(?P.+)|Status\:\s+(?P[0-9]+)|HTTP\/[0-9]+(?:\.[0-9]+)?\s+(?P[0-9]+))/i', $_header, $_m)) {
+ if (!empty($_m['retry']) || (!empty($_m['status']) && $_m['status'][0] !== '2' && $_m['status'] !== '404')
+ || (!empty($_m['http_status']) && $_m['http_status'][0] !== '2' && $_m['http_status'] !== '404')
+ ) {
+ return ($is = false); // Not a cacheable status.
+ }
}
}
- } unset($_key, $_header); // Housekeeping.
+ unset($_key, $_header); // Housekeeping.
- return ($is = true);
-};
-
-/*
- * Checks if a PHP extension is loaded up.
- *
- * @since 150422 Rewrite.
- *
- * @param string $extension A PHP extension slug (i.e. extension name).
- *
- * @return boolean `TRUE` if the extension is loaded.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->isExtensionLoaded = function ($extension) use ($self) {
- $extension = (string) $extension;
-
- if (!is_null($is = &$self->staticKey('isExtensionLoaded', $extension))) {
- return $is; // Already cached this.
+ return ($is = true);
}
- return ($is = (boolean) extension_loaded($extension));
-};
-/*
- * Is a particular function possible in every way?
- *
- * @since 150422 Rewrite.
- *
- * @param string $function A PHP function (or user function) to check.
- *
- * @return string `TRUE` if the function is possible.
- *
- * @note This checks (among other things) if the function exists and that it's callable.
- * It also checks the currently configured `disable_functions` and `suhosin.executor.func.blacklist`.
- */
-$self->functionIsPossible = function ($function) use ($self) {
- $function = (string) $function;
+ /*
+ * Checks if a PHP extension is loaded up.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $extension A PHP extension slug (i.e. extension name).
+ *
+ * @return boolean `TRUE` if the extension is loaded.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function isExtensionLoaded($extension)
+ {
+ $extension = (string) $extension;
- if (!is_null($is = &$self->staticKey('functionIsPossible', $function))) {
- return $is; // Already cached this.
+ if (!is_null($is = &$this->staticKey('isExtensionLoaded', $extension))) {
+ return $is; // Already cached this.
+ }
+ return ($is = (boolean) extension_loaded($extension));
}
- if (is_null($disabled_functions = &$self->staticKey('functionIsPossible_disabled_functions'))) {
- $disabled_functions = array(); // Initialize disabled/blacklisted functions.
- if (($disable_functions = trim(ini_get('disable_functions')))) {
- $disabled_functions = array_merge($disabled_functions, preg_split('/[\s;,]+/', strtolower($disable_functions), -1, PREG_SPLIT_NO_EMPTY));
+ /*
+ * Is a particular function possible in every way?
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $function A PHP function (or user function) to check.
+ *
+ * @return string `TRUE` if the function is possible.
+ *
+ * @note This checks (among other things) if the function exists and that it's callable.
+ * It also checks the currently configured `disable_functions` and `suhosin.executor.func.blacklist`.
+ */
+ public function functionIsPossible($function)
+ {
+ $function = (string) $function;
+
+ if (!is_null($is = &$this->staticKey('functionIsPossible', $function))) {
+ return $is; // Already cached this.
}
- if (($blacklist_functions = trim(ini_get('suhosin.executor.func.blacklist')))) {
- $disabled_functions = array_merge($disabled_functions, preg_split('/[\s;,]+/', strtolower($blacklist_functions), -1, PREG_SPLIT_NO_EMPTY));
+ if (is_null($disabled_functions = &$this->staticKey('functionIsPossible_disabled_functions'))) {
+ $disabled_functions = []; // Initialize disabled/blacklisted functions.
+
+ if (($disable_functions = trim(ini_get('disable_functions')))) {
+ $disabled_functions = array_merge($disabled_functions, preg_split('/[\s;,]+/', strtolower($disable_functions), -1, PREG_SPLIT_NO_EMPTY));
+ }
+ if (($blacklist_functions = trim(ini_get('suhosin.executor.func.blacklist')))) {
+ $disabled_functions = array_merge($disabled_functions, preg_split('/[\s;,]+/', strtolower($blacklist_functions), -1, PREG_SPLIT_NO_EMPTY));
+ }
+ if (filter_var(ini_get('suhosin.executor.disable_eval'), FILTER_VALIDATE_BOOLEAN)) {
+ $disabled_functions = array_merge($disabled_functions, ['eval']);
+ }
}
- if(filter_var(ini_get('suhosin.executor.disable_eval'), FILTER_VALIDATE_BOOLEAN)) {
- $disabled_functions = array_merge($disabled_functions, array('eval'));
+ if (!function_exists($function) || !is_callable($function)) {
+ if (!in_array($function, $this->php_constructs, true)) { // A language construct
+ return ($is = false); // Not possible.
+ }
}
- }
- if (!function_exists($function) || !is_callable($function)) {
- if(!in_array($function, $self->php_constructs, true)) { // A language construct
+ if ($disabled_functions && in_array(strtolower($function), $disabled_functions, true)) {
return ($is = false); // Not possible.
}
+ return ($is = true);
}
- if ($disabled_functions && in_array(strtolower($function), $disabled_functions, true)) {
- return ($is = false); // Not possible.
- }
- return ($is = true);
-};
+}
diff --git a/src/includes/traits/Shared/DomainMappingUtils.php b/src/includes/traits/Shared/DomainMappingUtils.php
index 4096ce08..da65988a 100644
--- a/src/includes/traits/Shared/DomainMappingUtils.php
+++ b/src/includes/traits/Shared/DomainMappingUtils.php
@@ -1,264 +1,275 @@
canConsiderDomainMapping = function () use ($self) {
- if (!is_null($can = &$self->staticKey('canConsiderDomainMapping'))) {
- return $can; // Already cached this.
- }
- if (!$self->isAdvancedCache() && is_multisite() && $self->hostBaseToken() === '/'
- && defined('SUNRISE_LOADED') && SUNRISE_LOADED && !empty($GLOBALS['dm_domain'])) {
- return ($can = true); // Can consider.
+trait DomainMappingUtils {
+ /*
+ * Can consider domain mapping?
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @return bool `TRUE` if we can consider domain mapping.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function canConsiderDomainMapping()
+ {
+ if (!is_null($can = &$this->staticKey('canConsiderDomainMapping'))) {
+ return $can; // Already cached this.
+ }
+ if (!$this->isAdvancedCache() && is_multisite() && $this->hostBaseToken() === '/'
+ && defined('SUNRISE_LOADED') && SUNRISE_LOADED && !empty($GLOBALS['dm_domain'])
+ ) {
+ return ($can = true); // Can consider.
+ }
+ return ($can = false); // Cannot consider.
}
- return ($can = false); // Cannot consider.
-};
-/*
- * Domain mapping?
- *
- * @since 150821 Improving multisite compat.
- *
- * @return integer Domain mapping ID; else `0` (false).
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->isDomainMapping = function () use ($self) {
- if (!is_null($is = &$self->staticKey('isDomainMapping'))) {
- return $is; // Already cached this.
- }
- if (!$self->isAdvancedCache() && is_multisite() && $self->canConsiderDomainMapping()
- && defined('DOMAIN_MAPPING') && DOMAIN_MAPPING && !empty($GLOBALS['domain_mapping_id'])) {
- return ($is = (integer) $GLOBALS['domain_mapping_id']); // Blog ID.
+ /*
+ * Domain mapping?
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @return integer Domain mapping ID; else `0` (false).
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function isDomainMapping()
+ {
+ if (!is_null($is = &$this->staticKey('isDomainMapping'))) {
+ return $is; // Already cached this.
+ }
+ if (!$this->isAdvancedCache() && is_multisite() && $this->canConsiderDomainMapping()
+ && defined('DOMAIN_MAPPING') && DOMAIN_MAPPING && !empty($GLOBALS['domain_mapping_id'])
+ ) {
+ return ($is = (integer) $GLOBALS['domain_mapping_id']); // Blog ID.
+ }
+ return ($is = 0); // Not domain mapping.
}
- return ($is = 0); // Not domain mapping.
-};
-/*
- * Filters a URL in order to apply domain mapping.
- *
- * @since 150821 Improving multisite compat.
- *
- * @param string $url The input URL to filter.
- *
- * @return string The filtered URL; else the original URL.
- *
- * @note The return value of this function is NOT cached, but inner portions are.
- */
-$self->domainMappingUrlFilter = function ($url) use ($self) {
- $original_url = (string) $url; // Preserve.
- $url = trim((string) $url);
+ /*
+ * Filters a URL in order to apply domain mapping.
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @param string $url The input URL to filter.
+ *
+ * @return string The filtered URL; else the original URL.
+ *
+ * @note The return value of this function is NOT cached, but inner portions are.
+ */
+ public function domainMappingUrlFilter($url)
+ {
+ $original_url = (string) $url; // Preserve.
+ $url = trim((string) $url);
- if (!is_multisite() || !$self->canConsiderDomainMapping()) {
- return $original_url; // Not possible.
- }
- if (!$url || !($url_parts = $self->parseUrl($url))) {
- return $original_url; // Not possible.
- }
- if (empty($url_parts['host'])) {
- return $original_url; // Not possible.
- }
- $blog_domain = strtolower($url_parts['host']); // In the unfiltered URL.
- $blog_path = $self->hostDirToken(false, false, !empty($url_parts['path']) ? $url_parts['path'] : '/');
+ if (!is_multisite() || !$this->canConsiderDomainMapping()) {
+ return $original_url; // Not possible.
+ }
+ if (!$url || !($url_parts = $this->parseUrl($url))) {
+ return $original_url; // Not possible.
+ }
+ if (empty($url_parts['host'])) {
+ return $original_url; // Not possible.
+ }
+ $blog_domain = strtolower($url_parts['host']); // In the unfiltered URL.
+ $blog_path = $this->hostDirToken(false, false, !empty($url_parts['path']) ? $url_parts['path'] : '/');
- if (!($blog_id = (integer) get_blog_id_from_url($blog_domain, $blog_path))) {
- return $original_url; // Not possible.
- }
- if (!($domain = $self->domainMappingBlogDomain($blog_id)) || $domain === $blog_domain) {
- return $original_url; // Not applicable.
- }
- $url_parts['host'] = $domain; // Filter the URL now.
- if (!empty($url_parts['path']) && $url_parts['path'] !== '/') {
- if (($host_base_dir_tokens = trim($self->hostBaseDirTokens(false, false, $url_parts['path']), '/'))) {
- $url_parts['path'] = preg_replace('/^\/'.preg_quote($host_base_dir_tokens, '/').'(\/|$)/i', '${1}', $url_parts['path']);
+ if (!($blog_id = (integer) get_blog_id_from_url($blog_domain, $blog_path))) {
+ return $original_url; // Not possible.
+ }
+ if (!($domain = $this->domainMappingBlogDomain($blog_id)) || $domain === $blog_domain) {
+ return $original_url; // Not applicable.
}
+ $url_parts['host'] = $domain; // Filter the URL now.
+ if (!empty($url_parts['path']) && $url_parts['path'] !== '/') {
+ if (($host_base_dir_tokens = trim($this->hostBaseDirTokens(false, false, $url_parts['path']), '/'))) {
+ $url_parts['path'] = preg_replace('/^\/'.preg_quote($host_base_dir_tokens, '/').'(\/|$)/i', '${1}', $url_parts['path']);
+ }
+ }
+ return ($url = $this->unParseUrl($url_parts));
}
- return ($url = $self->unParseUrl($url_parts));
-};
-/*
- * Filters a URL in order to remove domain mapping.
- *
- * @since 150821 Improving multisite compat.
- *
- * @param string $url The input URL to filter.
- *
- * @return string The filtered URL; else the original URL.
- *
- * @note The return value of this function is NOT cached, but inner portions are.
- */
-$self->domainMappingReverseUrlFilter = function ($url) use ($self) {
- $original_url = (string) $url; // Preserve.
- $url = trim((string) $url);
+ /*
+ * Filters a URL in order to remove domain mapping.
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @param string $url The input URL to filter.
+ *
+ * @return string The filtered URL; else the original URL.
+ *
+ * @note The return value of this function is NOT cached, but inner portions are.
+ */
+ public function domainMappingReverseUrlFilter($url)
+ {
+ $original_url = (string) $url; // Preserve.
+ $url = trim((string) $url);
- if (!is_multisite() || !$self->canConsiderDomainMapping()) {
- return $original_url; // Not possible.
- }
- if (!$url || !($url_parts = $self->parseUrl($url))) {
- return $original_url; // Not possible.
- }
- if (empty($url_parts['host'])) {
- return $original_url; // Not possible.
- }
- if (!($blog_id = $self->domainMappingBlogId('', $url_parts['host']))) {
- return $original_url; // No a domain in the map.
- }
- if (!($blog_details = $self->blogDetails($blog_id))) {
- return $original_url; // Not possible.
- }
- $url_parts['host'] = $blog_details->domain; // Filter the URL now.
- if (($host_base_dir_tokens = trim($self->hostBaseDirTokens(false, false, $blog_details->path), '/'))) {
- $url_parts['path'] = '/'.$host_base_dir_tokens.'/'.ltrim(@$url_parts['path'], '/');
+ if (!is_multisite() || !$this->canConsiderDomainMapping()) {
+ return $original_url; // Not possible.
+ }
+ if (!$url || !($url_parts = $this->parseUrl($url))) {
+ return $original_url; // Not possible.
+ }
+ if (empty($url_parts['host'])) {
+ return $original_url; // Not possible.
+ }
+ if (!($blog_id = $this->domainMappingBlogId('', $url_parts['host']))) {
+ return $original_url; // No a domain in the map.
+ }
+ if (!($blog_details = $this->blogDetails($blog_id))) {
+ return $original_url; // Not possible.
+ }
+ $url_parts['host'] = $blog_details->domain; // Filter the URL now.
+ if (($host_base_dir_tokens = trim($this->hostBaseDirTokens(false, false, $blog_details->path), '/'))) {
+ $url_parts['path'] = '/'.$host_base_dir_tokens.'/'.ltrim(@$url_parts['path'], '/');
+ }
+ return ($url = $this->unParseUrl($url_parts));
}
- return ($url = $self->unParseUrl($url_parts));
-};
-/*
- * Converts a host into a mapped blog ID.
- *
- * @since 150821 Improving multisite compat.
- *
- * @param string $url URL containing the domain to convert.
- * @param string $domain The domain to convert. Override URL is provided.
- *
- * @return integer The mapped blog ID; else `0` on failure.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->domainMappingBlogId = function ($url = '', $domain = '') use ($self) {
- $domain = (string) $domain;
- $url = $domain ? '' : (string) $url;
+ /*
+ * Converts a host into a mapped blog ID.
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @param string $url URL containing the domain to convert.
+ * @param string $domain The domain to convert. Override URL is provided.
+ *
+ * @return integer The mapped blog ID; else `0` on failure.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function domainMappingBlogId($url = '', $domain = '')
+ {
+ $domain = (string) $domain;
+ $url = $domain ? '' : (string) $url;
- if (!is_multisite() || !$self->canConsiderDomainMapping()) {
- return 0; // Not possible/applicable.
- }
- if ($url === 'network' || $domain === 'network') {
- $domain = (string) get_current_site()->domain;
- }
- if (!$domain && $url && $url !== 'network') {
- $domain = $self->parseUrl($url, PHP_URL_HOST);
- }
- if (!$url && !$domain && ($blog_details = $self->blogDetails())) {
- $domain = $blog_details->domain;
- }
- $domain = strtolower(preg_replace('/^www\./i', '', $domain));
+ if (!is_multisite() || !$this->canConsiderDomainMapping()) {
+ return 0; // Not possible/applicable.
+ }
+ if ($url === 'network' || $domain === 'network') {
+ $domain = (string) get_current_site()->domain;
+ }
+ if (!$domain && $url && $url !== 'network') {
+ $domain = $this->parseUrl($url, PHP_URL_HOST);
+ }
+ if (!$url && !$domain && ($blog_details = $this->blogDetails())) {
+ $domain = $blog_details->domain;
+ }
+ $domain = strtolower(preg_replace('/^www\./i', '', $domain));
- if (!$domain || strpos($domain, '.') === false) {
- return 0; // Not possible.
- }
- if (!is_null($blog_id = &$self->staticKey('domainMappingBlogId', $domain))) {
- return $blog_id; // Already cached this.
- }
- $wpdb = $self->wpdb(); // WordPress database class.
- $suppressing_errors = $wpdb->suppress_errors(); // In case table has not been created yet.
- $enforcing_primary_domain = !get_site_option('dm_no_primary_domain'); // Enforcing primary domain?
+ if (!$domain || strpos($domain, '.') === false) {
+ return 0; // Not possible.
+ }
+ if (!is_null($blog_id = &$this->staticKey('domainMappingBlogId', $domain))) {
+ return $blog_id; // Already cached this.
+ }
+ $wpdb = $this->wpdb(); // WordPress database class.
+ $suppressing_errors = $wpdb->suppress_errors(); // In case table has not been created yet.
+ $enforcing_primary_domain = !get_site_option('dm_no_primary_domain'); // Enforcing primary domain?
+
+ if (!$enforcing_primary_domain) {
+ $blog_id = (integer) $wpdb->get_var('SELECT `blog_id` FROM `'.esc_sql($wpdb->base_prefix.'domain_mapping').'` WHERE `domain` IN(\''.esc_sql('www.'.$domain).'\', \''.esc_sql($domain).'\') ORDER BY CHAR_LENGTH(`domain`) DESC, `active` DESC LIMIT 1');
+ } else {
+ $blog_id = (integer) $wpdb->get_var('SELECT `blog_id` FROM `'.esc_sql($wpdb->base_prefix.'domain_mapping').'` WHERE `domain` IN(\''.esc_sql('www.'.$domain).'\', \''.esc_sql($domain).'\') AND `active` = \'1\' ORDER BY CHAR_LENGTH(`domain`) DESC LIMIT 1');
+ }
+ $wpdb->suppress_errors($suppressing_errors); // Restore.
- if (!$enforcing_primary_domain) {
- $blog_id = (integer) $wpdb->get_var('SELECT `blog_id` FROM `'.esc_sql($wpdb->base_prefix.'domain_mapping').'` WHERE `domain` IN(\''.esc_sql('www.'.$domain).'\', \''.esc_sql($domain).'\') ORDER BY CHAR_LENGTH(`domain`) DESC, `active` DESC LIMIT 1');
- } else {
- $blog_id = (integer) $wpdb->get_var('SELECT `blog_id` FROM `'.esc_sql($wpdb->base_prefix.'domain_mapping').'` WHERE `domain` IN(\''.esc_sql('www.'.$domain).'\', \''.esc_sql($domain).'\') AND `active` = \'1\' ORDER BY CHAR_LENGTH(`domain`) DESC LIMIT 1');
+ return ($blog_id = (integer) $blog_id);
}
- $wpdb->suppress_errors($suppressing_errors); // Restore.
- return ($blog_id = (integer) $blog_id);
-};
+ /*
+ * Converts a blog ID into a mapped domain.
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @param integer $blog_id The blog ID.
+ *
+ * @param boolean $fallback Fallback on blog's domain?
+ *
+ * @return string The mapped domain, else an empty string.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function domainMappingBlogDomain($blog_id = 0, $fallback = false)
+ {
+ if (!is_multisite() || !$this->canConsiderDomainMapping()) {
+ return ''; // Not possible/applicable.
+ }
+ if (($blog_id = (integer) $blog_id) < 0) {
+ $blog_id = (integer) get_current_site()->blog_id;
+ }
+ if (!$blog_id) {
+ $blog_id = (integer) get_current_blog_id();
+ }
+ if (!$blog_id || $blog_id < 0) {
+ return ''; // Not possible.
+ }
+ if (!is_null($domain = &$this->staticKey('domainMappingBlogDomain', $blog_id))) {
+ return $domain; // Already cached this.
+ }
+ $wpdb = $this->wpdb(); // WordPress database class.
+ $suppressing_errors = $wpdb->suppress_errors(); // In case table has not been created yet.
+ $enforcing_primary_domain = !get_site_option('dm_no_primary_domain'); // Enforcing primary domain?
-/*
- * Converts a blog ID into a mapped domain.
- *
- * @since 150821 Improving multisite compat.
- *
- * @param integer $blog_id The blog ID.
- *
- * @param boolean $fallback Fallback on blog's domain?
- *
- * @return string The mapped domain, else an empty string.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->domainMappingBlogDomain = function ($blog_id = 0, $fallback = false) use ($self) {
- if (!is_multisite() || !$self->canConsiderDomainMapping()) {
- return ''; // Not possible/applicable.
- }
- if (($blog_id = (integer) $blog_id) < 0) {
- $blog_id = (integer) get_current_site()->blog_id;
- }
- if (!$blog_id) {
- $blog_id = (integer) get_current_blog_id();
- }
- if (!$blog_id || $blog_id < 0) {
- return ''; // Not possible.
- }
- if (!is_null($domain = &$self->staticKey('domainMappingBlogDomain', $blog_id))) {
- return $domain; // Already cached this.
- }
- $wpdb = $self->wpdb(); // WordPress database class.
- $suppressing_errors = $wpdb->suppress_errors(); // In case table has not been created yet.
- $enforcing_primary_domain = !get_site_option('dm_no_primary_domain'); // Enforcing primary domain?
+ if (!$enforcing_primary_domain) {
+ if ($this->isDomainMapping() === $blog_id) {
+ $domain = $this->hostToken();
+ $domain = preg_replace('/^www\./i', '', $domain);
+ $domain = (string) $wpdb->get_var('SELECT `domain` FROM `'.esc_sql($wpdb->base_prefix.'domain_mapping').'` WHERE `blog_id` = \''.esc_sql($blog_id).'\' AND `domain` IN(\''.esc_sql('www.'.$domain).'\', \''.esc_sql($domain).'\') ORDER BY CHAR_LENGTH(`domain`) DESC LIMIT 1');
+ } elseif (($domains = $this->domainMappingBlogDomains($blog_id))) {
+ $domain = $domains[0]; // Use the first of all possible domains.
+ }
+ } else { // A single primary domain in this case; i.e., `active` = primary.
+ $domain = (string) $wpdb->get_var('SELECT `domain` FROM `'.esc_sql($wpdb->base_prefix.'domain_mapping').'` WHERE `blog_id` = \''.esc_sql($blog_id).'\' AND `domain` IS NOT NULL AND `domain` != \'\' AND `active` = \'1\' LIMIT 1');
+ }
+ if (!$domain && $fallback && ($blog_details = $this->blogDetails($blog_id))) {
+ $domain = $blog_details->domain; // Use original domain.
+ }
+ $wpdb->suppress_errors($suppressing_errors); // Restore.
- if (!$enforcing_primary_domain) {
- if ($self->isDomainMapping() === $blog_id) {
- $domain = $self->hostToken();
- $domain = preg_replace('/^www\./i', '', $domain);
- $domain = (string) $wpdb->get_var('SELECT `domain` FROM `'.esc_sql($wpdb->base_prefix.'domain_mapping').'` WHERE `blog_id` = \''.esc_sql($blog_id).'\' AND `domain` IN(\''.esc_sql('www.'.$domain).'\', \''.esc_sql($domain).'\') ORDER BY CHAR_LENGTH(`domain`) DESC LIMIT 1');
- } elseif (($domains = $self->domainMappingBlogDomains($blog_id))) {
- $domain = $domains[0]; // Use the first of all possible domains.
- }
- } else { // A single primary domain in this case; i.e., `active` = primary.
- $domain = (string) $wpdb->get_var('SELECT `domain` FROM `'.esc_sql($wpdb->base_prefix.'domain_mapping').'` WHERE `blog_id` = \''.esc_sql($blog_id).'\' AND `domain` IS NOT NULL AND `domain` != \'\' AND `active` = \'1\' LIMIT 1');
- }
- if (!$domain && $fallback && ($blog_details = $self->blogDetails($blog_id))) {
- $domain = $blog_details->domain; // Use original domain.
+ return ($domain = strtolower((string) $domain));
}
- $wpdb->suppress_errors($suppressing_errors); // Restore.
- return ($domain = strtolower((string) $domain));
-};
+ /*
+ * Converts a blog ID into mapped domains (plural).
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @param integer $blog_id The blog ID.
+ *
+ * @return array Mapped domains; else an empty array.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function domainMappingBlogDomains($blog_id = 0)
+ {
+ if (!is_multisite() || !$this->canConsiderDomainMapping()) {
+ return []; // Not possible/applicable.
+ }
+ if (($blog_id = (integer) $blog_id) < 0) {
+ $blog_id = (integer) get_current_site()->blog_id;
+ }
+ if (!$blog_id) {
+ $blog_id = (integer) get_current_blog_id();
+ }
+ if (!$blog_id || $blog_id < 0) {
+ return []; // Not possible.
+ }
+ if (!is_null($domains = &$this->staticKey('domainMappingBlogDomains', $blog_id))) {
+ return $domains; // Already cached this.
+ }
+ $wpdb = $this->wpdb(); // WordPress database class.
+ $suppressing_errors = $wpdb->suppress_errors(); // In case table has not been created yet.
+ $enforcing_primary_domain = !get_site_option('dm_no_primary_domain'); // Enforcing primary domain?
-/*
- * Converts a blog ID into mapped domains (plural).
- *
- * @since 150821 Improving multisite compat.
- *
- * @param integer $blog_id The blog ID.
- *
- * @return array Mapped domains; else an empty array.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->domainMappingBlogDomains = function ($blog_id = 0) use ($self) {
- if (!is_multisite() || !$self->canConsiderDomainMapping()) {
- return array(); // Not possible/applicable.
- }
- if (($blog_id = (integer) $blog_id) < 0) {
- $blog_id = (integer) get_current_site()->blog_id;
- }
- if (!$blog_id) {
- $blog_id = (integer) get_current_blog_id();
- }
- if (!$blog_id || $blog_id < 0) {
- return array(); // Not possible.
- }
- if (!is_null($domains = &$self->staticKey('domainMappingBlogDomains', $blog_id))) {
- return $domains; // Already cached this.
- }
- $wpdb = $self->wpdb(); // WordPress database class.
- $suppressing_errors = $wpdb->suppress_errors(); // In case table has not been created yet.
- $enforcing_primary_domain = !get_site_option('dm_no_primary_domain'); // Enforcing primary domain?
+ if (!$enforcing_primary_domain) { // Not enforcing a primary domain, so let's pull all of the domains.
+ $domains = $wpdb->get_col('SELECT `domain` FROM `'.esc_sql($wpdb->base_prefix.'domain_mapping').'` WHERE `blog_id` = \''.esc_sql($blog_id).'\' AND `domain` IS NOT NULL AND `domain` != \'\' ORDER BY `active` DESC');
+ } else { // Primary domains in this case; i.e., `active` = primary.
+ $domains = $wpdb->get_col('SELECT `domain` FROM `'.esc_sql($wpdb->base_prefix.'domain_mapping').'` WHERE `blog_id` = \''.esc_sql($blog_id).'\' AND `domain` IS NOT NULL AND `domain` != \'\' AND `active` = \'1\'');
+ }
+ $wpdb->suppress_errors($suppressing_errors); // Restore.
- if (!$enforcing_primary_domain) { // Not enforcing a primary domain, so let's pull all of the domains.
- $domains = $wpdb->get_col('SELECT `domain` FROM `'.esc_sql($wpdb->base_prefix.'domain_mapping').'` WHERE `blog_id` = \''.esc_sql($blog_id).'\' AND `domain` IS NOT NULL AND `domain` != \'\' ORDER BY `active` DESC');
- } else { // Primary domains in this case; i.e., `active` = primary.
- $domains = $wpdb->get_col('SELECT `domain` FROM `'.esc_sql($wpdb->base_prefix.'domain_mapping').'` WHERE `blog_id` = \''.esc_sql($blog_id).'\' AND `domain` IS NOT NULL AND `domain` != \'\' AND `active` = \'1\'');
+ return ($domains = array_unique(array_map('strtolower', (array) $domains)));
}
- $wpdb->suppress_errors($suppressing_errors); // Restore.
-
- return ($domains = array_unique(array_map('strtolower', (array) $domains)));
-};
+}
diff --git a/src/includes/traits/Shared/EscapeUtils.php b/src/includes/traits/Shared/EscapeUtils.php
index 6d5b6cb6..48606865 100644
--- a/src/includes/traits/Shared/EscapeUtils.php
+++ b/src/includes/traits/Shared/EscapeUtils.php
@@ -1,17 +1,20 @@
`1`.
- *
- * @return string Escaped string; e.g. `Raam\'s the lead developer`.
- */
-$self->escSq = function ($string, $times = 1) use ($self) {
- return str_replace("'", str_repeat('\\', abs($times))."'", (string) $string);
-};
+trait EscapeUtils {
+ /*
+ * Escape single quotes.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $string Input string to escape.
+ * @param integer $times Optional. Defaults to one escape char; e.g. `\'`.
+ * If you need to escape more than once, set this to something > `1`.
+ *
+ * @return string Escaped string; e.g. `Raam\'s the lead developer`.
+ */
+ public function escSq($string, $times = 1)
+ {
+ return str_replace("'", str_repeat('\\', abs($times))."'", (string) $string);
+ }
+}
diff --git a/src/includes/traits/Shared/FsUtils.php b/src/includes/traits/Shared/FsUtils.php
index 880013f9..e56a3810 100644
--- a/src/includes/traits/Shared/FsUtils.php
+++ b/src/includes/traits/Shared/FsUtils.php
@@ -1,323 +1,333 @@
nDirSeps = function ($dir_file, $allow_trailing_slash = false) use ($self) {
- $dir_file = (string) $dir_file;
-
- if (!isset($dir_file[0])) {
- return ''; // Catch empty string.
- }
- if (strpos($dir_file, '://' !== false)) {
- if (preg_match('/^(?P[a-zA-Z0-9]+)\:\/\//', $dir_file, $stream_wrapper)) {
- $dir_file = preg_replace('/^(?P[a-zA-Z0-9]+)\:\/\//', '', $dir_file);
+trait FsUtils {
+ /*
+ * Normalizes directory/file separators.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $dir_file Directory/file path.
+ *
+ * @param boolean $allow_trailing_slash Defaults to FALSE.
+ * If TRUE; and `$dir_file` contains a trailing slash; we'll leave it there.
+ *
+ * @return string Normalized directory/file path.
+ */
+ public function nDirSeps($dir_file, $allow_trailing_slash = false)
+ {
+ $dir_file = (string) $dir_file;
+
+ if (!isset($dir_file[0])) {
+ return ''; // Catch empty string.
}
- }
- if (strpos($dir_file, ':' !== false)) {
- if (preg_match('/^(?P[a-zA-Z])\:[\/\\\\]/', $dir_file)) {
- $dir_file = preg_replace_callback('/^(?P[a-zA-Z])\:[\/\\\\]/', create_function('$m', 'return strtoupper($m[0]);'), $dir_file);
+ if (strpos($dir_file, '://' !== false)) {
+ if (preg_match('/^(?P[a-zA-Z0-9]+)\:\/\//', $dir_file, $stream_wrapper)) {
+ $dir_file = preg_replace('/^(?P[a-zA-Z0-9]+)\:\/\//', '', $dir_file);
+ }
}
- }
- $dir_file = preg_replace('/\/+/', '/', str_replace(array(DIRECTORY_SEPARATOR, '\\', '/'), '/', $dir_file));
- $dir_file = ($allow_trailing_slash) ? $dir_file : rtrim($dir_file, '/'); // Strip trailing slashes.
+ if (strpos($dir_file, ':' !== false)) {
+ if (preg_match('/^(?P[a-zA-Z])\:[\/\\\\]/', $dir_file)) {
+ $dir_file = preg_replace_callback('/^(?P[a-zA-Z])\:[\/\\\\]/', create_function('$m', 'return strtoupper($m[0]);'), $dir_file);
+ }
+ }
+ $dir_file = preg_replace('/\/+/', '/', str_replace([DIRECTORY_SEPARATOR, '\\', '/'], '/', $dir_file));
+ $dir_file = ($allow_trailing_slash) ? $dir_file : rtrim($dir_file, '/'); // Strip trailing slashes.
- if (!empty($stream_wrapper[0])) {
- $dir_file = strtolower($stream_wrapper[0]).$dir_file;
- }
- return $dir_file; // Normalized now.
-};
-
-/*
- * Acquires system tmp directory path.
- *
- * @since 150422 Rewrite.
- *
- * @return string System tmp directory path; else an empty string.
- */
-$self->getTmpDir = function () use ($self) {
- if (!is_null($dir = &$self->staticKey('getTmpDir'))) {
- return $dir; // Already cached this.
+ if (!empty($stream_wrapper[0])) {
+ $dir_file = strtolower($stream_wrapper[0]).$dir_file;
+ }
+ return $dir_file; // Normalized now.
}
- $possible_dirs = array(); // Initialize.
- if (defined('WP_TEMP_DIR')) {
- $possible_dirs[] = (string) WP_TEMP_DIR;
- }
- if ($self->functionIsPossible('sys_get_temp_dir')) {
- $possible_dirs[] = (string) sys_get_temp_dir();
- }
- $possible_dirs[] = (string) ini_get('upload_tmp_dir');
+ /*
+ * Acquires system tmp directory path.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return string System tmp directory path; else an empty string.
+ */
+ public function getTmpDir()
+ {
+ if (!is_null($dir = &$this->staticKey('getTmpDir'))) {
+ return $dir; // Already cached this.
+ }
+ $possible_dirs = []; // Initialize.
- if (!empty($_SERVER['TEMP'])) {
- $possible_dirs[] = (string) $_SERVER['TEMP'];
- }
- if (!empty($_SERVER['TMPDIR'])) {
- $possible_dirs[] = (string) $_SERVER['TMPDIR'];
- }
- if (!empty($_SERVER['TMP'])) {
- $possible_dirs[] = (string) $_SERVER['TMP'];
- }
- if (stripos(PHP_OS, 'win') === 0) {
- $possible_dirs[] = 'C:/Temp';
- }
- if (stripos(PHP_OS, 'win') !== 0) {
- $possible_dirs[] = '/tmp';
- }
- if (defined('WP_CONTENT_DIR')) {
- $possible_dirs[] = (string) WP_CONTENT_DIR;
- }
- foreach ($possible_dirs as $_key => $_dir) {
- if (($_dir = trim((string) $_dir)) && @is_dir($_dir) && @is_writable($_dir)) {
- return ($dir = $self->nDirSeps($_dir));
+ if (defined('WP_TEMP_DIR')) {
+ $possible_dirs[] = (string) WP_TEMP_DIR;
}
+ if ($this->functionIsPossible('sys_get_temp_dir')) {
+ $possible_dirs[] = (string) sys_get_temp_dir();
+ }
+ $possible_dirs[] = (string) ini_get('upload_tmp_dir');
+
+ if (!empty($_SERVER['TEMP'])) {
+ $possible_dirs[] = (string) $_SERVER['TEMP'];
+ }
+ if (!empty($_SERVER['TMPDIR'])) {
+ $possible_dirs[] = (string) $_SERVER['TMPDIR'];
+ }
+ if (!empty($_SERVER['TMP'])) {
+ $possible_dirs[] = (string) $_SERVER['TMP'];
+ }
+ if (stripos(PHP_OS, 'win') === 0) {
+ $possible_dirs[] = 'C:/Temp';
+ }
+ if (stripos(PHP_OS, 'win') !== 0) {
+ $possible_dirs[] = '/tmp';
+ }
+ if (defined('WP_CONTENT_DIR')) {
+ $possible_dirs[] = (string) WP_CONTENT_DIR;
+ }
+ foreach ($possible_dirs as $_key => $_dir) {
+ if (($_dir = trim((string) $_dir)) && @is_dir($_dir) && @is_writable($_dir)) {
+ return ($dir = $this->nDirSeps($_dir));
+ }
+ }
+ unset($_key, $_dir); // Housekeeping.
+
+ return ($dir = '');
}
- unset($_key, $_dir); // Housekeeping.
-
- return ($dir = '');
-};
-
-/*
- * Finds absolute server path to `/wp-config.php` file.
- *
- * @since 150422 Rewrite.
- *
- * @return string Absolute server path to `/wp-config.php` file;
- * else an empty string if unable to locate the file.
- */
-$self->findWpConfigFile = function () use ($self) {
- if (!is_null($file = &$self->staticKey('findWpConfigFile'))) {
- return $file; // Already cached this.
- }
- $file = ''; // Initialize.
- if (is_file($abspath_wp_config = ABSPATH.'wp-config.php')) {
- $file = $abspath_wp_config;
- } elseif (is_file($dirname_abspath_wp_config = dirname(ABSPATH).'/wp-config.php')) {
- $file = $dirname_abspath_wp_config;
+ /*
+ * Finds absolute server path to `/wp-config.php` file.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return string Absolute server path to `/wp-config.php` file;
+ * else an empty string if unable to locate the file.
+ */
+ public function findWpConfigFile()
+ {
+ if (!is_null($file = &$this->staticKey('findWpConfigFile'))) {
+ return $file; // Already cached this.
+ }
+ $file = ''; // Initialize.
+
+ if (is_file($abspath_wp_config = ABSPATH.'wp-config.php')) {
+ $file = $abspath_wp_config;
+ } elseif (is_file($dirname_abspath_wp_config = dirname(ABSPATH).'/wp-config.php')) {
+ $file = $dirname_abspath_wp_config;
+ }
+ return $file;
}
- return $file;
-};
-
-/*
- * Adds a tmp name suffix to a directory/file path.
- *
- * @since 150422 Rewrite.
- *
- * @param string $dir_file An input directory or file path.
- *
- * @return string The original `$dir_file` with a tmp name suffix.
- */
-$self->addTmpSuffix = function ($dir_file) use ($self) {
- $dir_file = (string) $dir_file;
- $dir_file = rtrim($dir_file, DIRECTORY_SEPARATOR.'\\/');
-
- return $dir_file.'-'.str_replace('.', '', uniqid('', true)).'-tmp';
-};
-
-/*
- * Recursive directory iterator based on a regex pattern.
- *
- * @since 150422 Rewrite.
- *
- * @param string $dir An absolute server directory path.
- * @param string $regex A regex pattern; compares to each full file path.
- *
- * @return \RegexIterator Navigable with {@link \foreach()}; where each item
- * is a {@link \RecursiveDirectoryIterator}.
- */
-$self->dirRegexIteration = function ($dir, $regex = '') use ($self) {
- $dir = (string) $dir;
- $regex = (string) $regex;
-
- $dir_iterator = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_SELF | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS);
- $iterator_iterator = new \RecursiveIteratorIterator($dir_iterator, \RecursiveIteratorIterator::CHILD_FIRST);
-
- if ($regex && $regex !== '/.*/' && $regex !== '/.+/') { // Apply regex filter?
- // @TODO Optimize calls to this method in order to avoid the regex iterator when not necessary.
- return new \RegexIterator($iterator_iterator, $regex, \RegexIterator::MATCH, \RegexIterator::USE_KEY);
+
+ /*
+ * Adds a tmp name suffix to a directory/file path.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $dir_file An input directory or file path.
+ *
+ * @return string The original `$dir_file` with a tmp name suffix.
+ */
+ public function addTmpSuffix($dir_file)
+ {
+ $dir_file = (string) $dir_file;
+ $dir_file = rtrim($dir_file, DIRECTORY_SEPARATOR.'\\/');
+
+ return $dir_file.'-'.str_replace('.', '', uniqid('', true)).'-tmp';
}
- return $iterator_iterator; // Iterate everything.
-};
-
-/*
- * Abbreviated byte notation for file sizes.
- *
- * @since 151002 Adding a few statistics.
- *
- * @param float $bytes File size in bytes. A (float) value.
- * @param integer $precision Number of decimals to use.
- *
- * @return string Byte notation.
- */
-$self->bytesAbbr = function ($bytes, $precision = 2) use ($self) {
- $bytes = max(0.0, (float) $bytes);
- $precision = max(0, (integer) $precision);
- $units = array('bytes', 'kbs', 'MB', 'GB', 'TB');
-
- $power = floor(($bytes ? log($bytes) : 0) / log(1024));
- $abbr_bytes = round($bytes / pow(1024, $power), $precision);
- $abbr = $units[min($power, count($units) - 1)];
-
- if ($abbr_bytes === (float) 1 && $abbr === 'bytes') {
- $abbr = 'byte'; // Quick fix.
- } elseif ($abbr_bytes === (float) 1 && $abbr === 'kbs') {
- $abbr = 'kb'; // Quick fix.
+
+ /*
+ * Recursive directory iterator based on a regex pattern.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $dir An absolute server directory path.
+ * @param string $regex A regex pattern; compares to each full file path.
+ *
+ * @return \RegexIterator Navigable with {@link \foreach()} where each item
+ * is a {@link \RecursiveDirectoryIterator}.
+ */
+ public function dirRegexIteration($dir, $regex = '')
+ {
+ $dir = (string) $dir;
+ $regex = (string) $regex;
+
+ $dir_iterator = new \RecursiveDirectoryIterator($dir, \FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_SELF | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS);
+ $iterator_iterator = new \RecursiveIteratorIterator($dir_iterator, \RecursiveIteratorIterator::CHILD_FIRST);
+
+ if ($regex && $regex !== '/.*/' && $regex !== '/.+/') { // Apply regex filter?
+ // @TODO Optimize calls to this method in order to avoid the regex iterator when not necessary.
+ return new \RegexIterator($iterator_iterator, $regex, \RegexIterator::MATCH, \RegexIterator::USE_KEY);
+ }
+ return $iterator_iterator; // Iterate everything.
}
- return $abbr_bytes.' '.$abbr;
-};
-
-/*
- * Converts an abbreviated byte notation into bytes.
- *
- * @since 151002 Adding a few statistics.
- *
- * @param string $string A string value in byte notation.
- *
- * @return float A float indicating the number of bytes.
- */
-$self->abbrBytes = function ($string) use ($self) {
- $string = (string) $string;
- $regex = '/^(?P[0-9\.]+)\s*(?Pbytes|byte|kbs|kb|k|mb|m|gb|g|tb|t)$/i';
-
- if (!preg_match($regex, $string, $_m)) {
- return (float) 0;
+
+ /*
+ * Abbreviated byte notation for file sizes.
+ *
+ * @since 151002 Adding a few statistics.
+ *
+ * @param float $bytes File size in bytes. A (float) value.
+ * @param integer $precision Number of decimals to use.
+ *
+ * @return string Byte notation.
+ */
+ public function bytesAbbr($bytes, $precision = 2)
+ {
+ $bytes = max(0.0, (float) $bytes);
+ $precision = max(0, (integer) $precision);
+ $units = ['bytes', 'kbs', 'MB', 'GB', 'TB'];
+
+ $power = floor(($bytes ? log($bytes) : 0) / log(1024));
+ $abbr_bytes = round($bytes / pow(1024, $power), $precision);
+ $abbr = $units[min($power, count($units) - 1)];
+
+ if ($abbr_bytes === (float) 1 && $abbr === 'bytes') {
+ $abbr = 'byte'; // Quick fix.
+ } elseif ($abbr_bytes === (float) 1 && $abbr === 'kbs') {
+ $abbr = 'kb'; // Quick fix.
+ }
+ return $abbr_bytes.' '.$abbr;
}
- $value = (float) $_m['value'];
- $modifier = strtolower($_m['modifier']);
- unset($_m); // Housekeeping.
-
- switch ($modifier) {
- case 't':
- case 'tb':
- $value *= 1024;
+
+ /*
+ * Converts an abbreviated byte notation into bytes.
+ *
+ * @since 151002 Adding a few statistics.
+ *
+ * @param string $string A string value in byte notation.
+ *
+ * @return float A float indicating the number of bytes.
+ */
+ public function abbrBytes($string)
+ {
+ $string = (string) $string;
+ $regex = '/^(?P[0-9\.]+)\s*(?Pbytes|byte|kbs|kb|k|mb|m|gb|g|tb|t)$/i';
+
+ if (!preg_match($regex, $string, $_m)) {
+ return (float) 0;
+ }
+ $value = (float) $_m['value'];
+ $modifier = strtolower($_m['modifier']);
+ unset($_m); // Housekeeping.
+
+ switch ($modifier) {
+ case 't':
+ case 'tb':
+ $value *= 1024;
// Fall through.
- case 'g':
- case 'gb':
- $value *= 1024;
+ case 'g':
+ case 'gb':
+ $value *= 1024;
// Fall through.
- case 'm':
- case 'mb':
- $value *= 1024;
+ case 'm':
+ case 'mb':
+ $value *= 1024;
// Fall through.
- case 'k':
- case 'kb':
- case 'kbs':
- $value *= 1024;
- }
- return (float) $value;
-};
-
-/*
- * Directory stats.
- *
- * @since 151002 Adding a few statistics.
- *
- * @param string $dir An absolute server directory path.
- * @param string $regex A regex pattern; compares to each full file path.
- * @param boolean $include_paths Include array of all scanned file paths?
- * @param boolean $check_disk Also check disk statistics?
- * @param boolean $no_cache Do not read/write cache?
- *
- * @return array Directory stats.
- */
-$self->getDirRegexStats = function ($dir, $regex = '', $include_paths = false, $check_disk = true, $no_cache = false) use ($self) {
- $dir = (string) $dir; // Force string.
- $cache_keys = array($dir, $regex, $include_paths, $check_disk);
- if (!$no_cache && !is_null($stats = &$self->staticKey('getDirRegexStats', $cache_keys))) {
- return $stats; // Already cached this.
+ case 'k':
+ case 'kb':
+ case 'kbs':
+ $value *= 1024;
+ }
+ return (float) $value;
}
- $stats = array(
- 'total_size' => 0,
- 'total_resources' => 0,
- 'total_links_files' => 0,
-
- 'total_links' => 0,
- 'link_subpaths' => array(),
- 'total_files' => 0,
- 'file_subpaths' => array(),
+ /*
+ * Directory stats.
+ *
+ * @since 151002 Adding a few statistics.
+ *
+ * @param string $dir An absolute server directory path.
+ * @param string $regex A regex pattern; compares to each full file path.
+ * @param boolean $include_paths Include array of all scanned file paths?
+ * @param boolean $check_disk Also check disk statistics?
+ * @param boolean $no_cache Do not read/write cache?
+ *
+ * @return array Directory stats.
+ */
+ public function getDirRegexStats($dir, $regex = '', $include_paths = false, $check_disk = true, $no_cache = false)
+ {
+ $dir = (string) $dir; // Force string.
+ $cache_keys = [$dir, $regex, $include_paths, $check_disk];
+ if (!$no_cache && !is_null($stats = &$this->staticKey('getDirRegexStats', $cache_keys))) {
+ return $stats; // Already cached this.
+ }
+ $stats = [
+ 'total_size' => 0,
+ 'total_resources' => 0,
+ 'total_links_files' => 0,
- 'total_dirs' => 0,
- 'dir_subpaths' => array(),
+ 'total_links' => 0,
+ 'link_subpaths' => [],
- 'disk_total_space' => 0,
- 'disk_free_space' => 0,
- );
- if (!$dir || !is_dir($dir)) {
- return $stats; // Not possible.
- }
- $short_name_lc = strtolower(SHORT_NAME); // Once only.
+ 'total_files' => 0,
+ 'file_subpaths' => [],
- foreach ($self->dirRegexIteration($dir, $regex) as $_resource) {
- $_resource_sub_path = $_resource->getSubpathname();
- $_resource_basename = basename($_resource_sub_path);
+ 'total_dirs' => 0,
+ 'dir_subpaths' => [],
- if ($_resource_basename === '.DS_Store') {
- continue; // Ignore `.htaccess`.
- }
- if ($_resource_basename === '.htaccess') {
- continue; // Ignore `.htaccess`.
+ 'disk_total_space' => 0,
+ 'disk_free_space' => 0,
+ ];
+ if (!$dir || !is_dir($dir)) {
+ return $stats; // Not possible.
}
- if (stripos($_resource_sub_path, $short_name_lc.'-') === 0) {
- continue; // Ignore [SHORT_NAME] files in base.
+ $short_name_lc = strtolower(SHORT_NAME); // Once only.
+
+ foreach ($this->dirRegexIteration($dir, $regex) as $_resource) {
+ $_resource_sub_path = $_resource->getSubpathname();
+ $_resource_basename = basename($_resource_sub_path);
+
+ if ($_resource_basename === '.DS_Store') {
+ continue; // Ignore `.htaccess`.
+ }
+ if ($_resource_basename === '.htaccess') {
+ continue; // Ignore `.htaccess`.
+ }
+ if (stripos($_resource_sub_path, $short_name_lc.'-') === 0) {
+ continue; // Ignore [SHORT_NAME] files in base.
+ }
+ switch ($_resource->getType()) { // `link`, `file`, `dir`.
+ case 'link':
+ if ($include_paths) {
+ $stats['link_subpaths'][] = $_sub_path;
+ }
+ ++$stats['total_resources'];
+ ++$stats['total_links_files'];
+ ++$stats['total_links'];
+
+ break; // Break switch.
+
+ case 'file':
+ if ($include_paths) {
+ $stats['file_subpaths'][] = $_sub_path;
+ }
+ $stats['total_size'] += $_resource->getSize();
+ ++$stats['total_resources'];
+ ++$stats['total_links_files'];
+ ++$stats['total_files'];
+
+ break; // Break switch.
+
+ case 'dir':
+ if ($include_paths) {
+ $stats['dir_subpaths'][] = $_sub_path;
+ }
+ ++$stats['total_resources'];
+ ++$stats['total_dirs'];
+
+ break; // Break switch.
+ }
}
- switch ($_resource->getType()) { // `link`, `file`, `dir`.
- case 'link':
- if ($include_paths) {
- $stats['link_subpaths'][] = $_sub_path;
- }
- ++$stats['total_resources'];
- ++$stats['total_links_files'];
- ++$stats['total_links'];
-
- break; // Break switch.
-
- case 'file':
- if ($include_paths) {
- $stats['file_subpaths'][] = $_sub_path;
- }
- $stats['total_size'] += $_resource->getSize();
- ++$stats['total_resources'];
- ++$stats['total_links_files'];
- ++$stats['total_files'];
-
- break; // Break switch.
-
- case 'dir':
- if ($include_paths) {
- $stats['dir_subpaths'][] = $_sub_path;
- }
- ++$stats['total_resources'];
- ++$stats['total_dirs'];
-
- break; // Break switch.
+ unset($_resource, $_resource_sub_path, $_resource_basename); // Housekeeping.
+
+ if ($check_disk) { // Check disk also?
+ $stats['disk_total_space'] = disk_total_space($dir);
+ $stats['disk_free_space'] = disk_free_space($dir);
}
+ return $stats;
}
- unset($_resource, $_resource_sub_path, $_resource_basename); // Housekeeping.
- if ($check_disk) { // Check disk also?
- $stats['disk_total_space'] = disk_total_space($dir);
- $stats['disk_free_space'] = disk_free_space($dir);
- }
- return $stats;
-};
-
-/*
- * Apache `.htaccess` rules that deny public access to the contents of a directory.
- *
- * @since 150422 Rewrite.
- *
- * @var string `.htaccess` fules.
- */
-public $htaccess_deny = "\n\tRequire all denied\n\n\n\tdeny from all\n";
+ /*
+ * Apache `.htaccess` rules that deny public access to the contents of a directory.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @var string `.htaccess` fules.
+ */
+ public $htaccess_deny = "\n\tRequire all denied\n\n\n\tdeny from all\n";
+}
diff --git a/src/includes/traits/Shared/HookUtils.php b/src/includes/traits/Shared/HookUtils.php
index d54cb62e..a8d64da9 100644
--- a/src/includes/traits/Shared/HookUtils.php
+++ b/src/includes/traits/Shared/HookUtils.php
@@ -1,249 +1,262 @@
hookId = function ($function) use ($self) {
- if (is_string($function)) {
- return $function;
- }
- if (is_object($function)) {
- $function = array($function, '');
- } else {
- $function = (array) $function;
- }
- if (isset($function[0], $function[1])) {
- if (is_object($function[0])) {
- return spl_object_hash($function[0]).$function[1];
- } elseif (is_string($function[0])) {
- return $function[0].'::'.$function[1];
+trait HookUtils {
+ /*
+ * Array of hooks.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @type array An array of hooks.
+ */
+ public $hooks = [];
+
+ /*
+ * Assigns an ID to each callable attached to a hook/filter.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string|callable|mixed $function A string or a callable.
+ *
+ * @return string Hook ID for the given `$function`.
+ *
+ * @throws \Exception If the hook/function is invalid (i.e. it's not possible to generate an ID).
+ */
+ public function hookId($function)
+ {
+ if (is_string($function)) {
+ return $function;
}
+ if (is_object($function)) {
+ $function = [$function, ''];
+ } else {
+ $function = (array) $function;
+ }
+ if (isset($function[0], $function[1])) {
+ if (is_object($function[0])) {
+ return spl_object_hash($function[0]).$function[1];
+ } elseif (is_string($function[0])) {
+ return $function[0].'::'.$function[1];
+ }
+ }
+ throw new \Exception(__('Invalid hook.', SLUG_TD));
}
- throw new \Exception(__('Invalid hook.', SLUG_TD));
-};
-
-/*
- * Adds a new hook (works with both actions & filters).
- *
- * @since 150422 Rewrite.
- *
- * @param string $hook The name of a hook to attach to.
- * @param string|callable|mixed $function A string or a callable.
- * @param integer $priority Hook priority; defaults to `10`.
- * @param integer $accepted_args Max number of args that should be passed to the `$function`.
- *
- * @return boolean This always returns a `TRUE` value.
- */
-$self->addHook = function ($hook, $function, $priority = 10, $accepted_args = 1) use ($self) {
- $hook = (string) $hook;
- if (stripos($hook, 'zencache') === 0) {
- $hook = GLOBAL_NS.substr($hook, strlen('zencache'));
- }
- $priority = (integer) $priority;
- $accepted_args = max(0, (integer) $accepted_args);
- $hook_id = $self->hookId($function);
- $self->hooks[$hook][$priority][$hook_id] = array(
+ /*
+ * Adds a new hook (works with both actions & filters).
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $hook The name of a hook to attach to.
+ * @param string|callable|mixed $function A string or a callable.
+ * @param integer $priority Hook priority; defaults to `10`.
+ * @param integer $accepted_args Max number of args that should be passed to the `$function`.
+ *
+ * @return boolean This always returns a `TRUE` value.
+ */
+ public function addHook($hook, $function, $priority = 10, $accepted_args = 1)
+ {
+ $hook = (string) $hook;
+ if (stripos($hook, 'zencache') === 0) {
+ $hook = GLOBAL_NS.substr($hook, strlen('zencache'));
+ }
+ $priority = (integer) $priority;
+ $accepted_args = max(0, (integer) $accepted_args);
+ $hook_id = $this->hookId($function);
+
+ $this->hooks[$hook][$priority][$hook_id] = [
'function' => $function,
'accepted_args' => $accepted_args,
- );
- return true; // Always returns true.
-};
-
-/*
- * Adds a new action hook.
- *
- * @since 150422 Rewrite.
- *
- * @return boolean This always returns a `TRUE` value.
- */
-$self->addAction = function () use ($self) {
- return call_user_func_array(array($self, 'addHook'), func_get_args());
-};
-$self->add_action = $self->addAction; // Back compat.
-
-/*
- * Adds a new filter.
- *
- * @since 150422 Rewrite.
- *
- * @return boolean This always returns a `TRUE` value.
- */
-$self->addFilter = function () use ($self) {
- return call_user_func_array(array($self, 'addHook'), func_get_args());
-};
-$self->add_filter = $self->addFilter; // Back compat.
-
-/*
- * Removes a hook (works with both actions & filters).
- *
- * @since 150422 Rewrite.
- *
- * @param string $hook The name of a hook to remove.
- * @param string|callable|mixed $function A string or a callable.
- * @param integer $priority Hook priority; defaults to `10`.
- *
- * @return boolean `TRUE` if removed; else `FALSE` if not removed for any reason.
- */
-$self->removeHook = function ($hook, $function, $priority = 10) use ($self) {
- $hook = (string) $hook;
- if (stripos($hook, 'zencache') === 0) {
- $hook = GLOBAL_NS.substr($hook, strlen('zencache'));
+ ];
+ return true; // Always returns true.
}
- $priority = (integer) $priority;
- $hook_id = $self->hookId($function);
- if (!isset($self->hooks[$hook][$priority][$hook_id])) {
- return false; // Nothing to remove.
+ /*
+ * Adds a new action hook.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return boolean This always returns a `TRUE` value.
+ */
+ public function addAction()
+ {
+ return call_user_func_array([$self, 'addHook'], func_get_args());
}
- unset($self->hooks[$hook][$priority][$hook_id]);
+$this->add_action = $this->addAction; // Back compat.
- if (!$self->hooks[$hook][$priority]) {
- unset($self->hooks[$hook][$priority]);
+ /*
+ * Adds a new filter.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return boolean This always returns a `TRUE` value.
+ */
+ public function addFilter()
+ {
+ return call_user_func_array([$self, 'addHook'], func_get_args());
}
- return true; // Existed before it was removed.
-};
-
-/*
- * Removes an action.
- *
- * @since 150422 Rewrite.
- *
- * @return boolean `TRUE` if removed; else `FALSE` if not removed for any reason.
- */
-$self->removeAction = function () use ($self) {
- return call_user_func_array(array($self, 'removeHook'), func_get_args());
-};
-
-/*
- * Removes a filter.
- *
- * @since 150422 Rewrite.
- *
- * @return boolean `TRUE` if removed; else `FALSE` if not removed for any reason.
- */
-$self->removeFilter = function () use ($self) {
- return call_user_func_array(array($self, 'removeHook'), func_get_args());
-};
-
-/*
- * Runs any callables attached to an action.
- *
- * @since 150422 Rewrite.
- *
- * @param string $hook The name of an action hook.
- */
-$self->doAction = function ($hook) use ($self) {
- $hook = (string) $hook;
- if (empty($self->hooks[$hook])) {
- return; // No hooks.
+$this->add_filter = $this->addFilter; // Back compat.
+
+ /*
+ * Removes a hook (works with both actions & filters).
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $hook The name of a hook to remove.
+ * @param string|callable|mixed $function A string or a callable.
+ * @param integer $priority Hook priority; defaults to `10`.
+ *
+ * @return boolean `TRUE` if removed; else `FALSE` if not removed for any reason.
+ */
+ public function removeHook($hook, $function, $priority = 10)
+ {
+ $hook = (string) $hook;
+ if (stripos($hook, 'zencache') === 0) {
+ $hook = GLOBAL_NS.substr($hook, strlen('zencache'));
+ }
+ $priority = (integer) $priority;
+ $hook_id = $this->hookId($function);
+
+ if (!isset($this->hooks[$hook][$priority][$hook_id])) {
+ return false; // Nothing to remove.
+ }
+ unset($this->hooks[$hook][$priority][$hook_id]);
+
+ if (!$this->hooks[$hook][$priority]) {
+ unset($this->hooks[$hook][$priority]);
+ }
+ return true; // Existed before it was removed.
+ }
+
+ /*
+ * Removes an action.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return boolean `TRUE` if removed; else `FALSE` if not removed for any reason.
+ */
+ public function removeAction()
+ {
+ return call_user_func_array([$self, 'removeHook'], func_get_args());
}
- $hook_actions = $self->hooks[$hook];
- $args = func_get_args();
- ksort($hook_actions);
-
- foreach ($hook_actions as $_hook_action) {
- foreach ($_hook_action as $_action) {
- if (!isset($_action['function'], $_action['accepted_args'])) {
- continue; // Not a valid filter in this case.
+
+ /*
+ * Removes a filter.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return boolean `TRUE` if removed; else `FALSE` if not removed for any reason.
+ */
+ public function removeFilter()
+ {
+ return call_user_func_array([$self, 'removeHook'], func_get_args());
+ }
+
+ /*
+ * Runs any callables attached to an action.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $hook The name of an action hook.
+ */
+ public function doAction($hook)
+ {
+ $hook = (string) $hook;
+ if (empty($this->hooks[$hook])) {
+ return; // No hooks.
+ }
+ $hook_actions = $this->hooks[$hook];
+ $args = func_get_args();
+ ksort($hook_actions);
+
+ foreach ($hook_actions as $_hook_action) {
+ foreach ($_hook_action as $_action) {
+ if (!isset($_action['function'], $_action['accepted_args'])) {
+ continue; // Not a valid filter in this case.
+ }
+ call_user_func_array($_action['function'], array_slice($args, 1, $_action['accepted_args']));
}
- call_user_func_array($_action['function'], array_slice($args, 1, $_action['accepted_args']));
}
+ unset($_hook_action, $_action); // Housekeeping.
}
- unset($_hook_action, $_action); // Housekeeping.
-};
-
-/*
- * Runs any callables attached to a filter.
- *
- * @since 150422 Rewrite.
- *
- * @param string $hook The name of a filter hook.
- * @param mixed $value The value to filter.
- *
- * @return mixed The filtered `$value`.
- */
-$self->applyFilters = function ($hook, $value) use ($self) {
- $hook = (string) $hook;
- if (empty($self->hooks[$hook])) {
- return $value; // No hooks.
- }
- $hook_filters = $self->hooks[$hook];
- $args = func_get_args();
- ksort($hook_filters);
-
- foreach ($hook_filters as $_hook_filter) {
- foreach ($_hook_filter as $_filter) {
- if (!isset($_filter['function'], $_filter['accepted_args'])) {
- continue; // Not a valid filter in this case.
+
+ /*
+ * Runs any callables attached to a filter.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $hook The name of a filter hook.
+ * @param mixed $value The value to filter.
+ *
+ * @return mixed The filtered `$value`.
+ */
+ public function applyFilters($hook, $value)
+ {
+ $hook = (string) $hook;
+ if (empty($this->hooks[$hook])) {
+ return $value; // No hooks.
+ }
+ $hook_filters = $this->hooks[$hook];
+ $args = func_get_args();
+ ksort($hook_filters);
+
+ foreach ($hook_filters as $_hook_filter) {
+ foreach ($_hook_filter as $_filter) {
+ if (!isset($_filter['function'], $_filter['accepted_args'])) {
+ continue; // Not a valid filter in this case.
+ }
+ $args[1] = $value; // Continously update the argument `$value`.
+ $value = call_user_func_array($_filter['function'], array_slice($args, 1, $_filter['accepted_args']));
}
- $args[1] = $value; // Continously update the argument `$value`.
- $value = call_user_func_array($_filter['function'], array_slice($args, 1, $_filter['accepted_args']));
}
+ unset($_hook_filter, $_filter); // Housekeeping.
+
+ return $value; // With applied filters.
}
- unset($_hook_filter, $_filter); // Housekeeping.
-
- return $value; // With applied filters.
-};
-
-/*
- * Does an action w/ back compat. for ZenCache.
- *
- * @since 150422 Rewrite.
- *
- * @param string $hook The hook to apply.
- */
-$self->doWpAction = function ($hook) use ($self) {
- $hook = (string) $hook;
- $args = func_get_args();
- call_user_func_array('do_action', $args);
-
- if (stripos($hook, GLOBAL_NS) === 0) {
- $zencache_filter = 'zencache'.substr($hook, strlen(GLOBAL_NS));
- $zencache_args = $args; // Use a copy of the args.
- $zencache_args[0] = $zencache_filter;
- call_user_func_array('do_action', $zencache_args);
+
+ /*
+ * Does an action w/ back compat. for ZenCache.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $hook The hook to apply.
+ */
+ public function doWpAction($hook)
+ {
+ $hook = (string) $hook;
+ $args = func_get_args();
+ call_user_func_array('do_action', $args);
+
+ if (stripos($hook, GLOBAL_NS) === 0) {
+ $zencache_filter = 'zencache'.substr($hook, strlen(GLOBAL_NS));
+ $zencache_args = $args; // Use a copy of the args.
+ $zencache_args[0] = $zencache_filter;
+ call_user_func_array('do_action', $zencache_args);
+ }
}
-};
-
-/*
- * Applies filters w/ back compat. for ZenCache.
- *
- * @since 150422 Rewrite.
- *
- * @param string $hook The hook to apply.
- *
- * @return mixed The filtered value.
- */
-$self->applyWpFilters = function ($hook) use ($self) {
- $hook = (string) $hook;
- $args = func_get_args();
- $value = call_user_func_array('apply_filters', $args);
-
- if (stripos($hook, GLOBAL_NS) === 0) {
- $zencache_hook = 'zencache'.substr($hook, strlen(GLOBAL_NS));
- $zencache_args = $args; // Use a copy of the args.
- $zencache_args[0] = $zencache_hook;
- $zencache_args[1] = $value; // Filtered value.
- $value = call_user_func_array('apply_filters', $zencache_args);
+
+ /*
+ * Applies filters w/ back compat. for ZenCache.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $hook The hook to apply.
+ *
+ * @return mixed The filtered value.
+ */
+ public function applyWpFilters($hook)
+ {
+ $hook = (string) $hook;
+ $args = func_get_args();
+ $value = call_user_func_array('apply_filters', $args);
+
+ if (stripos($hook, GLOBAL_NS) === 0) {
+ $zencache_hook = 'zencache'.substr($hook, strlen(GLOBAL_NS));
+ $zencache_args = $args; // Use a copy of the args.
+ $zencache_args[0] = $zencache_hook;
+ $zencache_args[1] = $value; // Filtered value.
+ $value = call_user_func_array('apply_filters', $zencache_args);
+ }
+ return $value; // Filtered value.
}
- return $value; // Filtered value.
-};
+}
diff --git a/src/includes/traits/Shared/HttpUtils.php b/src/includes/traits/Shared/HttpUtils.php
index f5cbea6b..952b36fa 100644
--- a/src/includes/traits/Shared/HttpUtils.php
+++ b/src/includes/traits/Shared/HttpUtils.php
@@ -1,166 +1,175 @@
httpProtocol = function () use ($self) {
- if (!is_null($protocol = &$self->staticKey('httpProtocol'))) {
- return $protocol; // Already cached this.
- }
- if (!empty($_SERVER['SERVER_PROTOCOL']) && is_string($_SERVER['SERVER_PROTOCOL'])) {
- $protocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
- }
- if (!$protocol || stripos($protocol, 'HTTP/') !== 0) {
- $protocol = 'HTTP/1.0'; // Default value.
+trait HttpUtils
+{
+ /*
+ * Current HTTP protocol.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return string Current HTTP protocol.
+ */
+ public function httpProtocol()
+ {
+ if (!is_null($protocol = &$this->staticKey('httpProtocol'))) {
+ return $protocol; // Already cached this.
+ }
+ if (!empty($_SERVER['SERVER_PROTOCOL']) && is_string($_SERVER['SERVER_PROTOCOL'])) {
+ $protocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
+ }
+ if (!$protocol || stripos($protocol, 'HTTP/') !== 0) {
+ $protocol = 'HTTP/1.0'; // Default value.
+ }
+ return $protocol;
}
- return $protocol;
-};
-/*
- * PHP {@link headers_list()} + HTTP status.
- *
- * @since 150422 Rewrite.
- *
- * @return array PHP {@link headers_list()} + HTTP status.
- *
- * @warning Do NOT call until end of script execution.
- */
-$self->headersList = function () use ($self) {
- if (!is_null($headers = &$self->staticKey('headersList'))) {
- return $headers; // Already cached this.
- }
- $headers = headers_list(); // Lacks status.
+ /*
+ * PHP {@link headers_list()} + HTTP status.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return array PHP {@link headers_list()} + HTTP status.
+ *
+ * @warning Do NOT call until end of script execution.
+ */
+ public function headersList()
+ {
+ if (!is_null($headers = &$this->staticKey('headersList'))) {
+ return $headers; // Already cached this.
+ }
+ $headers = headers_list(); // Lacks status.
- if (($status = (string) $self->httpStatus())) {
- array_unshift($headers, $self->httpProtocol().' '.$status);
+ if (($status = (string) $this->httpStatus())) {
+ array_unshift($headers, $this->httpProtocol().' '.$status);
+ }
+ return $headers;
}
- return $headers;
-};
-/*
- * PHP {@link headers_list()} + HTTP status.
- *
- * @since 150422 Rewrite.
- *
- * @return array PHP {@link headers_list()} + HTTP status.
- *
- * @warning Do NOT call until end of script execution.
- */
-$self->cacheableHeadersList = function () use ($self) {
- if (!is_null($headers = &$self->staticKey('cacheableHeadersList'))) {
- return $headers; // Already cached this.
- }
- $headers = headers_list(); // Lacks status.
+ /*
+ * PHP {@link headers_list()} + HTTP status.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return array PHP {@link headers_list()} + HTTP status.
+ *
+ * @warning Do NOT call until end of script execution.
+ */
+ public function cacheableHeadersList()
+ {
+ if (!is_null($headers = &$this->staticKey('cacheableHeadersList'))) {
+ return $headers; // Already cached this.
+ }
+ $headers = headers_list(); // Lacks status.
- $cacheable_headers = array(
- 'Access-Control-Allow-Origin',
- 'Accept-Ranges',
- 'Age',
- 'Allow',
- 'Cache-Control',
- 'Connection',
- 'Content-Encoding',
- 'Content-Language',
- 'Content-Length',
- 'Content-Location',
- 'Content-MD5',
- 'Content-Disposition',
- 'Content-Range',
- 'Content-Type',
- 'Date',
- 'ETag',
- 'Expires',
- 'Last-Modified',
- 'Link',
- 'Location',
- 'P3P',
- 'Pragma',
- 'Proxy-Authenticate',
- 'Refresh',
- 'Retry-After',
- 'Server',
- 'Status',
- 'Strict-Transport-Security',
- 'Trailer',
- 'Transfer-Encoding',
- 'Upgrade',
- 'Vary',
- 'Via',
- 'Warning',
- 'WWW-Authenticate',
- 'X-Frame-Options',
- 'Public-Key-Pins',
- 'X-XSS-Protection',
- 'Content-Security-Policy',
- 'X-Content-Security-Policy',
- 'X-WebKit-CSP',
- 'X-Content-Type-Options',
- 'X-Powered-By',
- 'X-UA-Compatible',
- );
- $cacheable_headers = array_map('strtolower', $cacheable_headers);
+ $cacheable_headers = [
+ 'Access-Control-Allow-Origin',
+ 'Accept-Ranges',
+ 'Age',
+ 'Allow',
+ 'Cache-Control',
+ 'Connection',
+ 'Content-Encoding',
+ 'Content-Language',
+ 'Content-Length',
+ 'Content-Location',
+ 'Content-MD5',
+ 'Content-Disposition',
+ 'Content-Range',
+ 'Content-Type',
+ 'Date',
+ 'ETag',
+ 'Expires',
+ 'Last-Modified',
+ 'Link',
+ 'Location',
+ 'P3P',
+ 'Pragma',
+ 'Proxy-Authenticate',
+ 'Refresh',
+ 'Retry-After',
+ 'Server',
+ 'Status',
+ 'Strict-Transport-Security',
+ 'Trailer',
+ 'Transfer-Encoding',
+ 'Upgrade',
+ 'Vary',
+ 'Via',
+ 'Warning',
+ 'WWW-Authenticate',
+ 'X-Frame-Options',
+ 'Public-Key-Pins',
+ 'X-XSS-Protection',
+ 'Content-Security-Policy',
+ 'X-Content-Security-Policy',
+ 'X-WebKit-CSP',
+ 'X-Content-Type-Options',
+ 'X-Powered-By',
+ 'X-UA-Compatible',
+ ];
+ $cacheable_headers = array_map('strtolower', $cacheable_headers);
- foreach ($headers as $_key => $_header) {
- $_header = strtolower((string) strstr($_header, ':', true));
- if (!$_header || !in_array($_header, $cacheable_headers, true)) {
- unset($headers[$_key]);
+ foreach ($headers as $_key => $_header) {
+ $_header = strtolower((string) strstr($_header, ':', true));
+ if (!$_header || !in_array($_header, $cacheable_headers, true)) {
+ unset($headers[$_key]);
+ }
}
- }
- unset($_key, $_header); // Housekeeping.
+ unset($_key, $_header); // Housekeeping.
- if (($status = (string) $self->httpStatus())) {
- array_unshift($headers, $self->httpProtocol().' '.$status);
+ if (($status = (string) $this->httpStatus())) {
+ array_unshift($headers, $this->httpProtocol().' '.$status);
+ }
+ return $headers;
}
- return $headers;
-};
-/*
- * HTTP status code.
- *
- * @since 150422 Rewrite.
- *
- * @return integer HTTP status code.
- *
- * @warning Do NOT call until end of script execution.
- *
- * @note Automatically updates HTTP status-related flags.
- */
-$self->httpStatus = function () use ($self) {
- if (!is_null($status = &$self->staticKey('httpStatus'))) {
- return $status; // Already cached this.
- }
- $status = 0; // Initialize.
- $has_property_is_404 = property_exists($self, 'is_404');
- $has_property_http_status = property_exists($self, 'http_status');
+ /*
+ * HTTP status code.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return integer HTTP status code.
+ *
+ * @warning Do NOT call until end of script execution.
+ *
+ * @note Automatically updates HTTP status-related flags.
+ */
+ public function httpStatus()
+ {
+ if (!is_null($status = &$this->staticKey('httpStatus'))) {
+ return $status; // Already cached this.
+ }
+ $status = 0; // Initialize.
+ $has_property_is_404 = property_exists($this, 'is_404');
+ $has_property_http_status = property_exists($this, 'http_status');
- if ($has_property_is_404 && $self->{'is_404'}) {
- $status = 404; // WordPress said so.
- } elseif ($self->functionIsPossible('http_response_code') && ($code = (integer) http_response_code())) {
- $status = (integer) $code; // {@link \http_response_code()} available since PHP v5.4.
- } elseif ($has_property_http_status && (integer) $self->{'http_status'}) {
- $status = (integer) $self->{'http_status'}; // {@link \status_header()} filter.
+ if ($has_property_is_404 && $this->{'is_404'}) {
+ $status = 404; // WordPress said so.
+ } elseif ($this->functionIsPossible('http_response_code') && ($code = (integer) http_response_code())) {
+ $status = (integer) $code; // {@link \http_response_code()} available since PHP v5.4.
+ } elseif ($has_property_http_status && (integer) $this->{'http_status'}) {
+ $status = (integer) $this->{'http_status'} // {@link \status_header()} filter.
}
- if ($status && $has_property_http_status) {
- $self->{'http_status'} = $status; // Prefer over {@link status_header()}.
+ if ($status && $has_property_http_status) {
+ $this->{'http_status'} = $status; // Prefer over {@link status_header()}.
+ }
+ if ($status === 404 && $has_property_is_404) {
+ $this->{'is_404'} = true; // Prefer over {@link is_404()}.
+ }
+ return $status;
}
- if ($status === 404 && $has_property_is_404) {
- $self->{'is_404'} = true; // Prefer over {@link is_404()}.
+
+ /*
+ * Sends no-cache headers.
+ *
+ * @since 151220 Enhancing no-cache headers.
+ */
+ public function sendNoCacheHeaders()
+ {
+ header_remove('Last-Modified');
+ header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');
+ header('Cache-Control: no-cache, must-revalidate, max-age=0');
+ header('Pragma: no-cache');
}
- return $status;
-};
-/*
-* Sends no-cache headers.
-*
-* @since 151220 Enhancing no-cache headers.
-*/
-$self->sendNoCacheHeaders = function() use($self) {
- header_remove('Last-Modified');
- header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');
- header('Cache-Control: no-cache, must-revalidate, max-age=0');
- header('Pragma: no-cache');
-};
+}
diff --git a/src/includes/traits/Shared/I18nUtils.php b/src/includes/traits/Shared/I18nUtils.php
index aaf025c7..88d02236 100644
--- a/src/includes/traits/Shared/I18nUtils.php
+++ b/src/includes/traits/Shared/I18nUtils.php
@@ -1,44 +1,49 @@
i18nFiles = function ($counter) use ($self) {
- $counter = (integer) $counter;
- return sprintf(_n('%1$s file', '%1$s files', $counter, SLUG_TD), $counter);
-};
+trait I18nUtils {
+ /*
+ * `X file` or `X files`, translated w/ singlular/plural context.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param integer $counter Total files; i.e. the counter.
+ *
+ * @return string The phrase `X file` or `X files`.
+ */
+ public function i18nFiles($counter)
+ {
+ $counter = (integer) $counter;
+ return sprintf(_n('%1$s file', '%1$s files', $counter, SLUG_TD), $counter);
+ }
-/*
- * `X directory` or `X directories`, translated w/ singlular/plural context.
- *
- * @since 150422 Rewrite.
- *
- * @param integer $counter Total directories; i.e. the counter.
- *
- * @return string The phrase `X directory` or `X directories`.
- */
-$self->i18nDirs = function ($counter) use ($self) {
- $counter = (integer) $counter;
- return sprintf(_n('%1$s directory', '%1$s directories', $counter, SLUG_TD), $counter);
-};
+ /*
+ * `X directory` or `X directories`, translated w/ singlular/plural context.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param integer $counter Total directories; i.e. the counter.
+ *
+ * @return string The phrase `X directory` or `X directories`.
+ */
+ public function i18nDirs($counter)
+ {
+ $counter = (integer) $counter;
+ return sprintf(_n('%1$s directory', '%1$s directories', $counter, SLUG_TD), $counter);
+ }
-/*
- * `X file/directory` or `X files/directories`, translated w/ singlular/plural context.
- *
- * @since 150422 Rewrite.
- *
- * @param integer $counter Total files/directories; i.e. the counter.
- *
- * @return string The phrase `X file/directory` or `X files/directories`.
- */
-$self->i18nFilesDirs = function ($counter) use ($self) {
- $counter = (integer) $counter;
- return sprintf(_n('%1$s file/directory', '%1$s files/directories', $counter, SLUG_TD), $counter);
-};
+ /*
+ * `X file/directory` or `X files/directories`, translated w/ singlular/plural context.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param integer $counter Total files/directories; i.e. the counter.
+ *
+ * @return string The phrase `X file/directory` or `X files/directories`.
+ */
+ public function i18nFilesDirs($counter)
+ {
+ $counter = (integer) $counter;
+ return sprintf(_n('%1$s file/directory', '%1$s files/directories', $counter, SLUG_TD), $counter);
+ }
+}
diff --git a/src/includes/traits/Shared/IpAddrUtils.php b/src/includes/traits/Shared/IpAddrUtils.php
index ce276d0d..7016b13e 100644
--- a/src/includes/traits/Shared/IpAddrUtils.php
+++ b/src/includes/traits/Shared/IpAddrUtils.php
@@ -1,83 +1,87 @@
currentIp = function () use ($self) {
- if (!is_null($ip = &$self->staticKey('currentIp'))) {
- return $ip; // Already cached this.
- }
- $sources = array(
- 'HTTP_CF_CONNECTING_IP',
- 'HTTP_CLIENT_IP',
- 'HTTP_X_FORWARDED_FOR',
- 'HTTP_X_FORWARDED',
- 'HTTP_X_CLUSTER_CLIENT_IP',
- 'HTTP_FORWARDED_FOR',
- 'HTTP_FORWARDED',
- 'HTTP_VIA',
- 'REMOTE_ADDR',
- );
- $sources = $self->applyFilters(GLOBAL_NS.'\\share::current_ip_sources', $sources);
- $sources = $self->applyFilters(GLOBAL_NS.'_current_ip_sources', $sources);
+trait IpAddrUtils {
+ /*
+ * Get the current visitor's real IP address.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return string Real IP address, else `unknown` on failure.
+ *
+ * @note This supports both IPv4 and IPv6 addresses.
+ * @note See my tests against this here: http://3v4l.org/fVWUp
+ */
+ public function currentIp()
+ {
+ if (!is_null($ip = &$this->staticKey('currentIp'))) {
+ return $ip; // Already cached this.
+ }
+ $sources = [
+ 'HTTP_CF_CONNECTING_IP',
+ 'HTTP_CLIENT_IP',
+ 'HTTP_X_FORWARDED_FOR',
+ 'HTTP_X_FORWARDED',
+ 'HTTP_X_CLUSTER_CLIENT_IP',
+ 'HTTP_FORWARDED_FOR',
+ 'HTTP_FORWARDED',
+ 'HTTP_VIA',
+ 'REMOTE_ADDR',
+ ];
+ $sources = $this->applyFilters(GLOBAL_NS.'\\share::current_ip_sources', $sources);
+ $sources = $this->applyFilters(GLOBAL_NS.'_current_ip_sources', $sources);
- $prioritize_remote_addr = false; // Off by default; can be filtered however.
- $prioritize_remote_addr = $self->applyFilters(GLOBAL_NS.'\\share::current_ip_prioritize_remote_addr', $prioritize_remote_addr);
- $prioritize_remote_addr = $self->applyFilters(GLOBAL_NS.'_current_ip_prioritize_remote_addr', $prioritize_remote_addr);
+ $prioritize_remote_addr = false; // Off by default; can be filtered however.
+ $prioritize_remote_addr = $this->applyFilters(GLOBAL_NS.'\\share::current_ip_prioritize_remote_addr', $prioritize_remote_addr);
+ $prioritize_remote_addr = $this->applyFilters(GLOBAL_NS.'_current_ip_prioritize_remote_addr', $prioritize_remote_addr);
- if (!empty($_SERVER['REMOTE_ADDR']) && $prioritize_remote_addr) {
- if (($_valid_public_ip = $self->validPublicIp((string) $_SERVER['REMOTE_ADDR']))) {
- return ($ip = $_valid_public_ip);
- }
- unset($_valid_public_ip); // Housekeeping.
- }
- foreach ($sources as $_key => $_source) {
- if (!empty($_SERVER[$_source])) {
- if (($_valid_public_ip = $self->validPublicIp((string) $_SERVER[$_source]))) {
+ if (!empty($_SERVER['REMOTE_ADDR']) && $prioritize_remote_addr) {
+ if (($_valid_public_ip = $this->validPublicIp((string) $_SERVER['REMOTE_ADDR']))) {
return ($ip = $_valid_public_ip);
}
+ unset($_valid_public_ip); // Housekeeping.
}
- unset($_key, $_source, $_valid_public_ip); // Housekeeping.
- }
- if (!empty($_SERVER['REMOTE_ADDR'])) {
- return ($ip = strtolower((string) $_SERVER['REMOTE_ADDR']));
+ foreach ($sources as $_key => $_source) {
+ if (!empty($_SERVER[$_source])) {
+ if (($_valid_public_ip = $this->validPublicIp((string) $_SERVER[$_source]))) {
+ return ($ip = $_valid_public_ip);
+ }
+ }
+ unset($_key, $_source, $_valid_public_ip); // Housekeeping.
+ }
+ if (!empty($_SERVER['REMOTE_ADDR'])) {
+ return ($ip = strtolower((string) $_SERVER['REMOTE_ADDR']));
+ }
+ return ($ip = 'unknown'); // Not possible.
}
- return ($ip = 'unknown'); // Not possible.
-};
-/*
- * Gets a valid/public IP address.
- *
- * @since 150422 Rewrite.
- *
- * @param string $list_of_possible_ips A single IP, or a comma-delimited list of IPs.
- *
- * @return string A valid/public IP address (if one is found), else an empty string.
- *
- * @note This supports both IPv4 and IPv6 addresses.
- * @note See my tests against this here: http://3v4l.org/fVWUp
- */
-$self->validPublicIp = function ($list_of_possible_ips) use ($self) {
- if (!$list_of_possible_ips || !is_string($list_of_possible_ips)) {
- return ''; // Empty or invalid data.
- }
- if (!($list_of_possible_ips = trim($list_of_possible_ips))) {
- return ''; // Not possible; i.e., empty string.
- }
- foreach (preg_split('/[\s;,]+/', $list_of_possible_ips, -1, PREG_SPLIT_NO_EMPTY) as $_key => $_possible_ip) {
- if (($_valid_public_ip = filter_var(strtolower($_possible_ip), FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE))) {
- return $_valid_public_ip; // A valid public IPv4 or IPv6 address.
+ /*
+ * Gets a valid/public IP address.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $list_of_possible_ips A single IP, or a comma-delimited list of IPs.
+ *
+ * @return string A valid/public IP address (if one is found), else an empty string.
+ *
+ * @note This supports both IPv4 and IPv6 addresses.
+ * @note See my tests against this here: http://3v4l.org/fVWUp
+ */
+ public function validPublicIp($list_of_possible_ips)
+ {
+ if (!$list_of_possible_ips || !is_string($list_of_possible_ips)) {
+ return ''; // Empty or invalid data.
}
- }
- unset($_key, $_possible_ip, $_valid_public_ip); // Housekeeping.
+ if (!($list_of_possible_ips = trim($list_of_possible_ips))) {
+ return ''; // Not possible; i.e., empty string.
+ }
+ foreach (preg_split('/[\s;,]+/', $list_of_possible_ips, -1, PREG_SPLIT_NO_EMPTY) as $_key => $_possible_ip) {
+ if (($_valid_public_ip = filter_var(strtolower($_possible_ip), FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE))) {
+ return $_valid_public_ip; // A valid public IPv4 or IPv6 address.
+ }
+ }
+ unset($_key, $_possible_ip, $_valid_public_ip); // Housekeeping.
- return ''; // Default return value.
-};
+ return ''; // Default return value.
+ }
+}
diff --git a/src/includes/traits/Shared/PatternUtils.php b/src/includes/traits/Shared/PatternUtils.php
index 6dc98872..7ae83aa1 100644
--- a/src/includes/traits/Shared/PatternUtils.php
+++ b/src/includes/traits/Shared/PatternUtils.php
@@ -1,48 +1,52 @@
lineDelimitedPatternsToRegex = function ($patterns) use ($self) {
- $regex = ''; // Initialize list of regex patterns.
- $patterns = (string) $patterns;
+trait PatternUtils {
+ /*
+ * Convert line-delimited patterns to a regex.
+ *
+ * @since 151114 Enhancing exclusion pattern support.
+ *
+ * @param string $patterns Line-delimited list of patterns.
+ *
+ * @return string A `/(?:list|of|regex)/i` patterns.
+ */
+ public function lineDelimitedPatternsToRegex($patterns)
+ {
+ $regex = ''; // Initialize list of regex patterns.
+ $patterns = (string) $patterns;
- if (($patterns = preg_split('/['."\r\n".']+/', $patterns, -1, PREG_SPLIT_NO_EMPTY))) {
- $regex = '/(?:'.implode('|', array_map($self->wdRegexToActualRegexFrag, $patterns)).')/i';
+ if (($patterns = preg_split('/['."\r\n".']+/', $patterns, -1, PREG_SPLIT_NO_EMPTY))) {
+ $regex = '/(?:'.implode('|', array_map($this->wdRegexToActualRegexFrag, $patterns)).')/i';
+ }
+ return $regex;
}
- return $regex;
-};
-/*
- * Convert watered-down regex to actual regex.
- *
- * @since 151114 Enhancing exclusion pattern support.
- *
- * @param string $string Input watered-down regex to convert.
- *
- * @return string Actual regex pattern after conversion.
- */
-$self->wdRegexToActualRegexFrag = function ($string) use ($self) {
- return preg_replace(
- array(
- '/\\\\\^/',
- '/\\\\\*\\\\\*/',
- '/\\\\\*/',
- '/\\\\\$/',
- ),
- array(
- '^', // Beginning of line.
- '.*?', // Zero or more chars.
- '[^\/]*?', // Zero or more chars != /.
- '$', // End of line.
- ),
- preg_quote((string) $string, '/')
- );
-};
+ /*
+ * Convert watered-down regex to actual regex.
+ *
+ * @since 151114 Enhancing exclusion pattern support.
+ *
+ * @param string $string Input watered-down regex to convert.
+ *
+ * @return string Actual regex pattern after conversion.
+ */
+ public function wdRegexToActualRegexFrag($string)
+ {
+ return preg_replace(
+ [
+ '/\\\\\^/',
+ '/\\\\\*\\\\\*/',
+ '/\\\\\*/',
+ '/\\\\\$/',
+ ],
+ [
+ '^', // Beginning of line.
+ '.*?', // Zero or more chars.
+ '[^\/]*?', // Zero or more chars != /.
+ '$', // End of line.
+ ],
+ preg_quote((string) $string, '/')
+ );
+ }
+}
diff --git a/src/includes/traits/Shared/ReplaceUtils.php b/src/includes/traits/Shared/ReplaceUtils.php
index 30296809..29b5c238 100644
--- a/src/includes/traits/Shared/ReplaceUtils.php
+++ b/src/includes/traits/Shared/ReplaceUtils.php
@@ -1,43 +1,47 @@
strReplaceOnce = function ($needle, $replace, $haystack, $caSe_insensitive = false) use ($self) {
- $needle = (string) $needle;
- $replace = (string) $replace;
- $haystack = (string) $haystack;
- $caSe_strpos = $caSe_insensitive ? 'stripos' : 'strpos';
+trait ReplaceUtils {
+ /*
+ * String replace ONE time.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $needle A string to search/replace.
+ * @param string $replace What to replace `$needle` with.
+ * @param string $haystack The string/haystack to search in.
+ *
+ * @param boolean $caSe_insensitive Defaults to a `FALSE` value.
+ * Pass this as `TRUE` to a caSe-insensitive search/replace.
+ *
+ * @return string The `$haystack`, with `$needle` replaced with `$replace` ONE time only.
+ */
+ public function strReplaceOnce($needle, $replace, $haystack, $caSe_insensitive = false)
+ {
+ $needle = (string) $needle;
+ $replace = (string) $replace;
+ $haystack = (string) $haystack;
+ $caSe_strpos = $caSe_insensitive ? 'stripos' : 'strpos';
- if (($needle_strpos = $caSe_strpos($haystack, $needle)) === false) {
- return $haystack; // Nothing to replace.
+ if (($needle_strpos = $caSe_strpos($haystack, $needle)) === false) {
+ return $haystack; // Nothing to replace.
+ }
+ return (string) substr_replace($haystack, $replace, $needle_strpos, strlen($needle));
}
- return (string) substr_replace($haystack, $replace, $needle_strpos, strlen($needle));
-};
-/*
- * String replace ONE time (caSe-insensitive).
- *
- * @since 150422 Rewrite.
- *
- * @param string $needle A string to search/replace.
- * @param string $replace What to replace `$needle` with.
- * @param string $haystack The string/haystack to search in.
- *
- * @return string The `$haystack`, with `$needle` replaced with `$replace` ONE time only.
- */
-$self->strIreplaceOnce = function ($needle, $replace, $haystack) use ($self) {
- return $self->strReplaceOnce($needle, $replace, $haystack, true);
-};
+ /*
+ * String replace ONE time (caSe-insensitive).
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param string $needle A string to search/replace.
+ * @param string $replace What to replace `$needle` with.
+ * @param string $haystack The string/haystack to search in.
+ *
+ * @return string The `$haystack`, with `$needle` replaced with `$replace` ONE time only.
+ */
+ public function strIreplaceOnce($needle, $replace, $haystack)
+ {
+ return $this->strReplaceOnce($needle, $replace, $haystack, true);
+ }
+}
diff --git a/src/includes/traits/Shared/ServerUtils.php b/src/includes/traits/Shared/ServerUtils.php
index 25022f62..44f9186e 100644
--- a/src/includes/traits/Shared/ServerUtils.php
+++ b/src/includes/traits/Shared/ServerUtils.php
@@ -1,65 +1,70 @@
isApache = function () use ($self) {
- if (!is_null($is = &$self->staticKey('isApache'))) {
- return $is; // Already cached this.
- }
- if (!empty($_SERVER['SERVER_SOFTWARE']) && is_string($_SERVER['SERVER_SOFTWARE'])) {
- if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
- return ($is = true);
+trait ServerUtils {
+ /*
+ * Is running on Apache?
+ *
+ * @since 151002 This is Apache?
+ *
+ * @return bool True if running Apache.
+ */
+ public function isApache()
+ {
+ if (!is_null($is = &$this->staticKey('isApache'))) {
+ return $is; // Already cached this.
}
- if (stripos($_SERVER['SERVER_SOFTWARE'], 'litespeed') !== false) {
- return ($is = true);
+ if (!empty($_SERVER['SERVER_SOFTWARE']) && is_string($_SERVER['SERVER_SOFTWARE'])) {
+ if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
+ return ($is = true);
+ }
+ if (stripos($_SERVER['SERVER_SOFTWARE'], 'litespeed') !== false) {
+ return ($is = true);
+ }
}
+ return ($is = false);
}
- return ($is = false);
-};
-/*
- * Is running on Nginx?
- *
- * @since 151002 This is Nginx?
- *
- * @return bool True if running Nginx.
- */
-$self->isNginx = function () use ($self) {
- if (!is_null($is = &$self->staticKey('isNginx'))) {
- return $is; // Already cached this.
- }
- if (!empty($_SERVER['SERVER_SOFTWARE']) && is_string($_SERVER['SERVER_SOFTWARE'])) {
- if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
- return ($is = true);
+ /*
+ * Is running on Nginx?
+ *
+ * @since 151002 This is Nginx?
+ *
+ * @return bool True if running Nginx.
+ */
+ public function isNginx()
+ {
+ if (!is_null($is = &$this->staticKey('isNginx'))) {
+ return $is; // Already cached this.
}
+ if (!empty($_SERVER['SERVER_SOFTWARE']) && is_string($_SERVER['SERVER_SOFTWARE'])) {
+ if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
+ return ($is = true);
+ }
+ }
+ return ($is = false);
}
- return ($is = false);
-};
-/*
- * Is running on Windows IIS?
- *
- * @since 151002 This is Windows IIS?
- *
- * @return bool True if running Windows IIS.
- */
-$self->isIis = function () use ($self) {
- if (!is_null($is = &$self->staticKey('isIis'))) {
- return $is; // Already cached this.
- }
- if (!empty($_SERVER['SERVER_SOFTWARE']) && is_string($_SERVER['SERVER_SOFTWARE'])) {
- if (stripos($_SERVER['SERVER_SOFTWARE'], 'microsoft-iis') !== false) {
- return ($is = true);
+ /*
+ * Is running on Windows IIS?
+ *
+ * @since 151002 This is Windows IIS?
+ *
+ * @return bool True if running Windows IIS.
+ */
+ public function isIis()
+ {
+ if (!is_null($is = &$this->staticKey('isIis'))) {
+ return $is; // Already cached this.
}
- if (stripos($_SERVER['SERVER_SOFTWARE'], 'expressiondevserver') !== false) {
- return ($is = true);
+ if (!empty($_SERVER['SERVER_SOFTWARE']) && is_string($_SERVER['SERVER_SOFTWARE'])) {
+ if (stripos($_SERVER['SERVER_SOFTWARE'], 'microsoft-iis') !== false) {
+ return ($is = true);
+ }
+ if (stripos($_SERVER['SERVER_SOFTWARE'], 'expressiondevserver') !== false) {
+ return ($is = true);
+ }
}
+ return ($is = false);
}
- return ($is = false);
-};
+}
diff --git a/src/includes/traits/Shared/StringUtils.php b/src/includes/traits/Shared/StringUtils.php
index e7555085..a5617d4a 100644
--- a/src/includes/traits/Shared/StringUtils.php
+++ b/src/includes/traits/Shared/StringUtils.php
@@ -1,87 +1,91 @@
clip = function ($value, $max_length = 80, $force_ellipsis = false) use ($self) {
- if (is_array($value) || is_object($value)) {
- foreach ($value as $_key => &$_value) {
- $_value = $self->clip($_value, $max_length, $force_ellipsis);
- }
- unset($_key, $_value); // Housekeeping.
+trait StringUtils {
+ /*
+ * Clips string(s) to X chars deeply.
+ *
+ * @since 151114 Adding string utils.
+ *
+ * @param mixed $value Any input value.
+ * @param int $max_length Defaults to a value of `80`.
+ * @param bool $force_ellipsis Defaults to a value of `FALSE`.
+ *
+ * @return string|array|object Clipped value.
+ */
+ public function clip($value, $max_length = 80, $force_ellipsis = false)
+ {
+ if (is_array($value) || is_object($value)) {
+ foreach ($value as $_key => &$_value) {
+ $_value = $this->clip($_value, $max_length, $force_ellipsis);
+ }
+ unset($_key, $_value); // Housekeeping.
- return $value;
- }
- if (!($string = (string) $value)) {
- return $string; // Empty.
- }
- $max_length = max(4, $max_length);
+ return $value;
+ }
+ if (!($string = (string) $value)) {
+ return $string; // Empty.
+ }
+ $max_length = max(4, $max_length);
- $string = strip_tags($string);
- $string = preg_replace('/\s+/', ' ', strip_tags($string));
- $string = trim($string); // Trim it up now.
+ $string = strip_tags($string);
+ $string = preg_replace('/\s+/', ' ', strip_tags($string));
+ $string = trim($string); // Trim it up now.
- if (strlen($string) > $max_length) {
- $string = (string) substr($string, 0, $max_length - 3).'...';
- } elseif ($force_ellipsis && strlen($string) + 3 > $max_length) {
- $string = (string) substr($string, 0, $max_length - 3).'...';
- } else {
- $string .= $force_ellipsis ? '...' : '';
+ if (strlen($string) > $max_length) {
+ $string = (string) substr($string, 0, $max_length - 3).'...';
+ } elseif ($force_ellipsis && strlen($string) + 3 > $max_length) {
+ $string = (string) substr($string, 0, $max_length - 3).'...';
+ } else {
+ $string .= $force_ellipsis ? '...' : '';
+ }
+ return $string;
}
- return $string;
-};
-/*
- * Mid-clips string(s) to X chars deeply.
- *
- * @since 151114 Adding string utils.
- *
- * @param mixed $value Any input value.
- * @param int $max_length Defaults to a value of `80`.
- *
- * @return string|array|object Mid-clipped value.
- */
-$self->midClip = function ($value, $max_length = 80) use ($self) {
- if (is_array($value) || is_object($value)) {
- foreach ($value as $_key => &$_value) {
- $_value = $self->midClip($_value, $max_length);
- }
- unset($_key, $_value); // Housekeeping.
+ /*
+ * Mid-clips string(s) to X chars deeply.
+ *
+ * @since 151114 Adding string utils.
+ *
+ * @param mixed $value Any input value.
+ * @param int $max_length Defaults to a value of `80`.
+ *
+ * @return string|array|object Mid-clipped value.
+ */
+ public function midClip($value, $max_length = 80)
+ {
+ if (is_array($value) || is_object($value)) {
+ foreach ($value as $_key => &$_value) {
+ $_value = $this->midClip($_value, $max_length);
+ }
+ unset($_key, $_value); // Housekeeping.
- return $value;
- }
- if (!($string = (string) $value)) {
- return $string; // Empty.
- }
- $max_length = max(4, $max_length);
+ return $value;
+ }
+ if (!($string = (string) $value)) {
+ return $string; // Empty.
+ }
+ $max_length = max(4, $max_length);
- $string = strip_tags($string);
- $string = preg_replace('/\s+/', ' ', strip_tags($string));
- $string = trim($string); // Trim it up now.
+ $string = strip_tags($string);
+ $string = preg_replace('/\s+/', ' ', strip_tags($string));
+ $string = trim($string); // Trim it up now.
- if (strlen($string) <= $max_length) {
- return $string; // Nothing to do.
- }
- $full_string = $string;
- $half_max_length = floor($max_length / 2);
+ if (strlen($string) <= $max_length) {
+ return $string; // Nothing to do.
+ }
+ $full_string = $string;
+ $half_max_length = floor($max_length / 2);
- $first_clip = $half_max_length - 3;
- $string = $first_clip >= 1 // Something?
- ? substr($full_string, 0, $first_clip).'...'
- : '...'; // Ellipsis only.
+ $first_clip = $half_max_length - 3;
+ $string = $first_clip >= 1 // Something?
+ ? substr($full_string, 0, $first_clip).'...'
+ : '...'; // Ellipsis only.
- $second_clip = strlen($full_string) - ($max_length - strlen($string));
- $string .= $second_clip >= 0 && $second_clip >= $first_clip
- ? substr($full_string, $second_clip) : '';
+ $second_clip = strlen($full_string) - ($max_length - strlen($string));
+ $string .= $second_clip >= 0 && $second_clip >= $first_clip
+ ? substr($full_string, $second_clip) : '';
- return $string;
-};
+ return $string;
+ }
+}
diff --git a/src/includes/traits/Shared/SysUtils.php b/src/includes/traits/Shared/SysUtils.php
index 4c6fd857..5165db55 100644
--- a/src/includes/traits/Shared/SysUtils.php
+++ b/src/includes/traits/Shared/SysUtils.php
@@ -1,92 +1,97 @@
sysLoadAverages = function () use ($self) {
- if (!is_null($averages = &$self->cacheKey('sysLoadAverages'))) {
- return $averages; // Already cached these.
- }
- if (!$self->functionIsPossible('sys_getloadavg')) {
- return ($averages = array());
- }
- if (!is_array($averages = sys_getloadavg()) || !$averages) {
- return ($averages = array());
- }
- $averages = array_map('floatval', $averages);
- $averages = array_slice($averages, 0, 3);
- // i.e., 1m, 5m, 15m; see:
-
- return $averages;
-};
+trait SysUtils {
+ /*
+ * System load averages.
+ *
+ * @since 151002 Adding cache directory statistics.
+ *
+ * @return array System load averages.
+ */
+ public function sysLoadAverages()
+ {
+ if (!is_null($averages = &$this->cacheKey('sysLoadAverages'))) {
+ return $averages; // Already cached these.
+ }
+ if (!$this->functionIsPossible('sys_getloadavg')) {
+ return ($averages = []);
+ }
+ if (!is_array($averages = sys_getloadavg()) || !$averages) {
+ return ($averages = []);
+ }
+ $averages = array_map('floatval', $averages);
+ $averages = array_slice($averages, 0, 3);
+ // i.e., 1m, 5m, 15m; see:
-/*
- * System memory info.
- *
- * @since 151002 Adding cache directory statistics.
- *
- * @return \stdClass|boolean System memory info.
- */
-$self->sysMemoryStatus = function () use ($self) {
- if (!is_null($status = &$self->cacheKey('sysMemoryStatus'))) {
- return $status; // Already cached this.
- }
- if (!$self->functionIsPossible('shell_exec')) {
- return ($status = false);
- }
- if (!($free = trim((string) @shell_exec('free')))) {
- return ($status = false);
- }
- if (!($free_lines = explode("\n", $free))) {
- return ($status = false);
- }
- if (empty($free_lines[1])) {
- return ($status = false);
+ return $averages;
}
- if (!($memory = explode(' ', $free_lines[1]))) {
- return ($status = false);
- }
- if (!($memory = array_merge(array_filter($memory)))) {
- return ($status = false);
- }
- if (!isset($memory[1], $memory[2])) {
- return ($status = false);
- }
- if (($total = (integer) $memory[1]) <= 0) {
- return ($status = false);
- }
- $used = (integer) $memory[2];
- $percent = $used / $total * 100;
- $percentage = sprintf(__('%s%%', SLUG_TD), number_format($percent, 2, '.', ''));
- $status = (object) compact('total', 'used', 'percent', 'percentage');
- return $status;
-};
+ /*
+ * System memory info.
+ *
+ * @since 151002 Adding cache directory statistics.
+ *
+ * @return \stdClass|boolean System memory info.
+ */
+ public function sysMemoryStatus()
+ {
+ if (!is_null($status = &$this->cacheKey('sysMemoryStatus'))) {
+ return $status; // Already cached this.
+ }
+ if (!$this->functionIsPossible('shell_exec')) {
+ return ($status = false);
+ }
+ if (!($free = trim((string) @shell_exec('free')))) {
+ return ($status = false);
+ }
+ if (!($free_lines = explode("\n", $free))) {
+ return ($status = false);
+ }
+ if (empty($free_lines[1])) {
+ return ($status = false);
+ }
+ if (!($memory = explode(' ', $free_lines[1]))) {
+ return ($status = false);
+ }
+ if (!($memory = array_merge(array_filter($memory)))) {
+ return ($status = false);
+ }
+ if (!isset($memory[1], $memory[2])) {
+ return ($status = false);
+ }
+ if (($total = (integer) $memory[1]) <= 0) {
+ return ($status = false);
+ }
+ $used = (integer) $memory[2];
+ $percent = $used / $total * 100;
+ $percentage = sprintf(__('%s%%', SLUG_TD), number_format($percent, 2, '.', ''));
+ $status = (object) compact('total', 'used', 'percent', 'percentage');
-/*
- * System opcache status/details.
- *
- * @since 151002 Adding cache directory statistics.
- *
- * @return \stdClass|boolean System opcache status/details.
- */
-$self->sysOpcacheStatus = function () use ($self) {
- if (!is_null($status = &$self->cacheKey('sysOpcacheStatus'))) {
- return $status; // Already cached this.
+ return $status;
}
- if (!$self->functionIsPossible('opcache_get_status')) {
- return ($status = false);
- }
- if (!is_array($status = opcache_get_status(false)) || !$status) {
- return ($status = false);
- }
- if (empty($status['opcache_enabled'])) {
- return ($status = false);
- }
- return json_decode(json_encode($status));
-};
+
+ /*
+ * System opcache status/details.
+ *
+ * @since 151002 Adding cache directory statistics.
+ *
+ * @return \stdClass|boolean System opcache status/details.
+ */
+ public function sysOpcacheStatus()
+ {
+ if (!is_null($status = &$this->cacheKey('sysOpcacheStatus'))) {
+ return $status; // Already cached this.
+ }
+ if (!$this->functionIsPossible('opcache_get_status')) {
+ return ($status = false);
+ }
+ if (!is_array($status = opcache_get_status(false)) || !$status) {
+ return ($status = false);
+ }
+ if (empty($status['opcache_enabled'])) {
+ return ($status = false);
+ }
+ return json_decode(json_encode($status));
+ }
+}
diff --git a/src/includes/traits/Shared/TokenUtils.php b/src/includes/traits/Shared/TokenUtils.php
index 46e057cd..f3787178 100644
--- a/src/includes/traits/Shared/TokenUtils.php
+++ b/src/includes/traits/Shared/TokenUtils.php
@@ -1,346 +1,356 @@
hostToken = function ($dashify = false, $consider_domain_mapping = false, $consider_domain_mapping_domain = '') use ($self) {
- if (!is_null($token = &$self->staticKey('hostToken', array($dashify, $consider_domain_mapping, $consider_domain_mapping_domain)))) {
- return $token; // Already cached this.
- }
- $token = ''; // Initialize token value.
+ /*
+ * Current host.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param boolean $dashify Optional, defaults to a `FALSE` value.
+ * If `TRUE`, the token is returned with dashes in place of `[^a-z0-9]`.
+ *
+ * @param boolean $consider_domain_mapping Consider?
+ *
+ * @param string $consider_domain_mapping_domain A specific domain?
+ *
+ * @return string Current host.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function hostToken($dashify = false, $consider_domain_mapping = false, $consider_domain_mapping_domain = '')
+ {
+ if (!is_null($token = &$this->staticKey('hostToken', [$dashify, $consider_domain_mapping, $consider_domain_mapping_domain]))) {
+ return $token; // Already cached this.
+ }
+ $token = ''; // Initialize token value.
- if (!is_multisite() || $self->isAdvancedCache()) {
- $token = (string) $_SERVER['HTTP_HOST'];
- } elseif ($consider_domain_mapping && $self->canConsiderDomainMapping()) {
- if (($consider_domain_mapping_domain = trim((string) $consider_domain_mapping_domain))) {
- $token = $consider_domain_mapping_domain;
- } elseif ($self->isDomainMapping()) {
+ if (!is_multisite() || $this->isAdvancedCache()) {
$token = (string) $_SERVER['HTTP_HOST'];
- } else { // For the current blog ID.
- $token = $self->domainMappingUrlFilter($self->currentUrl());
- $token = $self->parseUrl($token, PHP_URL_HOST);
+ } elseif ($consider_domain_mapping && $this->canConsiderDomainMapping()) {
+ if (($consider_domain_mapping_domain = trim((string) $consider_domain_mapping_domain))) {
+ $token = $consider_domain_mapping_domain;
+ } elseif ($this->isDomainMapping()) {
+ $token = (string) $_SERVER['HTTP_HOST'];
+ } else { // For the current blog ID.
+ $token = $this->domainMappingUrlFilter($this->currentUrl());
+ $token = $this->parseUrl($token, PHP_URL_HOST);
+ }
}
- }
- if (!$token) { // Use default?
- $token = (string) $_SERVER['HTTP_HOST'];
- }
- if ($token) { // Have token?
- $token = strtolower($token);
- if ($dashify) { // Dashify it?
- $token = preg_replace('/[^a-z0-9]/i', '-', $token);
- $token = trim($token, '-');
+ if (!$token) { // Use default?
+ $token = (string) $_SERVER['HTTP_HOST'];
}
+ if ($token) { // Have token?
+ $token = strtolower($token);
+ if ($dashify) { // Dashify it?
+ $token = preg_replace('/[^a-z0-9]/i', '-', $token);
+ $token = trim($token, '-');
+ }
+ }
+ return $token;
}
- return $token;
-};
-/*
- * Host for a specific blog.
- *
- * @since 150821 Improving multisite compat.
- *
- * @param boolean $dashify Optional, defaults to a `FALSE` value.
- * If `TRUE`, the token is returned with dashes in place of `[^a-z0-9]`.
- *
- * @param boolean $consider_domain_mapping Consider?
- *
- * @param string $consider_domain_mapping_domain A specific domain?
- *
- * @param boolean $fallback Fallback on blog's domain when mapping?
- *
- * @param integer $blog_id For which blog ID?
- *
- * @return string Host for a specific blog.
- *
- * @note The return value of this function is NOT cached in support of `switch_to_blog()`.
- */
-$self->hostTokenForBlog = function ($dashify = false, $consider_domain_mapping = false, $consider_domain_mapping_domain = '', $fallback = false, $blog_id = 0) use ($self) {
- if (!is_multisite() || $self->isAdvancedCache()) {
- return $self->hostToken($dashify, $consider_domain_mapping, $consider_domain_mapping_domain);
- }
- $token = ''; // Initialize token value.
+ /*
+ * Host for a specific blog.
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @param boolean $dashify Optional, defaults to a `FALSE` value.
+ * If `TRUE`, the token is returned with dashes in place of `[^a-z0-9]`.
+ *
+ * @param boolean $consider_domain_mapping Consider?
+ *
+ * @param string $consider_domain_mapping_domain A specific domain?
+ *
+ * @param boolean $fallback Fallback on blog's domain when mapping?
+ *
+ * @param integer $blog_id For which blog ID?
+ *
+ * @return string Host for a specific blog.
+ *
+ * @note The return value of this function is NOT cached in support of `switch_to_blog()`.
+ */
+ public function hostTokenForBlog($dashify = false, $consider_domain_mapping = false, $consider_domain_mapping_domain = '', $fallback = false, $blog_id = 0)
+ {
+ if (!is_multisite() || $this->isAdvancedCache()) {
+ return $this->hostToken($dashify, $consider_domain_mapping, $consider_domain_mapping_domain);
+ }
+ $token = ''; // Initialize token value.
- if ($consider_domain_mapping && $self->canConsiderDomainMapping()) {
- if (($consider_domain_mapping_domain = trim((string) $consider_domain_mapping_domain))) {
- $token = $consider_domain_mapping_domain; // Force this value.
- } else {
- $token = $self->domainMappingBlogDomain($blog_id, $fallback);
+ if ($consider_domain_mapping && $this->canConsiderDomainMapping()) {
+ if (($consider_domain_mapping_domain = trim((string) $consider_domain_mapping_domain))) {
+ $token = $consider_domain_mapping_domain; // Force this value.
+ } else {
+ $token = $this->domainMappingBlogDomain($blog_id, $fallback);
+ }
+ } elseif (($blog_details = $this->blogDetails($blog_id))) {
+ $token = $blog_details->domain; // Unmapped domain.
}
- } elseif (($blog_details = $self->blogDetails($blog_id))) {
- $token = $blog_details->domain; // Unmapped domain.
- }
- if ($token) { // Have token?
- $token = strtolower($token);
- if ($dashify) { // Dashify it?
- $token = preg_replace('/[^a-z0-9]/i', '-', $token);
- $token = trim($token, '-');
+ if ($token) { // Have token?
+ $token = strtolower($token);
+ if ($dashify) { // Dashify it?
+ $token = preg_replace('/[^a-z0-9]/i', '-', $token);
+ $token = trim($token, '-');
+ }
}
+ return $token;
}
- return $token;
-};
-/*
- * Current site's base directory.
- *
- * @since 150422 Rewrite.
- *
- * @param boolean $dashify Optional, defaults to a `FALSE` value.
- * If `TRUE`, the token is returned with dashes in place of `[^a-z0-9\/]`.
- *
- * @param boolean $consider_domain_mapping Consider?
- *
- * @return string Current site's base directory.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->hostBaseToken = function ($dashify = false, $consider_domain_mapping = false) use ($self) {
- if (!is_null($token = &$self->staticKey('hostBaseToken', array($dashify, $consider_domain_mapping)))) {
- return $token; // Already cached this.
- }
- $token = '/'; // Assume NOT multisite; or own domain.
-
- if (!is_multisite()) {
- return $token; // Not applicable.
- }
- if (defined('SUBDOMAIN_INSTALL') && SUBDOMAIN_INSTALL) {
- return $token; // Not applicable.
- }
- if ($consider_domain_mapping && $self->canConsiderDomainMapping()) {
- return $token; // Not applicable.
- }
- if (defined('PATH_CURRENT_SITE')) {
- $token = (string) PATH_CURRENT_SITE;
- }
- $token = trim($token, '\\/'." \t\n\r\0\x0B");
- $token = isset($token[0]) ? '/'.$token.'/' : '/';
-
- if ($token !== '/' && $dashify) {
- $token = preg_replace('/[^a-z0-9\/]/i', '-', $token);
- $token = trim($token, '-');
- }
- return $token;
-};
-
-/*
- * Current blog's sub-directory.
- *
- * @since 150422 Rewrite.
- *
- * @param boolean $dashify Optional, defaults to a `FALSE` value.
- * If `TRUE`, the token is returned with dashes in place of `[^a-z0-9\/]`.
- *
- * @param boolean $consider_domain_mapping Consider?
- *
- * @param string $path Defaults to the current URI path.
- *
- * @return string Current blog's sub-directory.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->hostDirToken = function ($dashify = false, $consider_domain_mapping = false, $path = null) use ($self) {
- if (!isset($path)) { // Use current/default path?
- $path = (string) $self->parseUrl($_SERVER['REQUEST_URI'], PHP_URL_PATH);
- }
- $path = '/'.ltrim((string) $path, '/'); // Force leading slash.
+ /*
+ * Current site's base directory.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param boolean $dashify Optional, defaults to a `FALSE` value.
+ * If `TRUE`, the token is returned with dashes in place of `[^a-z0-9\/]`.
+ *
+ * @param boolean $consider_domain_mapping Consider?
+ *
+ * @return string Current site's base directory.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function hostBaseToken($dashify = false, $consider_domain_mapping = false)
+ {
+ if (!is_null($token = &$this->staticKey('hostBaseToken', [$dashify, $consider_domain_mapping]))) {
+ return $token; // Already cached this.
+ }
+ $token = '/'; // Assume NOT multisite; or own domain.
- if (!is_null($token = &$self->staticKey('hostDirToken', array($dashify, $consider_domain_mapping, $path)))) {
- return $token; // Already cached this.
- }
- $token = '/'; // Assume NOT multisite; or own domain.
+ if (!is_multisite()) {
+ return $token; // Not applicable.
+ }
+ if (defined('SUBDOMAIN_INSTALL') && SUBDOMAIN_INSTALL) {
+ return $token; // Not applicable.
+ }
+ if ($consider_domain_mapping && $this->canConsiderDomainMapping()) {
+ return $token; // Not applicable.
+ }
+ if (defined('PATH_CURRENT_SITE')) {
+ $token = (string) PATH_CURRENT_SITE;
+ }
+ $token = trim($token, '\\/'." \t\n\r\0\x0B");
+ $token = isset($token[0]) ? '/'.$token.'/' : '/';
- if (!is_multisite()) {
- return $token; // Not applicable.
- }
- if (defined('SUBDOMAIN_INSTALL') && SUBDOMAIN_INSTALL) {
- return $token; // Not applicable.
- }
- if ($consider_domain_mapping && $self->canConsiderDomainMapping()) {
- return $token; // Not applicable.
- }
- if ($path && $path !== '/' && ($host_base_token = trim($self->hostBaseToken(), '/'))) {
- $path_minus_base = preg_replace('/^\/'.preg_quote($host_base_token, '/').'(\/|$)/i', '${1}', $path);
- } else {
- $path_minus_base = $path; // Default value.
+ if ($token !== '/' && $dashify) {
+ $token = preg_replace('/[^a-z0-9\/]/i', '-', $token);
+ $token = trim($token, '-');
+ }
+ return $token;
}
- list($token) = explode('/', trim($path_minus_base, '/'));
- $token = trim($token, '\\/'." \t\n\r\0\x0B");
- $token = isset($token[0]) ? '/'.$token.'/' : '/';
- if ($token !== '/') { // Perhaps NOT the main site?
- $blog_paths_file = $self->cacheDir().'/'.strtolower(SHORT_NAME).'-blog-paths';
- if (!is_file($blog_paths_file) || !in_array($token, unserialize(file_get_contents($blog_paths_file)), true)) {
- $token = '/'; // NOT a real/valid child blog path.
+ /*
+ * Current blog's sub-directory.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param boolean $dashify Optional, defaults to a `FALSE` value.
+ * If `TRUE`, the token is returned with dashes in place of `[^a-z0-9\/]`.
+ *
+ * @param boolean $consider_domain_mapping Consider?
+ *
+ * @param string $path Defaults to the current URI path.
+ *
+ * @return string Current blog's sub-directory.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function hostDirToken($dashify = false, $consider_domain_mapping = false, $path = null)
+ {
+ if (!isset($path)) { // Use current/default path?
+ $path = (string) $this->parseUrl($_SERVER['REQUEST_URI'], PHP_URL_PATH);
}
- }
- if ($token !== '/' && $dashify) {
- $token = preg_replace('/[^a-z0-9\/]/i', '-', $token);
- $token = trim($token, '-');
- }
- return $token;
-};
+ $path = '/'.ltrim((string) $path, '/'); // Force leading slash.
-/*
- * A blog's sub-directory.
- *
- * @since 150821 Improving multisite compat.
- *
- * @param boolean $dashify Optional, defaults to a `FALSE` value.
- * If `TRUE`, the token is returned with dashes in place of `[^a-z0-9]`.
- *
- * @param boolean $consider_domain_mapping Consider?
- *
- * @param integer $blog_id For which blog ID?
- *
- * @return string A blog's sub-directory.
- *
- * @note The return value of this function is NOT cached in support of `switch_to_blog()`.
- */
-$self->hostDirTokenForBlog = function ($dashify = false, $consider_domain_mapping = false, $blog_id = 0) use ($self) {
- if (!is_multisite() || $self->isAdvancedCache()) {
- return $self->hostDirToken($dashify, $consider_domain_mapping);
- }
- $token = '/'; // Initialize token value.
+ if (!is_null($token = &$this->staticKey('hostDirToken', [$dashify, $consider_domain_mapping, $path]))) {
+ return $token; // Already cached this.
+ }
+ $token = '/'; // Assume NOT multisite; or own domain.
- if (defined('SUBDOMAIN_INSTALL') && SUBDOMAIN_INSTALL) {
- return $token; // Not applicable.
- }
- if ($consider_domain_mapping && $self->canConsiderDomainMapping()) {
- return $token; // Not applicable.
- }
- if (($blog_details = $self->blogDetails($blog_id))) {
- $path = $blog_details->path; // e.g., `[/base]/path/` (includes base).
- if ($path && $path !== '/' && ($host_base_token = trim($self->hostBaseToken(), '/'))) {
+ if (!is_multisite()) {
+ return $token; // Not applicable.
+ }
+ if (defined('SUBDOMAIN_INSTALL') && SUBDOMAIN_INSTALL) {
+ return $token; // Not applicable.
+ }
+ if ($consider_domain_mapping && $this->canConsiderDomainMapping()) {
+ return $token; // Not applicable.
+ }
+ if ($path && $path !== '/' && ($host_base_token = trim($this->hostBaseToken(), '/'))) {
$path_minus_base = preg_replace('/^\/'.preg_quote($host_base_token, '/').'(\/|$)/i', '${1}', $path);
} else {
$path_minus_base = $path; // Default value.
}
list($token) = explode('/', trim($path_minus_base, '/'));
- }
- $token = trim($token, '\\/'." \t\n\r\0\x0B");
- $token = isset($token[0]) ? '/'.$token.'/' : '/';
+ $token = trim($token, '\\/'." \t\n\r\0\x0B");
+ $token = isset($token[0]) ? '/'.$token.'/' : '/';
- if ($token !== '/') { // Perhaps NOT the main site?
- $blog_paths_file = $self->cacheDir().'/'.strtolower(SHORT_NAME).'-blog-paths';
- if (!is_file($blog_paths_file) || !in_array($token, unserialize(file_get_contents($blog_paths_file)), true)) {
- $token = '/'; // NOT a real/valid child blog path.
+ if ($token !== '/') { // Perhaps NOT the main site?
+ $blog_paths_file = $this->cacheDir().'/'.strtolower(SHORT_NAME).'-blog-paths';
+ if (!is_file($blog_paths_file) || !in_array($token, unserialize(file_get_contents($blog_paths_file)), true)) {
+ $token = '/'; // NOT a real/valid child blog path.
+ }
}
+ if ($token !== '/' && $dashify) {
+ $token = preg_replace('/[^a-z0-9\/]/i', '-', $token);
+ $token = trim($token, '-');
+ }
+ return $token;
}
- if ($token !== '/' && $dashify) {
- $token = preg_replace('/[^a-z0-9\/]/i', '-', $token);
- $token = trim($token, '-');
- }
- return $token;
-};
-/*
- * Current site's base directory & current blog's sub-directory.
- *
- * @since 150422 Rewrite.
- *
- * @param boolean $dashify Optional, defaults to a `FALSE` value.
- * If `TRUE`, the tokens are returned with dashes in place of `[^a-z0-9\/]`.
- *
- * @param boolean $consider_domain_mapping Consider?
- *
- * @param string $path Defaults to the current URI path.
- *
- * @return string Current site's base directory & current blog's sub-directory.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->hostBaseDirTokens = function ($dashify = false, $consider_domain_mapping = false, $path = null) use ($self) {
- if (!is_null($tokens = &$self->staticKey('hostBaseDirTokens', array($dashify, $consider_domain_mapping, $path)))) {
- return $tokens; // Already cached this.
+ /*
+ * A blog's sub-directory.
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @param boolean $dashify Optional, defaults to a `FALSE` value.
+ * If `TRUE`, the token is returned with dashes in place of `[^a-z0-9]`.
+ *
+ * @param boolean $consider_domain_mapping Consider?
+ *
+ * @param integer $blog_id For which blog ID?
+ *
+ * @return string A blog's sub-directory.
+ *
+ * @note The return value of this function is NOT cached in support of `switch_to_blog()`.
+ */
+ public function hostDirTokenForBlog($dashify = false, $consider_domain_mapping = false, $blog_id = 0)
+ {
+ if (!is_multisite() || $this->isAdvancedCache()) {
+ return $this->hostDirToken($dashify, $consider_domain_mapping);
+ }
+ $token = '/'; // Initialize token value.
+
+ if (defined('SUBDOMAIN_INSTALL') && SUBDOMAIN_INSTALL) {
+ return $token; // Not applicable.
+ }
+ if ($consider_domain_mapping && $this->canConsiderDomainMapping()) {
+ return $token; // Not applicable.
+ }
+ if (($blog_details = $this->blogDetails($blog_id))) {
+ $path = $blog_details->path; // e.g., `[/base]/path/` (includes base).
+ if ($path && $path !== '/' && ($host_base_token = trim($this->hostBaseToken(), '/'))) {
+ $path_minus_base = preg_replace('/^\/'.preg_quote($host_base_token, '/').'(\/|$)/i', '${1}', $path);
+ } else {
+ $path_minus_base = $path; // Default value.
+ }
+ list($token) = explode('/', trim($path_minus_base, '/'));
+ }
+ $token = trim($token, '\\/'." \t\n\r\0\x0B");
+ $token = isset($token[0]) ? '/'.$token.'/' : '/';
+
+ if ($token !== '/') { // Perhaps NOT the main site?
+ $blog_paths_file = $this->cacheDir().'/'.strtolower(SHORT_NAME).'-blog-paths';
+ if (!is_file($blog_paths_file) || !in_array($token, unserialize(file_get_contents($blog_paths_file)), true)) {
+ $token = '/'; // NOT a real/valid child blog path.
+ }
+ }
+ if ($token !== '/' && $dashify) {
+ $token = preg_replace('/[^a-z0-9\/]/i', '-', $token);
+ $token = trim($token, '-');
+ }
+ return $token;
}
- $tokens = $self->hostBaseToken($dashify, $consider_domain_mapping);
- $tokens .= $self->hostDirToken($dashify, $consider_domain_mapping, $path);
- return ($tokens = preg_replace('/\/+/', '/', $tokens));
-};
+ /*
+ * Current site's base directory & current blog's sub-directory.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param boolean $dashify Optional, defaults to a `FALSE` value.
+ * If `TRUE`, the tokens are returned with dashes in place of `[^a-z0-9\/]`.
+ *
+ * @param boolean $consider_domain_mapping Consider?
+ *
+ * @param string $path Defaults to the current URI path.
+ *
+ * @return string Current site's base directory & current blog's sub-directory.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function hostBaseDirTokens($dashify = false, $consider_domain_mapping = false, $path = null)
+ {
+ if (!is_null($tokens = &$this->staticKey('hostBaseDirTokens', [$dashify, $consider_domain_mapping, $path]))) {
+ return $tokens; // Already cached this.
+ }
+ $tokens = $this->hostBaseToken($dashify, $consider_domain_mapping);
+ $tokens .= $this->hostDirToken($dashify, $consider_domain_mapping, $path);
-/*
- * A site's base directory & a blog's sub-directory.
- *
- * @since 150821 Improving multisite compat.
- *
- * @param boolean $dashify Optional, defaults to a `FALSE` value.
- * If `TRUE`, the tokens are returned with dashes in place of `[^a-z0-9\/]`.
- *
- * @param boolean $consider_domain_mapping Consider?
- *
- * @param integer $blog_id For which blog ID?
- *
- * @return string A site's base directory & a blog's sub-directory.
- *
- * @note The return value of this function is NOT cached in support of `switch_to_blog()`.
- */
-$self->hostBaseDirTokensForBlog = function ($dashify = false, $consider_domain_mapping = false, $blog_id = 0) use ($self) {
- $tokens = $self->hostBaseToken($dashify, $consider_domain_mapping);
- $tokens .= $self->hostDirTokenForBlog($dashify, $consider_domain_mapping, $blog_id);
+ return ($tokens = preg_replace('/\/+/', '/', $tokens));
+ }
- return ($tokens = preg_replace('/\/+/', '/', $tokens));
-};
+ /*
+ * A site's base directory & a blog's sub-directory.
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @param boolean $dashify Optional, defaults to a `FALSE` value.
+ * If `TRUE`, the tokens are returned with dashes in place of `[^a-z0-9\/]`.
+ *
+ * @param boolean $consider_domain_mapping Consider?
+ *
+ * @param integer $blog_id For which blog ID?
+ *
+ * @return string A site's base directory & a blog's sub-directory.
+ *
+ * @note The return value of this function is NOT cached in support of `switch_to_blog()`.
+ */
+ public function hostBaseDirTokensForBlog($dashify = false, $consider_domain_mapping = false, $blog_id = 0)
+ {
+ $tokens = $this->hostBaseToken($dashify, $consider_domain_mapping);
+ $tokens .= $this->hostDirTokenForBlog($dashify, $consider_domain_mapping, $blog_id);
-/*[pro strip-from="lite"]*/
-/*
- * Produces a token based on the current user.
- *
- * @since 150422 Rewrite.
- *
- * @return string Produces a token based on the current user;
- * else an empty string if that's not possible to do.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- *
- * @note This routine may trigger a flag which indicates that the current user was logged-in at some point,
- * but now the login cookie can no longer be validated by WordPress; i.e. they are NOT actually logged in any longer.
- * See {@link $user_login_cookie_expired_or_invalid}
- *
- * @warning Do NOT call upon this method until WordPress reaches it's cache postload phase.
- */
-$self->userToken = function () use ($self) {
- if (!is_null($token = &$self->staticKey('userToken'))) {
- return $token; // Already cached this.
+ return ($tokens = preg_replace('/\/+/', '/', $tokens));
}
- if ($self->functionIsPossible('wp_validate_auth_cookie')) {
- if (($user_id = (integer) wp_validate_auth_cookie('', 'logged_in'))) {
- return ($token = (string) $user_id); // A real user in this case.
- } elseif (!empty($_COOKIE['wordpress_logged_in_'.COOKIEHASH])) {
- $self->user_login_cookie_expired_or_invalid = true;
+
+ /*[pro strip-from="lite"]*/
+ /*
+ * Produces a token based on the current user.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return string Produces a token based on the current user;
+ * else an empty string if that's not possible to do.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ *
+ * @note This routine may trigger a flag which indicates that the current user was logged-in at some point,
+ * but now the login cookie can no longer be validated by WordPress; i.e. they are NOT actually logged in any longer.
+ * See {@link $user_login_cookie_expired_or_invalid}
+ *
+ * @warning Do NOT call upon this method until WordPress reaches it's cache postload phase.
+ */
+ public function userToken()
+ {
+ if (!is_null($token = &$this->staticKey('userToken'))) {
+ return $token; // Already cached this.
}
+ if ($this->functionIsPossible('wp_validate_auth_cookie')) {
+ if (($user_id = (integer) wp_validate_auth_cookie('', 'logged_in'))) {
+ return ($token = (string) $user_id); // A real user in this case.
+ } elseif (!empty($_COOKIE['wordpress_logged_in_'.COOKIEHASH])) {
+ $this->user_login_cookie_expired_or_invalid = true;
+ }
+ }
+ if (!empty($_COOKIE['comment_author_email_'.COOKIEHASH])) {
+ return ($token = md5(strtolower(stripslashes((string) $_COOKIE['comment_author_email_'.COOKIEHASH]))));
+ } elseif (!empty($_COOKIE['wp-postpass_'.COOKIEHASH])) {
+ return ($token = md5(stripslashes((string) $_COOKIE['wp-postpass_'.COOKIEHASH])));
+ } elseif (defined('SID') && SID) {
+ return ($token = preg_replace('/[^a-z0-9]/i', '', (string) SID));
+ }
+ return ($token = '');
}
- if (!empty($_COOKIE['comment_author_email_'.COOKIEHASH])) {
- return ($token = md5(strtolower(stripslashes((string) $_COOKIE['comment_author_email_'.COOKIEHASH]))));
- } elseif (!empty($_COOKIE['wp-postpass_'.COOKIEHASH])) {
- return ($token = md5(stripslashes((string) $_COOKIE['wp-postpass_'.COOKIEHASH])));
- } elseif (defined('SID') && SID) {
- return ($token = preg_replace('/[^a-z0-9]/i', '', (string) SID));
- }
- return ($token = '');
-};
-/*[/pro]*/
+ /*[/pro]*/
+}
diff --git a/src/includes/traits/Shared/TrimUtils.php b/src/includes/traits/Shared/TrimUtils.php
index eeed46b6..963f7e79 100644
--- a/src/includes/traits/Shared/TrimUtils.php
+++ b/src/includes/traits/Shared/TrimUtils.php
@@ -1,36 +1,39 @@
trimDeep = function ($values, $chars = '', $extra_chars = '') use ($self) {
- if (is_array($values) || is_object($values)) {
- foreach ($values as $_key => &$_values) {
- $_values = $self->trimDeep($_values, $chars, $extra_chars);
- }
- unset($_key, $_values); // Housekeeping.
+trait TrimUtils {
+ /*
+ * Trims strings deeply.
+ *
+ * @since 150422 Rewrite.
+ *
+ * @param mixed $values Any value can be converted into a trimmed string.
+ * Actually, objects can't, but this recurses into objects.
+ *
+ * @param string $chars Specific chars to trim.
+ * Defaults to PHP's trim: " \r\n\t\0\x0B". Use an empty string to bypass.
+ *
+ * @param string $extra_chars Additional chars to trim.
+ *
+ * @return string|array|object Trimmed string, array, object.
+ */
+ public function trimDeep($values, $chars = '', $extra_chars = '')
+ {
+ if (is_array($values) || is_object($values)) {
+ foreach ($values as $_key => &$_values) {
+ $_values = $this->trimDeep($_values, $chars, $extra_chars);
+ }
+ unset($_key, $_values); // Housekeeping.
- return $values;
- }
- $string = (string) $values;
- $chars = (string) $chars;
- $extra_chars = (string) $extra_chars;
+ return $values;
+ }
+ $string = (string) $values;
+ $chars = (string) $chars;
+ $extra_chars = (string) $extra_chars;
- $chars = isset($chars[0]) ? $chars : " \r\n\t\0\x0B";
- $chars = $chars.$extra_chars; // Concatenate.
+ $chars = isset($chars[0]) ? $chars : " \r\n\t\0\x0B";
+ $chars = $chars.$extra_chars; // Concatenate.
- return trim($string, $chars);
-};
+ return trim($string, $chars);
+ }
+}
diff --git a/src/includes/traits/Shared/UrlUtils.php b/src/includes/traits/Shared/UrlUtils.php
index 34cd2377..0f6050c7 100644
--- a/src/includes/traits/Shared/UrlUtils.php
+++ b/src/includes/traits/Shared/UrlUtils.php
@@ -1,131 +1,137 @@
parseUrl = function ($url_uri_qsl, $component = -1) use ($self) {
- $url_uri_qsl = (string) $url_uri_qsl;
- $component = (integer) $component;
- ${'//'} = strpos($url_uri_qsl, '//') === 0;
+trait UrlUtils {
+ /*
+ * Parses a URL.
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @param string $url_uri_qsl Input URL, URI, or query string w/ a leading `?`.
+ * @param int $component Optional component to retrieve.
+ *
+ * @return array|string|int|null Array, else `string|int|null` component value.
+ */
+ public function parseUrl($url_uri_qsl, $component = -1)
+ {
+ $url_uri_qsl = (string) $url_uri_qsl;
+ $component = (integer) $component;
+ ${'//'} = strpos($url_uri_qsl, '//') === 0;
- if ($url_uri_qsl && strpos($url_uri_qsl, '&') !== false) {
- $url_uri_qsl = str_replace('&', '&', $url_uri_qsl);
- }
- if ($component > -1) {
- if (${'//'} && $component === PHP_URL_SCHEME) {
- return ($part = '//');
- }
- return ($part = parse_url($url_uri_qsl, $component));
- } else {
- if (!is_array($parts = parse_url($url_uri_qsl))) {
- return ($parts = array());
+ if ($url_uri_qsl && strpos($url_uri_qsl, '&') !== false) {
+ $url_uri_qsl = str_replace('&', '&', $url_uri_qsl);
}
- if (${'//'}) {
- $parts['scheme'] = '//';
+ if ($component > -1) {
+ if (${'//'} && $component === PHP_URL_SCHEME) {
+ return ($part = '//');
+ }
+ return ($part = parse_url($url_uri_qsl, $component));
+ } else {
+ if (!is_array($parts = parse_url($url_uri_qsl))) {
+ return ($parts = []);
+ }
+ if (${'//'}) {
+ $parts['scheme'] = '//';
+ }
+ return $parts;
}
- return $parts;
}
-};
-/*
- * Unparses a URL.
- *
- * @since 150821 Improving multisite compat.
- *
- * @param array $parts Input URL parts.
- *
- * @return string Unparsed URL in string format.
- */
-$self->unParseUrl = function (array $parts) use ($self) {
- $scheme = '';
- $host = '';
- $port = '';
- $user = '';
- $pass = '';
- $path = '';
- $query = '';
- $fragment = '';
+ /*
+ * Unparses a URL.
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @param array $parts Input URL parts.
+ *
+ * @return string Unparsed URL in string format.
+ */
+ public function unParseUrl(array $parts)
+ {
+ $scheme = '';
+ $host = '';
+ $port = '';
+ $user = '';
+ $pass = '';
+ $path = '';
+ $query = '';
+ $fragment = '';
- if (!empty($parts['scheme'])) {
- if ($parts['scheme'] === '//') {
- $scheme = $parts['scheme'];
- } else {
- $scheme = $parts['scheme'].'://';
+ if (!empty($parts['scheme'])) {
+ if ($parts['scheme'] === '//') {
+ $scheme = $parts['scheme'];
+ } else {
+ $scheme = $parts['scheme'].'://';
+ }
}
+ if (!empty($parts['host'])) {
+ $host = $parts['host'];
+ }
+ if (!empty($parts['port'])) {
+ $port = ':'.$parts['port'];
+ }
+ if (!empty($parts['user'])) {
+ $user = $parts['user'];
+ }
+ if (!empty($parts['pass'])) {
+ $pass = $parts['pass'];
+ }
+ if ($user || $pass) {
+ $pass .= '@';
+ }
+ if (!empty($parts['path'])) {
+ $path = '/'.ltrim($parts['path'], '/');
+ }
+ if (!empty($parts['query'])) {
+ $query = '?'.$parts['query'];
+ }
+ if (!empty($parts['fragment'])) {
+ $fragment = '#'.$parts['fragment'];
+ }
+ return $scheme.$user.$pass.$host.$port.$path.$query.$fragment;
}
- if (!empty($parts['host'])) {
- $host = $parts['host'];
- }
- if (!empty($parts['port'])) {
- $port = ':'.$parts['port'];
- }
- if (!empty($parts['user'])) {
- $user = $parts['user'];
- }
- if (!empty($parts['pass'])) {
- $pass = $parts['pass'];
- }
- if ($user || $pass) {
- $pass .= '@';
- }
- if (!empty($parts['path'])) {
- $path = '/'.ltrim($parts['path'], '/');
- }
- if (!empty($parts['query'])) {
- $query = '?'.$parts['query'];
- }
- if (!empty($parts['fragment'])) {
- $fragment = '#'.$parts['fragment'];
- }
- return $scheme.$user.$pass.$host.$port.$path.$query.$fragment;
-};
-/*
- * Is the current request over SSL?
- *
- * @since 150422 Rewrite.
- *
- * @return boolean `TRUE` if the current request is over SSL.
- *
- * @note The return value of this function is cached to reduce overhead on repeat calls.
- */
-$self->isSsl = function () use ($self) {
- if (!is_null($is = &$self->staticKey('isSsl'))) {
- return $is; // Already cached this.
- }
- if (!empty($_SERVER['SERVER_PORT'])) {
- if ((integer) $_SERVER['SERVER_PORT'] === 443) {
- return ($is = true);
+ /*
+ * Is the current request over SSL?
+ *
+ * @since 150422 Rewrite.
+ *
+ * @return boolean `TRUE` if the current request is over SSL.
+ *
+ * @note The return value of this function is cached to reduce overhead on repeat calls.
+ */
+ public function isSsl()
+ {
+ if (!is_null($is = &$this->staticKey('isSsl'))) {
+ return $is; // Already cached this.
}
- }
- if (!empty($_SERVER['HTTPS'])) {
- if (filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN)) {
- return ($is = true);
+ if (!empty($_SERVER['SERVER_PORT'])) {
+ if ((integer) $_SERVER['SERVER_PORT'] === 443) {
+ return ($is = true);
+ }
}
- }
- if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
- if (strcasecmp((string) $_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0) {
- return ($is = true);
+ if (!empty($_SERVER['HTTPS'])) {
+ if (filter_var($_SERVER['HTTPS'], FILTER_VALIDATE_BOOLEAN)) {
+ return ($is = true);
+ }
+ }
+ if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
+ if (strcasecmp((string) $_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0) {
+ return ($is = true);
+ }
}
+ return ($is = false);
}
- return ($is = false);
-};
-/*
- * Current URL.
- *
- * @since 150821 Improving multisite compat.
- *
- * @return string Current URL.
- */
-$self->currentUrl = function () use ($self) {
- return ($self->isSsl() ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
-};
+ /*
+ * Current URL.
+ *
+ * @since 150821 Improving multisite compat.
+ *
+ * @return string Current URL.
+ */
+ public function currentUrl()
+ {
+ return ($this->isSsl() ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
+ }
+}
From 8aba8cd205391b82a8791937485954b169d01260 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sat, 27 Feb 2016 22:30:34 -0500
Subject: [PATCH 005/112] Convert to Traits: Convert more references of $self
to $this
See websharks/comet-cache#635
---
src/includes/traits/Ac/AcPluginUtils.php | 2 +-
src/includes/traits/Ac/ObUtils.php | 4 ++--
src/includes/traits/Ac/PostloadUtils.php | 16 ++++++++--------
src/includes/traits/Plugin/MenuPageUtils.php | 16 ++++++++--------
src/includes/traits/Shared/CachePathUtils.php | 4 ++--
src/includes/traits/Shared/ConditionalUtils.php | 4 ++--
src/includes/traits/Shared/HookUtils.php | 8 ++++----
src/includes/traits/Shared/HttpUtils.php | 2 +-
8 files changed, 28 insertions(+), 28 deletions(-)
diff --git a/src/includes/traits/Ac/AcPluginUtils.php b/src/includes/traits/Ac/AcPluginUtils.php
index 532ba66e..32014a07 100644
--- a/src/includes/traits/Ac/AcPluginUtils.php
+++ b/src/includes/traits/Ac/AcPluginUtils.php
@@ -12,7 +12,7 @@ public function loadAcPlugins()
if (!is_dir(WP_CONTENT_DIR.'/ac-plugins')) {
return; // Nothing to do here.
}
- $GLOBALS[GLOBAL_NS.'_advanced_cache'] = $self; // Self reference.
+ $GLOBALS[GLOBAL_NS.'_advanced_cache'] = $this; // Self reference.
$GLOBALS[GLOBAL_NS.'__advanced_cache'] = &$GLOBALS[GLOBAL_NS.'_advanced_cache'];
if (!isset($GLOBALS['zencache__advanced_cache'])) {
$GLOBALS['zencache_advanced_cache'] = &$GLOBALS[GLOBAL_NS.'_advanced_cache'];
diff --git a/src/includes/traits/Ac/ObUtils.php b/src/includes/traits/Ac/ObUtils.php
index 7c5c92ab..822dd6e2 100644
--- a/src/includes/traits/Ac/ObUtils.php
+++ b/src/includes/traits/Ac/ObUtils.php
@@ -181,7 +181,7 @@ public function maybeStartOutputBuffering()
$this->version_salt = ''; // Initialize the version salt.
/*[pro strip-from="lite"]*/ // Fill the version salt in pro version.
$this->version_salt = COMET_CACHE_VERSION_SALT; // Initialize the version salt. /*[/pro]*/
- $this->version_salt = $this->applyFilters(get_class($self).'__version_salt', $this->version_salt);
+ $this->version_salt = $this->applyFilters(get_class($this).'__version_salt', $this->version_salt);
$this->version_salt = $this->applyFilters(GLOBAL_NS.'_version_salt', $this->version_salt);
$this->cache_path = $this->buildCachePath($this->protocol.$this->host_token.$_SERVER['REQUEST_URI'], '', $this->version_salt);
@@ -220,7 +220,7 @@ public function maybeStartOutputBuffering()
}
exit($cache); // Exit with cache contents.
} else {
- ob_start([$self, 'outputBufferCallbackHandler']);
+ ob_start([$this, 'outputBufferCallbackHandler']);
}
return; // Return value not applicable.
}
diff --git a/src/includes/traits/Ac/PostloadUtils.php b/src/includes/traits/Ac/PostloadUtils.php
index 6f4bc875..5b0fbe71 100644
--- a/src/includes/traits/Ac/PostloadUtils.php
+++ b/src/includes/traits/Ac/PostloadUtils.php
@@ -198,7 +198,7 @@ public function maybeStartObWhenLoggedInPostload()
}
exit($cache); // Exit with cache contents.
} else {
- ob_start([$self, 'outputBufferCallbackHandler']);
+ ob_start([$this, 'outputBufferCallbackHandler']);
}
return; // Only for IDEs not to complain here.
}
@@ -214,13 +214,13 @@ public function maybeFilterStatusHeaderPostload()
if (empty($this->postload['filter_status_header'])) {
return; // Nothing to do in this case.
}
- $_self = $self; // Reference needed below.
+ $_this = $this; // Reference needed below.
add_filter(
'status_header',
- function ($status_header, $status_code) use ($_self) {
+ function ($status_header, $status_code) use ($_this) {
if ($status_code > 0) {
- $_self->http_status = (integer) $status_code;
+ $_this->http_status = (integer) $status_code;
}
return $status_header;
},
@@ -248,7 +248,7 @@ public function maybeSetDebugInfoPostload()
if (strcasecmp(PHP_SAPI, 'cli') === 0) {
return; // Let's not run the risk here.
}
- add_action('shutdown', [$self, 'maybeEchoNcDebugInfo'], PHP_INT_MAX - 10);
+ add_action('shutdown', [$this, 'maybeEchoNcDebugInfo'], PHP_INT_MAX - 10);
}
/*
@@ -280,12 +280,12 @@ public function wpMainQueryPostload()
$this->is_user_logged_in = is_user_logged_in();
$this->content_url = rtrim(content_url(), '/');
$this->is_maintenance = $this->functionIsPossible('is_maintenance') && is_maintenance();
- $_self = $self; // Reference for the closure below.
+ $_this = $this; // Reference for the closure below.
add_action(
'template_redirect',
- function () use ($_self) {
- $_self->is_a_wp_content_type = $_self->is_404 || $_self->is_maintenance
+ function () use ($_this) {
+ $_this->is_a_wp_content_type = $_this->is_404 || $_this->is_maintenance
|| is_front_page() // See
|| is_home() || is_singular() || is_archive() || is_post_type_archive() || is_tax() || is_search() || is_feed();
},
diff --git a/src/includes/traits/Plugin/MenuPageUtils.php b/src/includes/traits/Plugin/MenuPageUtils.php
index 54574281..bfa0d791 100644
--- a/src/includes/traits/Plugin/MenuPageUtils.php
+++ b/src/includes/traits/Plugin/MenuPageUtils.php
@@ -75,17 +75,17 @@ public function addNetworkMenuPages()
$icon = file_get_contents(dirname(dirname(dirname(dirname(__FILE__)))).'/client-s/images/inline-icon.svg');
$icon = 'data:image/svg+xml;base64,'.base64_encode($this->colorSvgMenuIcon($icon));
- add_menu_page(NAME.(IS_PRO ? ' Pro' : ''), NAME.(IS_PRO ? ' Pro' : ''), $this->network_cap, GLOBAL_NS, [$self, 'menuPageOptions'], $icon);
- add_submenu_page(GLOBAL_NS, __('Plugin Options', SLUG_TD), __('Plugin Options', SLUG_TD), $this->network_cap, GLOBAL_NS, [$self, 'menuPageOptions']);
+ add_menu_page(NAME.(IS_PRO ? ' Pro' : ''), NAME.(IS_PRO ? ' Pro' : ''), $this->network_cap, GLOBAL_NS, [$this, 'menuPageOptions'], $icon);
+ add_submenu_page(GLOBAL_NS, __('Plugin Options', SLUG_TD), __('Plugin Options', SLUG_TD), $this->network_cap, GLOBAL_NS, [$this, 'menuPageOptions']);
/*[pro strip-from="lite"]*/
if ($this->options['stats_enable']) {
- add_submenu_page(GLOBAL_NS, __('Stats / Charts', SLUG_TD), __('Stats / Charts', SLUG_TD), $this->network_cap, GLOBAL_NS.'-stats', [$self, 'menuPageStats']);
+ add_submenu_page(GLOBAL_NS, __('Stats / Charts', SLUG_TD), __('Stats / Charts', SLUG_TD), $this->network_cap, GLOBAL_NS.'-stats', [$this, 'menuPageStats']);
} /*[/pro]*/
/*[pro strip-from="lite"]*/
if (current_user_can($this->network_cap)) {
- add_submenu_page(GLOBAL_NS, __('Pro Plugin Updater', SLUG_TD), __('Plugin Updater', SLUG_TD), $this->update_cap, GLOBAL_NS.'-pro-updater', [$self, 'menuPageProUpdater']);
+ add_submenu_page(GLOBAL_NS, __('Pro Plugin Updater', SLUG_TD), __('Plugin Updater', SLUG_TD), $this->update_cap, GLOBAL_NS.'-pro-updater', [$this, 'menuPageProUpdater']);
} /*[/pro]*/
}
@@ -104,16 +104,16 @@ public function addMenuPages()
$icon = file_get_contents(dirname(dirname(dirname(dirname(__FILE__)))).'/client-s/images/inline-icon.svg');
$icon = 'data:image/svg+xml;base64,'.base64_encode($this->colorSvgMenuIcon($icon));
- add_menu_page(NAME.(IS_PRO ? ' Pro' : ''), NAME.(IS_PRO ? ' Pro' : ''), $this->cap, GLOBAL_NS, [$self, 'menuPageOptions'], $icon);
- add_submenu_page(GLOBAL_NS, __('Plugin Options', SLUG_TD), __('Plugin Options', SLUG_TD), $this->cap, GLOBAL_NS, [$self, 'menuPageOptions']);
+ add_menu_page(NAME.(IS_PRO ? ' Pro' : ''), NAME.(IS_PRO ? ' Pro' : ''), $this->cap, GLOBAL_NS, [$this, 'menuPageOptions'], $icon);
+ add_submenu_page(GLOBAL_NS, __('Plugin Options', SLUG_TD), __('Plugin Options', SLUG_TD), $this->cap, GLOBAL_NS, [$this, 'menuPageOptions']);
/*[pro strip-from="lite"]*/
if ($this->options['stats_enable']) {
- add_submenu_page(GLOBAL_NS, __('Stats / Charts', SLUG_TD), __('Stats / Charts', SLUG_TD), $this->cap, GLOBAL_NS.'-stats', [$self, 'menuPageStats']);
+ add_submenu_page(GLOBAL_NS, __('Stats / Charts', SLUG_TD), __('Stats / Charts', SLUG_TD), $this->cap, GLOBAL_NS.'-stats', [$this, 'menuPageStats']);
} /*[/pro]*/
/*[pro strip-from="lite"]*/
- add_submenu_page(GLOBAL_NS, __('Pro Plugin Updater', SLUG_TD), __('Plugin Updater', SLUG_TD), $this->update_cap, GLOBAL_NS.'-pro-updater', [$self, 'menuPageProUpdater']);
+ add_submenu_page(GLOBAL_NS, __('Pro Plugin Updater', SLUG_TD), __('Plugin Updater', SLUG_TD), $this->update_cap, GLOBAL_NS.'-pro-updater', [$this, 'menuPageProUpdater']);
/*[/pro]*/
}
diff --git a/src/includes/traits/Shared/CachePathUtils.php b/src/includes/traits/Shared/CachePathUtils.php
index 1e90284f..77d8f1c3 100644
--- a/src/includes/traits/Shared/CachePathUtils.php
+++ b/src/includes/traits/Shared/CachePathUtils.php
@@ -311,7 +311,7 @@ public function buildHostCachePathRegexFragsFromWcUris($uris, $regex_suffix_frag
$uris = trim((string) $uris);
$regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
- $_self = $self; // Reference for the closure below.
+ $_this = $this; // Reference for the closure below.
$flags = CACHE_PATH_ALLOW_WILDCARDS | CACHE_PATH_NO_SCHEME | CACHE_PATH_NO_HOST
| CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
@@ -322,7 +322,7 @@ public function buildHostCachePathRegexFragsFromWcUris($uris, $regex_suffix_frag
foreach ($uri_patterns as $_key => &$_uri_pattern) {
if (($_uri_pattern = trim($_uri_pattern, '^$'))) {
- $_cache_path = $_self->buildCachePath($host_url.'/'.trim($_uri_pattern, '/'), '', '', $flags);
+ $_cache_path = $_this->buildCachePath($host_url.'/'.trim($_uri_pattern, '/'), '', '', $flags);
$_relative_cache_path = preg_replace('/^'.preg_quote($host_cache_path, '/').'(?:\/|$)/i', '', $_cache_path);
$_uri_pattern = $this->wdRegexToActualRegexFrag($_relative_cache_path);
}
diff --git a/src/includes/traits/Shared/ConditionalUtils.php b/src/includes/traits/Shared/ConditionalUtils.php
index 31003526..7273ec4c 100644
--- a/src/includes/traits/Shared/ConditionalUtils.php
+++ b/src/includes/traits/Shared/ConditionalUtils.php
@@ -37,7 +37,7 @@ trait ConditionalUtils {
*/
public function isAdvancedCache()
{
- return $self instanceof AdvancedCache;
+ return $this instanceof AdvancedCache;
}
/*
@@ -49,7 +49,7 @@ public function isAdvancedCache()
*/
public function isPlugin()
{
- return $self instanceof Plugin;
+ return $this instanceof Plugin;
}
/*
diff --git a/src/includes/traits/Shared/HookUtils.php b/src/includes/traits/Shared/HookUtils.php
index a8d64da9..d9af042c 100644
--- a/src/includes/traits/Shared/HookUtils.php
+++ b/src/includes/traits/Shared/HookUtils.php
@@ -80,7 +80,7 @@ public function addHook($hook, $function, $priority = 10, $accepted_args = 1)
*/
public function addAction()
{
- return call_user_func_array([$self, 'addHook'], func_get_args());
+ return call_user_func_array([$this, 'addHook'], func_get_args());
}
$this->add_action = $this->addAction; // Back compat.
@@ -93,7 +93,7 @@ public function addAction()
*/
public function addFilter()
{
- return call_user_func_array([$self, 'addHook'], func_get_args());
+ return call_user_func_array([$this, 'addHook'], func_get_args());
}
$this->add_filter = $this->addFilter; // Back compat.
@@ -137,7 +137,7 @@ public function removeHook($hook, $function, $priority = 10)
*/
public function removeAction()
{
- return call_user_func_array([$self, 'removeHook'], func_get_args());
+ return call_user_func_array([$this, 'removeHook'], func_get_args());
}
/*
@@ -149,7 +149,7 @@ public function removeAction()
*/
public function removeFilter()
{
- return call_user_func_array([$self, 'removeHook'], func_get_args());
+ return call_user_func_array([$this, 'removeHook'], func_get_args());
}
/*
diff --git a/src/includes/traits/Shared/HttpUtils.php b/src/includes/traits/Shared/HttpUtils.php
index 952b36fa..b093b1c1 100644
--- a/src/includes/traits/Shared/HttpUtils.php
+++ b/src/includes/traits/Shared/HttpUtils.php
@@ -149,7 +149,7 @@ public function httpStatus()
} elseif ($this->functionIsPossible('http_response_code') && ($code = (integer) http_response_code())) {
$status = (integer) $code; // {@link \http_response_code()} available since PHP v5.4.
} elseif ($has_property_http_status && (integer) $this->{'http_status'}) {
- $status = (integer) $this->{'http_status'} // {@link \status_header()} filter.
+ $status = (integer) $this->{'http_status'}; // {@link \status_header()} filter.
}
if ($status && $has_property_http_status) {
$this->{'http_status'} = $status; // Prefer over {@link status_header()}.
From ee0543e9c1314cb8eb34753ed2e8e6abbd6fb687 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 08:13:15 -0500
Subject: [PATCH 006/112] Convert to Traits: Convert aliases
See websharks/comet-cache#635
---
src/includes/traits/Plugin/UserUtils.php | 52 +++++++++++++++++++--
src/includes/traits/Plugin/WcpPostUtils.php | 9 +++-
src/includes/traits/Plugin/WcpUserUtils.php | 18 ++++++-
src/includes/traits/Plugin/WcpUtils.php | 27 +++++++++--
src/includes/traits/Shared/HookUtils.php | 18 ++++++-
5 files changed, 112 insertions(+), 12 deletions(-)
diff --git a/src/includes/traits/Plugin/UserUtils.php b/src/includes/traits/Plugin/UserUtils.php
index 92ac2982..6e01af54 100644
--- a/src/includes/traits/Plugin/UserUtils.php
+++ b/src/includes/traits/Plugin/UserUtils.php
@@ -34,7 +34,18 @@ public function currentUserCanClearCache()
/*[/pro]*/
return ($can = false);
}
-$this->currentUserCanWipeCache = $this->currentUserCanClearCache;
+
+ /*
+ * Alias for currentUserCanClearCache()
+ *
+ * @since 151002 Enhancing user permissions.
+ *
+ * @return boolean Current user can clear the cache?
+ */
+ public function currentUserCanWipeCache()
+ {
+ return call_user_func_array([$this, 'currentUserCanClearCache'], func_get_args());
+ }
/*
* Current user can clear the opcache?
@@ -58,7 +69,18 @@ public function currentUserCanClearOpCache()
}
return ($can = false);
}
-$this->currentUserCanWipeOpCache = $this->currentUserCanClearOpCache;
+
+ /*
+ * Alias for currentUserCanClearOpCache()
+ *
+ * @since 151114 Enhancing user permissions.
+ *
+ * @return boolean Current user can clear the opcache?
+ */
+ public function currentUserCanWipeOpCache()
+ {
+ return call_user_func_array([$this, 'currentUserCanClearOpCache'], func_get_args());
+ }
/*
* Current user can clear the CDN cache?
@@ -82,7 +104,18 @@ public function currentUserCanClearCdnCache()
}
return ($can = false);
}
-$this->currentUserCanWipeCdnCache = $this->currentUserCanClearCdnCache;
+
+ /*
+ * Alias for currentUserCanClearCdnCache()
+ *
+ * @since 151114 Enhancing user permissions.
+ *
+ * @return boolean Current user can clear the CDN cache?
+ */
+ public function currentUserCanWipeCdnCache()
+ {
+ return call_user_func_array([$this, 'currentUserCanClearCdnCache'], func_get_args());
+ }
/*
* Current user can clear expired transients?
@@ -106,7 +139,18 @@ public function currentUserCanClearExpiredTransients()
}
return ($can = false);
}
-$this->currentUserCanWipeExpiredTransients = $this->currentUserCanClearExpiredTransients;
+
+ /*
+ * Alias for currentUserCanClearExpiredTransients()
+ *
+ * @since 151220 Enhancing user permissions.
+ *
+ * @return boolean Current user can clear expired transients?
+ */
+ public function currentUserCanWipeExpiredTransients()
+ {
+ return call_user_func_array([$this, 'currentUserCanClearExpiredTransients'], func_get_args());
+ }
/*
* Current user can see stats?
diff --git a/src/includes/traits/Plugin/WcpPostUtils.php b/src/includes/traits/Plugin/WcpPostUtils.php
index bb446934..d85d88e9 100644
--- a/src/includes/traits/Plugin/WcpPostUtils.php
+++ b/src/includes/traits/Plugin/WcpPostUtils.php
@@ -111,7 +111,14 @@ public function autoClearPostCache($post_id, $force = false)
}
return $counter;
}
-$this->auto_clear_post_cache = $this->autoClearPostCache; // Back compat.
+
+ /*
+ * Back compat. alias for autoClearPostCache()
+ */
+ public function auto_clear_post_cache()
+ {
+ return call_user_func_array([$this, 'autoClearPostCache'], func_get_args());
+ }
/*
* Handles post status transitioning.
diff --git a/src/includes/traits/Plugin/WcpUserUtils.php b/src/includes/traits/Plugin/WcpUserUtils.php
index d11e69ce..436869cc 100644
--- a/src/includes/traits/Plugin/WcpUserUtils.php
+++ b/src/includes/traits/Plugin/WcpUserUtils.php
@@ -48,7 +48,14 @@ public function autoClearUserCache($user_id)
}
return $counter;
}
-$this->auto_clear_user_cache = $this->autoClearUserCache; // Back compat.
+
+ /*
+ * Back compat. alias for autoClearUserCache()
+ */
+ public function auto_clear_user_cache()
+ {
+ return call_user_func_array([$this, 'autoClearUserCache'], func_get_args());
+ }
/*
* Automatically clears cache files associated with a particular user.
@@ -127,6 +134,13 @@ public function autoClearUserCacheCur()
{
$this->autoClearUserCache(get_current_user_id());
}
-$this->auto_clear_user_cache_cur = $this->autoClearUserCacheCur; // Back compat.
+
+ /*
+ * Back compat. alias for autoClearUserCache()
+ */
+ public function auto_clear_user_cache_cur()
+ {
+ return call_user_func_array([$this, 'autoClearUserCacheCur'], func_get_args());
+ }
}
/*[/pro]*/
diff --git a/src/includes/traits/Plugin/WcpUtils.php b/src/includes/traits/Plugin/WcpUtils.php
index 76e0dc06..aad85a3f 100644
--- a/src/includes/traits/Plugin/WcpUtils.php
+++ b/src/includes/traits/Plugin/WcpUtils.php
@@ -57,7 +57,14 @@ public function wipeCache($manually = false)
/*[/pro]*/
return $counter;
}
-$this->wipe_cache = $this->wipeCache; // Back compat.
+
+ /*
+ * Back compat. alias for autoClearUserCache()
+ */
+ public function wipe_cache()
+ {
+ return call_user_func_array([$this, 'wipeCache'], func_get_args());
+ }
/*
* Clears cache files (current blog).
@@ -103,7 +110,14 @@ public function clearCache($manually = false)
/*[/pro]*/
return $counter;
}
-$this->clear_cache = $this->clearCache; // Back compat.
+
+ /*
+ * Back compat. alias for clearCache()
+ */
+ public function clear_cache()
+ {
+ return call_user_func_array([$this, 'clearCache'], func_get_args());
+ }
/*
* Purges expired cache files (current blog).
@@ -137,7 +151,14 @@ public function purgeCache($manually = false)
/*[/pro]*/
return $counter;
}
-$this->purge_cache = $this->purgeCache; // Back compat.
+
+ /*
+ * Back compat. alias for purgeCache()
+ */
+ public function purge_cache()
+ {
+ return call_user_func_array([$this, 'purgeCache'], func_get_args());
+ }
/*
* Wurges (purges) all expired cache files; like wipe, but expired files only.
diff --git a/src/includes/traits/Shared/HookUtils.php b/src/includes/traits/Shared/HookUtils.php
index d9af042c..ff273e89 100644
--- a/src/includes/traits/Shared/HookUtils.php
+++ b/src/includes/traits/Shared/HookUtils.php
@@ -82,7 +82,14 @@ public function addAction()
{
return call_user_func_array([$this, 'addHook'], func_get_args());
}
-$this->add_action = $this->addAction; // Back compat.
+
+ /*
+ * Back compat. alias for addAction()
+ */
+ public function add_action()
+ {
+ return call_user_func_array([$this, 'addAction'], func_get_args());
+ }
/*
* Adds a new filter.
@@ -95,7 +102,14 @@ public function addFilter()
{
return call_user_func_array([$this, 'addHook'], func_get_args());
}
-$this->add_filter = $this->addFilter; // Back compat.
+
+ /*
+ * Back compat. alias for addFilter()
+ */
+ public function add_filter()
+ {
+ return call_user_func_array([$this, 'addFilter'], func_get_args());
+ }
/*
* Removes a hook (works with both actions & filters).
From 761279b9d2bfddb6dbbcce4503981c9b92022174 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 08:19:46 -0500
Subject: [PATCH 007/112] Convert to Traits: Fix incorrect /*[/pro]*/ placement
inside trait
See websharks/comet-cache#635
---
src/includes/traits/Ac/HtmlCUtils.php | 2 +-
src/includes/traits/Plugin/AdminBarUtils.php | 2 +-
src/includes/traits/Plugin/AutoCacheUtils.php | 2 +-
src/includes/traits/Plugin/CdnUtils.php | 2 +-
4 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/src/includes/traits/Ac/HtmlCUtils.php b/src/includes/traits/Ac/HtmlCUtils.php
index 81a69e1e..f6d5ab90 100644
--- a/src/includes/traits/Ac/HtmlCUtils.php
+++ b/src/includes/traits/Ac/HtmlCUtils.php
@@ -77,5 +77,5 @@ public function maybeCompressHtml($cache)
}
return $compressed_cache;
}
- /*[/pro]*/
}
+/*[/pro]*/
diff --git a/src/includes/traits/Plugin/AdminBarUtils.php b/src/includes/traits/Plugin/AdminBarUtils.php
index 02a54cae..b1f5106c 100644
--- a/src/includes/traits/Plugin/AdminBarUtils.php
+++ b/src/includes/traits/Plugin/AdminBarUtils.php
@@ -360,5 +360,5 @@ public function adminBarScripts()
}
wp_enqueue_script(GLOBAL_NS.'-admin-bar', $this->url('/src/client-s/js/admin-bar.min.js'), $deps, VERSION, true);
}
- /*[/pro]*/
}
+/*[/pro]*/
diff --git a/src/includes/traits/Plugin/AutoCacheUtils.php b/src/includes/traits/Plugin/AutoCacheUtils.php
index af0b3247..62253ae4 100644
--- a/src/includes/traits/Plugin/AutoCacheUtils.php
+++ b/src/includes/traits/Plugin/AutoCacheUtils.php
@@ -166,5 +166,5 @@ public function autoCacheCheckXmlSitemap($sitemap, $is_nested_sitemap = false, $
return true;
}
- /*[/pro]*/
}
+/*[/pro]*/
diff --git a/src/includes/traits/Plugin/CdnUtils.php b/src/includes/traits/Plugin/CdnUtils.php
index 0e3d54f3..4149029b 100644
--- a/src/includes/traits/Plugin/CdnUtils.php
+++ b/src/includes/traits/Plugin/CdnUtils.php
@@ -19,5 +19,5 @@ public function bumpCdnInvalidationCounter()
}
$this->updateOptions(['cdn_invalidation_counter' => ++$this->options['cdn_invalidation_counter']]);
}
- /*[/pro]*/
}
+/*[/pro]*/
From d8a6dc707122889b9e912fb4567c0c5c97130983 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 08:21:34 -0500
Subject: [PATCH 008/112] Convert to Traits: Add Classes\ to instanceof
See websharks/comet-cache#635
---
src/includes/traits/Shared/ConditionalUtils.php | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/includes/traits/Shared/ConditionalUtils.php b/src/includes/traits/Shared/ConditionalUtils.php
index 7273ec4c..08c8f9cf 100644
--- a/src/includes/traits/Shared/ConditionalUtils.php
+++ b/src/includes/traits/Shared/ConditionalUtils.php
@@ -37,7 +37,7 @@ trait ConditionalUtils {
*/
public function isAdvancedCache()
{
- return $this instanceof AdvancedCache;
+ return $this instanceof Classes\AdvancedCache;
}
/*
@@ -49,7 +49,7 @@ public function isAdvancedCache()
*/
public function isPlugin()
{
- return $this instanceof Plugin;
+ return $this instanceof Classes\Plugin;
}
/*
From 0e144058b0bd1db7ab0aa533b70d26d91809be11 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 08:23:56 -0500
Subject: [PATCH 009/112] Convert to Traits: Update $this->{''}
See websharks/comet-cache#635
---
src/includes/traits/Shared/HttpUtils.php | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/src/includes/traits/Shared/HttpUtils.php b/src/includes/traits/Shared/HttpUtils.php
index b093b1c1..ef8bd5d1 100644
--- a/src/includes/traits/Shared/HttpUtils.php
+++ b/src/includes/traits/Shared/HttpUtils.php
@@ -144,18 +144,18 @@ public function httpStatus()
$has_property_is_404 = property_exists($this, 'is_404');
$has_property_http_status = property_exists($this, 'http_status');
- if ($has_property_is_404 && $this->{'is_404'}) {
+ if ($has_property_is_404 && $this->is_404) {
$status = 404; // WordPress said so.
} elseif ($this->functionIsPossible('http_response_code') && ($code = (integer) http_response_code())) {
$status = (integer) $code; // {@link \http_response_code()} available since PHP v5.4.
- } elseif ($has_property_http_status && (integer) $this->{'http_status'}) {
- $status = (integer) $this->{'http_status'}; // {@link \status_header()} filter.
+ } elseif ($has_property_http_status && (integer) $this->http_status) {
+ $status = (integer) $this->http_status; // {@link \status_header()} filter.
}
if ($status && $has_property_http_status) {
- $this->{'http_status'} = $status; // Prefer over {@link status_header()}.
+ $this->http_status = $status; // Prefer over {@link status_header()}.
}
if ($status === 404 && $has_property_is_404) {
- $this->{'is_404'} = true; // Prefer over {@link is_404()}.
+ $this->is_404 = true; // Prefer over {@link is_404()}.
}
return $status;
}
From 8275d7eb3cf948947bbbd79359ddfad34107814c Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 08:35:46 -0500
Subject: [PATCH 010/112] Convert to Traits: Add \Classes to namespace in
src/includes/classes/
See websharks/comet-cache#635
---
src/includes/classes/AbsBase.php | 2 +-
src/includes/classes/AbsBaseAp.php | 2 +-
src/includes/classes/Actions.php | 2 +-
src/includes/classes/AdvCacheBackCompat.php | 2 +-
src/includes/classes/AdvancedCache.php | 2 +-
src/includes/classes/ApiBase.php | 2 +-
src/includes/classes/AutoCache.php | 2 +-
src/includes/classes/CdnFilters.php | 2 +-
src/includes/classes/Conflicts.php | 2 +-
src/includes/classes/DirStats.php | 2 +-
src/includes/classes/FeedUtils.php | 2 +-
src/includes/classes/MenuPage.php | 2 +-
src/includes/classes/MenuPageOptions.php | 2 +-
src/includes/classes/MenuPageProUpdater.php | 2 +-
src/includes/classes/MenuPageStats.php | 2 +-
src/includes/classes/Plugin.php | 2 +-
src/includes/classes/VsUpgrades.php | 2 +-
17 files changed, 17 insertions(+), 17 deletions(-)
diff --git a/src/includes/classes/AbsBase.php b/src/includes/classes/AbsBase.php
index a2754fef..5bd93003 100644
--- a/src/includes/classes/AbsBase.php
+++ b/src/includes/classes/AbsBase.php
@@ -1,5 +1,5 @@
Date: Sun, 28 Feb 2016 08:36:52 -0500
Subject: [PATCH 011/112] Convert to Traits: Update composer.json
See websharks/comet-cache#635
---
composer.json | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/composer.json b/composer.json
index de0b1659..52793558 100644
--- a/composer.json
+++ b/composer.json
@@ -43,7 +43,8 @@
"autoload": {
"psr-4": {
- "WebSharks\\CometCache\\Pro\\": "src/includes/classes/"
+ "WebSharks\\CometCache\\Pro\\Classes\\": "src/includes/classes/",
+ "WebSharks\\CometCache\\Pro\\Traits\\": "src/includes/traits/"
}
},
"config": {
From 05b27d9a343d85447d1cccab80074ca717714c7f Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 08:44:03 -0500
Subject: [PATCH 012/112] Convert to Traits: Add `use
WebSharks\CometCache\Pro\Classes;`
See websharks/comet-cache#635
---
src/includes/traits/Ac/AbortUtils.php | 2 ++
src/includes/traits/Ac/AcPluginUtils.php | 2 ++
src/includes/traits/Ac/BrowserUtils.php | 2 ++
src/includes/traits/Ac/HtmlCUtils.php | 2 ++
src/includes/traits/Ac/NcDebugConsts.php | 2 ++
src/includes/traits/Ac/NcDebugUtils.php | 2 ++
src/includes/traits/Ac/ObUtils.php | 2 ++
src/includes/traits/Ac/PostloadUtils.php | 2 ++
src/includes/traits/Ac/ShutdownUtils.php | 2 ++
src/includes/traits/Plugin/ActionUtils.php | 2 ++
src/includes/traits/Plugin/AdminBarUtils.php | 2 ++
src/includes/traits/Plugin/AutoCacheUtils.php | 2 ++
src/includes/traits/Plugin/BbPressUtils.php | 2 ++
src/includes/traits/Plugin/CdnUtils.php | 2 ++
src/includes/traits/Plugin/CleanupUtils.php | 2 ++
src/includes/traits/Plugin/CondUtils.php | 2 ++
src/includes/traits/Plugin/CronUtils.php | 2 ++
src/includes/traits/Plugin/DbUtils.php | 2 ++
src/includes/traits/Plugin/DirUtils.php | 2 ++
src/includes/traits/Plugin/HtaccessUtils.php | 2 ++
src/includes/traits/Plugin/HtmlCUtils.php | 2 ++
src/includes/traits/Plugin/InstallUtils.php | 2 ++
src/includes/traits/Plugin/MenuPageUtils.php | 2 ++
src/includes/traits/Plugin/NoticeUtils.php | 2 ++
src/includes/traits/Plugin/OptionUtils.php | 2 ++
src/includes/traits/Plugin/PostUtils.php | 2 ++
src/includes/traits/Plugin/StatsUtils.php | 2 ++
src/includes/traits/Plugin/UpdateUtils.php | 2 ++
src/includes/traits/Plugin/UrlUtils.php | 2 ++
src/includes/traits/Plugin/UserUtils.php | 2 ++
src/includes/traits/Plugin/WcpAuthorUtils.php | 2 ++
src/includes/traits/Plugin/WcpCdnUtils.php | 2 ++
src/includes/traits/Plugin/WcpCommentUtils.php | 2 ++
src/includes/traits/Plugin/WcpEvalUtils.php | 2 ++
src/includes/traits/Plugin/WcpFeedUtils.php | 2 ++
src/includes/traits/Plugin/WcpHomeBlogUtils.php | 2 ++
src/includes/traits/Plugin/WcpHtmlCUtils.php | 2 ++
src/includes/traits/Plugin/WcpJetpackUtils.php | 2 ++
src/includes/traits/Plugin/WcpOpcacheUtils.php | 2 ++
src/includes/traits/Plugin/WcpPluginUtils.php | 2 ++
src/includes/traits/Plugin/WcpPostTypeUtils.php | 2 ++
src/includes/traits/Plugin/WcpPostUtils.php | 2 ++
src/includes/traits/Plugin/WcpS2cleanUtils.php | 2 ++
src/includes/traits/Plugin/WcpSettingUtils.php | 2 ++
src/includes/traits/Plugin/WcpSitemapUtils.php | 2 ++
src/includes/traits/Plugin/WcpTermUtils.php | 2 ++
src/includes/traits/Plugin/WcpTransientUtils.php | 2 ++
src/includes/traits/Plugin/WcpUpdaterUtils.php | 2 ++
src/includes/traits/Plugin/WcpUrlUtils.php | 2 ++
src/includes/traits/Plugin/WcpUserUtils.php | 2 ++
src/includes/traits/Plugin/WcpUtils.php | 2 ++
src/includes/traits/Plugin/WcpWooCommerceUtils.php | 2 ++
src/includes/traits/Shared/BlogUtils.php | 2 ++
src/includes/traits/Shared/CacheDirUtils.php | 2 ++
src/includes/traits/Shared/CacheLockUtils.php | 2 ++
src/includes/traits/Shared/CachePathConsts.php | 2 ++
src/includes/traits/Shared/CachePathUtils.php | 2 ++
src/includes/traits/Shared/ConditionalUtils.php | 2 ++
src/includes/traits/Shared/DomainMappingUtils.php | 2 ++
src/includes/traits/Shared/EscapeUtils.php | 2 ++
src/includes/traits/Shared/FsUtils.php | 2 ++
src/includes/traits/Shared/HookUtils.php | 2 ++
src/includes/traits/Shared/HttpUtils.php | 2 ++
src/includes/traits/Shared/I18nUtils.php | 2 ++
src/includes/traits/Shared/IpAddrUtils.php | 2 ++
src/includes/traits/Shared/PatternUtils.php | 2 ++
src/includes/traits/Shared/ReplaceUtils.php | 2 ++
src/includes/traits/Shared/ServerUtils.php | 2 ++
src/includes/traits/Shared/StringUtils.php | 2 ++
src/includes/traits/Shared/SysUtils.php | 2 ++
src/includes/traits/Shared/TokenUtils.php | 2 ++
src/includes/traits/Shared/TrimUtils.php | 2 ++
src/includes/traits/Shared/UrlUtils.php | 2 ++
73 files changed, 146 insertions(+)
diff --git a/src/includes/traits/Ac/AbortUtils.php b/src/includes/traits/Ac/AbortUtils.php
index e25d533e..b70a48d2 100644
--- a/src/includes/traits/Ac/AbortUtils.php
+++ b/src/includes/traits/Ac/AbortUtils.php
@@ -1,6 +1,8 @@
Date: Sun, 28 Feb 2016 08:47:11 -0500
Subject: [PATCH 013/112] Convert to Traits: Convert `new ClassName` to `new
Classes\ClassName`
See websharks/comet-cache#635
---
src/includes/traits/Plugin/ActionUtils.php | 2 +-
src/includes/traits/Plugin/AutoCacheUtils.php | 2 +-
src/includes/traits/Plugin/InstallUtils.php | 2 +-
src/includes/traits/Plugin/MenuPageUtils.php | 6 +++---
src/includes/traits/Plugin/WcpFeedUtils.php | 2 +-
5 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/src/includes/traits/Plugin/ActionUtils.php b/src/includes/traits/Plugin/ActionUtils.php
index d90a848f..7ec47e61 100644
--- a/src/includes/traits/Plugin/ActionUtils.php
+++ b/src/includes/traits/Plugin/ActionUtils.php
@@ -14,7 +14,7 @@ trait ActionUtils {
public function actions()
{
if (!empty($_REQUEST[GLOBAL_NS])) {
- new Actions();
+ new Classes\Actions();
}
/*[pro strip-from="lite"]*/
if (!empty($_REQUEST[GLOBAL_NS.'_auto_cache_cron'])
diff --git a/src/includes/traits/Plugin/AutoCacheUtils.php b/src/includes/traits/Plugin/AutoCacheUtils.php
index eb4a9b6e..b954a1dd 100644
--- a/src/includes/traits/Plugin/AutoCacheUtils.php
+++ b/src/includes/traits/Plugin/AutoCacheUtils.php
@@ -28,7 +28,7 @@ public function autoCache()
if (!$this->autoCacheCheckPhpIni()) {
return; // Server does not meet minimum requirements.
}
- new AutoCache();
+ new Classes\AutoCache();
}
/**
diff --git a/src/includes/traits/Plugin/InstallUtils.php b/src/includes/traits/Plugin/InstallUtils.php
index ca2df1cd..e974af84 100644
--- a/src/includes/traits/Plugin/InstallUtils.php
+++ b/src/includes/traits/Plugin/InstallUtils.php
@@ -48,7 +48,7 @@ public function checkVersion()
}
$this->updateOptions(['version' => VERSION]);
- new VsUpgrades($prev_version);
+ new Classes\VsUpgrades($prev_version);
if ($this->options['enable']) {
$this->addWpCacheToWpConfig();
diff --git a/src/includes/traits/Plugin/MenuPageUtils.php b/src/includes/traits/Plugin/MenuPageUtils.php
index 676a51c3..8d426a58 100644
--- a/src/includes/traits/Plugin/MenuPageUtils.php
+++ b/src/includes/traits/Plugin/MenuPageUtils.php
@@ -180,7 +180,7 @@ public function colorSvgMenuIcon($svg)
*/
public function menuPageOptions()
{
- new MenuPage('options');
+ new Classes\MenuPage('options');
}
/*[pro strip-from="lite"]*/
@@ -191,7 +191,7 @@ public function menuPageOptions()
*/
public function menuPageStats()
{
- new MenuPage('stats');
+ new Classes\MenuPage('stats');
}
/*[/pro]*/
@@ -203,7 +203,7 @@ public function menuPageStats()
*/
public function menuPageProUpdater()
{
- new MenuPage('pro-updater');
+ new Classes\MenuPage('pro-updater');
}
/*[/pro]*/
diff --git a/src/includes/traits/Plugin/WcpFeedUtils.php b/src/includes/traits/Plugin/WcpFeedUtils.php
index 4887a5a8..9e87f207 100644
--- a/src/includes/traits/Plugin/WcpFeedUtils.php
+++ b/src/includes/traits/Plugin/WcpFeedUtils.php
@@ -45,7 +45,7 @@ public function autoClearXmlFeedsCache($type, $post_id = 0)
if (!is_dir($cache_dir = $this->cacheDir())) {
return $counter; // Nothing to do.
}
- $utils = new FeedUtils(); // Feed utilities.
+ $utils = new Classes\FeedUtils(); // Feed utilities.
$variations = $variation_regex_frags = []; // Initialize.
switch ($type) { // Handle clearing based on the `$type`.
From bc5699ecefbd58c631fdc7ede1e7062d77e47c80 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 08:49:54 -0500
Subject: [PATCH 014/112] Convert to Traits: Convert `ClassName::` to
`Classes\ClassName::`
See websharks/comet-cache#635
---
src/includes/traits/Ac/ObUtils.php | 2 +-
src/includes/traits/Plugin/CleanupUtils.php | 2 +-
src/includes/traits/Plugin/WcpUtils.php | 8 ++++----
3 files changed, 6 insertions(+), 6 deletions(-)
diff --git a/src/includes/traits/Ac/ObUtils.php b/src/includes/traits/Ac/ObUtils.php
index 0f79af28..947ff810 100644
--- a/src/includes/traits/Ac/ObUtils.php
+++ b/src/includes/traits/Ac/ObUtils.php
@@ -249,7 +249,7 @@ public function outputBufferCallbackHandler($buffer, $phase)
if (!($phase & PHP_OUTPUT_HANDLER_END)) {
throw new \Exception(sprintf(__('Unexpected OB phase: `%1$s`.', SLUG_TD), $phase));
}
- AdvCacheBackCompat::zenCacheConstants();
+ Classes\AdvCacheBackCompat::zenCacheConstants();
$cache = trim((string) $buffer);
diff --git a/src/includes/traits/Plugin/CleanupUtils.php b/src/includes/traits/Plugin/CleanupUtils.php
index c5591192..680d1350 100644
--- a/src/includes/traits/Plugin/CleanupUtils.php
+++ b/src/includes/traits/Plugin/CleanupUtils.php
@@ -26,7 +26,7 @@ public function cleanupCache()
/*[pro strip-from="lite"]*/
if ($this->options['stats_enable']) {
- $dir_stats = DirStats::instance();
+ $dir_stats = Classes\DirStats::instance();
$dir_stats->forCache(true);
}
/*[/pro]*/
diff --git a/src/includes/traits/Plugin/WcpUtils.php b/src/includes/traits/Plugin/WcpUtils.php
index 885a21ea..54d6ce0e 100644
--- a/src/includes/traits/Plugin/WcpUtils.php
+++ b/src/includes/traits/Plugin/WcpUtils.php
@@ -53,7 +53,7 @@ public function wipeCache($manually = false)
/*[pro strip-from="lite"]*/
if ($this->options['stats_enable']) {
- $dir_stats = DirStats::instance();
+ $dir_stats = Classes\DirStats::instance();
$dir_stats->wipeCache();
}
/*[/pro]*/
@@ -106,7 +106,7 @@ public function clearCache($manually = false)
/*[pro strip-from="lite"]*/
if ($this->options['stats_enable']) {
- $dir_stats = DirStats::instance();
+ $dir_stats = Classes\DirStats::instance();
$dir_stats->clearHostCache();
}
/*[/pro]*/
@@ -147,7 +147,7 @@ public function purgeCache($manually = false)
}
/*[pro strip-from="lite"]*/
if ($this->options['stats_enable']) {
- $dir_stats = DirStats::instance();
+ $dir_stats = Classes\DirStats::instance();
$dir_stats->clearHostCache();
}
/*[/pro]*/
@@ -188,7 +188,7 @@ public function wurgeCache($manually = false)
}
/*[pro strip-from="lite"]*/
if ($this->options['stats_enable']) {
- $dir_stats = DirStats::instance();
+ $dir_stats = Classes\DirStats::instance();
$dir_stats->wipeCache();
}
/*[/pro]*/
From b875c8c85f89356dedebf1a91382e122ee135019 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 09:14:35 -0500
Subject: [PATCH 015/112] Convert to Traits: Move NcDebugConsts to interface
See websharks/comet-cache#635
---
composer.json | 3 +-
.../interfaces/Shared/NcDebugConsts.php | 294 +++++++++++++++++
src/includes/traits/Ac/NcDebugConsts.php | 296 ------------------
3 files changed, 296 insertions(+), 297 deletions(-)
create mode 100644 src/includes/interfaces/Shared/NcDebugConsts.php
delete mode 100644 src/includes/traits/Ac/NcDebugConsts.php
diff --git a/composer.json b/composer.json
index 52793558..b56bd927 100644
--- a/composer.json
+++ b/composer.json
@@ -44,7 +44,8 @@
"autoload": {
"psr-4": {
"WebSharks\\CometCache\\Pro\\Classes\\": "src/includes/classes/",
- "WebSharks\\CometCache\\Pro\\Traits\\": "src/includes/traits/"
+ "WebSharks\\CometCache\\Pro\\Traits\\": "src/includes/traits/",
+ "WebSharks\\CometCache\\Pro\\Interfaces\\": "src/includes/interfaces/"
}
},
"config": {
diff --git a/src/includes/interfaces/Shared/NcDebugConsts.php b/src/includes/interfaces/Shared/NcDebugConsts.php
new file mode 100644
index 00000000..bebcacd5
--- /dev/null
+++ b/src/includes/interfaces/Shared/NcDebugConsts.php
@@ -0,0 +1,294 @@
+
Date: Sun, 28 Feb 2016 09:17:25 -0500
Subject: [PATCH 016/112] Convert to Traits: Add `implements
Interfaces\Shared\NcDebugConsts`
See websharks/comet-cache#635
---
src/includes/classes/AdvancedCache.php | 4 +++-
src/includes/classes/Plugin.php | 4 +++-
2 files changed, 6 insertions(+), 2 deletions(-)
diff --git a/src/includes/classes/AdvancedCache.php b/src/includes/classes/AdvancedCache.php
index 4b672548..50c18e7e 100644
--- a/src/includes/classes/AdvancedCache.php
+++ b/src/includes/classes/AdvancedCache.php
@@ -1,12 +1,14 @@
Date: Sun, 28 Feb 2016 09:25:26 -0500
Subject: [PATCH 017/112] Convert to Traits: Add `Classes\` to
advanced-cache.txt
See websharks/comet-cache#635
---
src/includes/templates/advanced-cache.txt | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/includes/templates/advanced-cache.txt b/src/includes/templates/advanced-cache.txt
index dfb6fc4a..42b01537 100644
--- a/src/includes/templates/advanced-cache.txt
+++ b/src/includes/templates/advanced-cache.txt
@@ -33,8 +33,8 @@ if (defined('WP_DEBUG') && WP_DEBUG) {
} elseif ((@include_once(dirname(COMET_CACHE_PLUGIN_FILE).'/src/includes/functions/wp-cache-postload.php')) === false) {
return; // Unable to find postload function(s). Fail softly.
}
-AdvCacheBackCompat::zenCacheConstants();
-AdvCacheBackCompat::zcRequestVars();
+Classes\AdvCacheBackCompat::zenCacheConstants();
+Classes\AdvCacheBackCompat::zcRequestVars();
if (!defined('COMET_CACHE_PRO')) {
/**
From d6d2f4a23857f4145489ec2930af11fe52d883d0 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 09:27:17 -0500
Subject: [PATCH 018/112] Convert to Traits: Add `$this::` to NC_DEBUG
constants
See websharks/comet-cache#635
---
src/includes/traits/Ac/NcDebugUtils.php | 64 ++++++++++----------
src/includes/traits/Ac/ObUtils.php | 76 ++++++++++++------------
src/includes/traits/Ac/PostloadUtils.php | 2 +-
3 files changed, 71 insertions(+), 71 deletions(-)
diff --git a/src/includes/traits/Ac/NcDebugUtils.php b/src/includes/traits/Ac/NcDebugUtils.php
index c9811fe5..dccaa91b 100644
--- a/src/includes/traits/Ac/NcDebugUtils.php
+++ b/src/includes/traits/Ac/NcDebugUtils.php
@@ -77,19 +77,19 @@ public function maybeGetNcDebugInfo($reason_code = '', $reason = '')
}
if (!$reason) {
switch ($reason_code) {
- case NC_DEBUG_PHP_SAPI_CLI:
+ case $this::NC_DEBUG_PHP_SAPI_CLI:
$reason = __('because `PHP_SAPI` reports that you are currently running from the command line.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_NO_SERVER_HTTP_HOST:
+ case $this::NC_DEBUG_NO_SERVER_HTTP_HOST:
$reason = __('because `$_SERVER[\'HTTP_HOST\']` is missing from your server configuration.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_NO_SERVER_REQUEST_URI:
+ case $this::NC_DEBUG_NO_SERVER_REQUEST_URI:
$reason = __('because `$_SERVER[\'REQUEST_URI\']` is missing from your server configuration.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_COMET_CACHE_ALLOWED_CONSTANT:
+ case $this::NC_DEBUG_COMET_CACHE_ALLOWED_CONSTANT:
if ($this->functionIsPossible('did_action') && did_action('ws_plugin__s2member_during_no_cache_constants')) {
$reason = __('because the s2Member plugin set the PHP constant `COMET_CACHE_ALLOWED` to a boolean-ish `FALSE` value at runtime. The s2Member plugin is serving content that must remain dynamic on this particular page, and therefore this page was intentionally not cached for a very good reason.', SLUG_TD);
} else {
@@ -97,112 +97,112 @@ public function maybeGetNcDebugInfo($reason_code = '', $reason = '')
}
break; // Break switch handler.
- case NC_DEBUG_COMET_CACHE_ALLOWED_SERVER_VAR:
+ case $this::NC_DEBUG_COMET_CACHE_ALLOWED_SERVER_VAR:
$reason = __('because the environment variable `$_SERVER[\'COMET_CACHE_ALLOWED\']` has been set to a boolean-ish `FALSE` value at runtime. Perhaps by WordPress itself, or by one of your themes/plugins. This usually means that you have a theme/plugin intentionally disabling the cache on this page; and it\'s usually for a very good reason.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_DONOTCACHEPAGE_CONSTANT:
+ case $this::NC_DEBUG_DONOTCACHEPAGE_CONSTANT:
$reason = __('because the PHP constant `DONOTCACHEPAGE` has been set at runtime. Perhaps by WordPress itself, or by one of your themes/plugins. This usually means that you have a theme/plugin intentionally disabling the cache on this page; and it\'s usually for a very good reason.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_DONOTCACHEPAGE_SERVER_VAR:
+ case $this::NC_DEBUG_DONOTCACHEPAGE_SERVER_VAR:
$reason = __('because the environment variable `$_SERVER[\'DONOTCACHEPAGE\']` has been set at runtime. Perhaps by WordPress itself, or by one of your themes/plugins. This usually means that you have a theme/plugin intentionally disabling the cache on this page; and it\'s usually for a very good reason.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_AC_GET_VAR:
+ case $this::NC_DEBUG_AC_GET_VAR:
$reason = sprintf(__('because `$_GET[\'%1$sAC\']` is set to a boolean-ish FALSE value.', SLUG_TD), strtolower(SHORT_NAME));
break; // Break switch handler.
- case NC_DEBUG_UNCACHEABLE_REQUEST:
+ case $this::NC_DEBUG_UNCACHEABLE_REQUEST:
$reason = __('because `$_SERVER[\'REQUEST_METHOD\']` is `POST`, `PUT`, `DELETE`, `HEAD`, `OPTIONS`, `TRACE` or `CONNECT`. These request methods should never (ever) be cached in any way.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_SELF_SERVE_REQUEST:
+ case $this::NC_DEBUG_SELF_SERVE_REQUEST:
$reason = __('because `[current IP address]` === `$_SERVER[\'SERVER_ADDR\']`; i.e. a self-serve request. DEVELOPER TIP: if you are testing on a localhost installation, please add `define(\'LOCALHOST\', TRUE);` to your `/wp-config.php` file while you run tests :-) Remove it (or set it to a `FALSE` value) once you go live on the web.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_FEED_REQUEST:
+ case $this::NC_DEBUG_FEED_REQUEST:
$reason = __('because `$_SERVER[\'REQUEST_URI\']` indicates this is a `/feed`; and the configuration of this site says not to cache XML-based feeds.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_WP_SYSTEMATICS:
+ case $this::NC_DEBUG_WP_SYSTEMATICS:
$reason = __('because `$_SERVER[\'REQUEST_URI\']` indicates this is a `wp-` or `xmlrpc` file; i.e. a WordPress systematic file. WordPress systematics are never (ever) cached in any way.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_WP_ADMIN:
+ case $this::NC_DEBUG_WP_ADMIN:
$reason = __('because `$_SERVER[\'REQUEST_URI\']` or the `is_admin()` function indicates this is an administrative area of the site.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_MS_FILES:
+ case $this::NC_DEBUG_MS_FILES:
$reason = __('because `$_SERVER[\'REQUEST_URI\']` indicates this is a Multisite Network; and this was a request for `/files/*`, not a page.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_IS_LOGGED_IN_USER:
- case NC_DEBUG_IS_LIKE_LOGGED_IN_USER:
+ case $this::NC_DEBUG_IS_LOGGED_IN_USER:
+ case $this::NC_DEBUG_IS_LIKE_LOGGED_IN_USER:
$reason = __('because the current user visiting this page (usually YOU), appears to be logged-in. The current configuration says NOT to cache pages for logged-in visitors. This message may also appear if you have an active PHP session on this site, or if you\'ve left (or replied to) a comment recently. If this message continues, please clear your cookies and try again.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_IS_LOGGED_IN_USER_NONCE:
+ case $this::NC_DEBUG_IS_LOGGED_IN_USER_NONCE:
$reason = __('because the current page contains `_wpnonce` or `akismet_comment_nonce`. While your current configuration states that pages SHOULD be cache for logged-in visitors, `*nonce*` values in the markup are not cache-compatible. See http://wsharks.com/1O1Kudy for further details.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_PAGE_CONTAINS_NONCE:
+ case $this::NC_DEBUG_PAGE_CONTAINS_NONCE:
$reason = __('because the current page contains `_wpnonce` or `akismet_comment_nonce`. Note that `*nonce*` values in the markup are not cache-compatible. See http://wsharks.com/1O1Kudy for further details.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_NO_USER_TOKEN:
+ case $this::NC_DEBUG_NO_USER_TOKEN:
$reason = sprintf(__('because the current user appeared to be logged into the site (in one way or another); but %1$s was unable to formulate a User Token for them. Please report this as a possible bug.', SLUG_TD), NAME);
break; // Break switch handler.
- case NC_DEBUG_GET_REQUEST_QUERIES:
+ case $this::NC_DEBUG_GET_REQUEST_QUERIES:
$reason = __('because `$_GET` contains query string data. The current configuration says NOT to cache GET requests with a query string.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_PREVIEW:
+ case $this::NC_DEBUG_PREVIEW:
$reason = __('because `$_REQUEST` indicates this is simply a preview of something to come.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_EXCLUDED_URIS:
+ case $this::NC_DEBUG_EXCLUDED_URIS:
$reason = __('because `$_SERVER[\'REQUEST_URI\']` matches a configured URI Exclusion Pattern on this installation.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_EXCLUDED_AGENTS:
+ case $this::NC_DEBUG_EXCLUDED_AGENTS:
$reason = __('because `$_SERVER[\'HTTP_USER_AGENT\']` matches a configured User-Agent Exclusion Pattern on this installation.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_EXCLUDED_REFS:
+ case $this::NC_DEBUG_EXCLUDED_REFS:
$reason = __('because `$_SERVER[\'HTTP_REFERER\']` and/or `$_GET[\'_wp_http_referer\']` matches a configured HTTP Referrer Exclusion Pattern on this installation.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_404_REQUEST:
+ case $this::NC_DEBUG_404_REQUEST:
$reason = __('because the WordPress `is_404()` Conditional Tag says the current page is a 404 error. The current configuration says NOT to cache 404 errors.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_MAINTENANCE_PLUGIN:
+ case $this::NC_DEBUG_MAINTENANCE_PLUGIN:
$reason = __('because a plugin running on this installation says this page is in Maintenance Mode; i.e. is not available publicly at this time.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_OB_ZLIB_CODING_TYPE:
+ case $this::NC_DEBUG_OB_ZLIB_CODING_TYPE:
$reason = sprintf(__('because %1$s is unable to cache already-compressed output. Please use `mod_deflate` w/ Apache; or use `zlib.output_compression` in your `php.ini` file. %1$s is NOT compatible with `ob_gzhandler()` and others like this.', SLUG_TD), NAME);
break; // Break switch handler.
- case NC_DEBUG_WP_ERROR_PAGE:
+ case $this::NC_DEBUG_WP_ERROR_PAGE:
$reason = __('because the contents of this document contain ``, which indicates this is an auto-generated WordPress error message.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_UNCACHEABLE_CONTENT_TYPE:
+ case $this::NC_DEBUG_UNCACHEABLE_CONTENT_TYPE:
$reason = __('because a `Content-Type:` header was set via PHP at runtime. The header contains a MIME type which is NOT a variation of HTML or XML. This header might have been set by your hosting company, by WordPress itself; or by one of your themes/plugins.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_UNCACHEABLE_STATUS:
+ case $this::NC_DEBUG_UNCACHEABLE_STATUS:
$reason = __('because a `Status:` header (or an `HTTP/` header) was set via PHP at runtime. The header contains a non-`2xx` status code. This indicates the current page was not loaded successfully. This header might have been set by your hosting company, by WordPress itself; or by one of your themes/plugins.', SLUG_TD);
break; // Break switch handler.
- case NC_DEBUG_1ST_TIME_404_SYMLINK:
+ case $this::NC_DEBUG_1ST_TIME_404_SYMLINK:
$reason = sprintf(__('because the WordPress `is_404()` Conditional Tag says the current page is a 404 error; and this is the first time it\'s happened on this page. Your current configuration says that 404 errors SHOULD be cached, so %1$s built a cached symlink which points future requests for this location to your already-cached 404 error document. If you reload this page (assuming you don\'t clear the cache before you do so); you should get a cached version of your 404 error document. This message occurs ONCE for each new/unique 404 error request.', SLUG_TD), NAME);
break; // Break switch handler.
- case NC_DEBUG_EARLY_BUFFER_TERMINATION:
+ case $this::NC_DEBUG_EARLY_BUFFER_TERMINATION:
$reason = sprintf(__('because %1$s detected an early output buffer termination. This may happen when a theme/plugin ends, cleans, or flushes all output buffers before reaching the PHP shutdown phase. It\'s not always a bad thing. Sometimes it is necessary for a theme/plugin to do this. However, in this scenario it is NOT possible to cache the output; since %1$s is effectively disabled at runtime when this occurs.', SLUG_TD), NAME);
break; // Break switch handler.
diff --git a/src/includes/traits/Ac/ObUtils.php b/src/includes/traits/Ac/ObUtils.php
index 947ff810..ba22e8ec 100644
--- a/src/includes/traits/Ac/ObUtils.php
+++ b/src/includes/traits/Ac/ObUtils.php
@@ -106,74 +106,74 @@ trait ObUtils {
public function maybeStartOutputBuffering()
{
if (strcasecmp(PHP_SAPI, 'cli') === 0) {
- return $this->maybeSetDebugInfo(NC_DEBUG_PHP_SAPI_CLI);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_PHP_SAPI_CLI);
}
if (empty($_SERVER['HTTP_HOST']) || !$this->hostToken()) {
- return $this->maybeSetDebugInfo(NC_DEBUG_NO_SERVER_HTTP_HOST);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_NO_SERVER_HTTP_HOST);
}
if (empty($_SERVER['REQUEST_URI'])) {
- return $this->maybeSetDebugInfo(NC_DEBUG_NO_SERVER_REQUEST_URI);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_NO_SERVER_REQUEST_URI);
}
if (defined('COMET_CACHE_ALLOWED') && !COMET_CACHE_ALLOWED) {
- return $this->maybeSetDebugInfo(NC_DEBUG_COMET_CACHE_ALLOWED_CONSTANT);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_COMET_CACHE_ALLOWED_CONSTANT);
}
if (isset($_SERVER['COMET_CACHE_ALLOWED']) && !$_SERVER['COMET_CACHE_ALLOWED']) {
- return $this->maybeSetDebugInfo(NC_DEBUG_COMET_CACHE_ALLOWED_SERVER_VAR);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_COMET_CACHE_ALLOWED_SERVER_VAR);
}
if (defined('DONOTCACHEPAGE')) {
- return $this->maybeSetDebugInfo(NC_DEBUG_DONOTCACHEPAGE_CONSTANT);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_DONOTCACHEPAGE_CONSTANT);
}
if (isset($_SERVER['DONOTCACHEPAGE'])) {
- return $this->maybeSetDebugInfo(NC_DEBUG_DONOTCACHEPAGE_SERVER_VAR);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_DONOTCACHEPAGE_SERVER_VAR);
}
if (isset($_GET[strtolower(SHORT_NAME).'AC']) && !filter_var($_GET[strtolower(SHORT_NAME).'AC'], FILTER_VALIDATE_BOOLEAN)) {
- return $this->maybeSetDebugInfo(NC_DEBUG_AC_GET_VAR);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_AC_GET_VAR);
}
if ($this->isUncacheableRequestMethod()) {
- return $this->maybeSetDebugInfo(NC_DEBUG_UNCACHEABLE_REQUEST);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_UNCACHEABLE_REQUEST);
}
if (isset($_SERVER['SERVER_ADDR']) && $this->currentIp() === $_SERVER['SERVER_ADDR']) {
if ((!IS_PRO || !$this->isAutoCacheEngine()) && !$this->isLocalhost()) {
- return $this->maybeSetDebugInfo(NC_DEBUG_SELF_SERVE_REQUEST);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_SELF_SERVE_REQUEST);
}
}
if (!COMET_CACHE_FEEDS_ENABLE && $this->isFeed()) {
- return $this->maybeSetDebugInfo(NC_DEBUG_FEED_REQUEST);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_FEED_REQUEST);
}
if (preg_match('/\/(?:wp\-[^\/]+|xmlrpc)\.php(?:[?]|$)/i', $_SERVER['REQUEST_URI'])) {
- return $this->maybeSetDebugInfo(NC_DEBUG_WP_SYSTEMATICS);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_WP_SYSTEMATICS);
}
if (is_admin() || preg_match('/\/wp-admin(?:[\/?]|$)/i', $_SERVER['REQUEST_URI'])) {
- return $this->maybeSetDebugInfo(NC_DEBUG_WP_ADMIN);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_WP_ADMIN);
}
if (is_multisite() && preg_match('/\/files(?:[\/?]|$)/i', $_SERVER['REQUEST_URI'])) {
- return $this->maybeSetDebugInfo(NC_DEBUG_MS_FILES);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_MS_FILES);
}
if ((!IS_PRO || !COMET_CACHE_WHEN_LOGGED_IN) && $this->isLikeUserLoggedIn()) {
- return $this->maybeSetDebugInfo(NC_DEBUG_IS_LIKE_LOGGED_IN_USER);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_IS_LIKE_LOGGED_IN_USER);
}
if (!COMET_CACHE_GET_REQUESTS && $this->requestContainsUncacheableQueryVars()) {
- return $this->maybeSetDebugInfo(NC_DEBUG_GET_REQUEST_QUERIES);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_GET_REQUEST_QUERIES);
}
if (!empty($_REQUEST['preview'])) {
- return $this->maybeSetDebugInfo(NC_DEBUG_PREVIEW);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_PREVIEW);
}
if (COMET_CACHE_EXCLUDE_URIS && preg_match(COMET_CACHE_EXCLUDE_URIS, $_SERVER['REQUEST_URI'])) {
- return $this->maybeSetDebugInfo(NC_DEBUG_EXCLUDED_URIS);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_EXCLUDED_URIS);
}
if (COMET_CACHE_EXCLUDE_AGENTS && !empty($_SERVER['HTTP_USER_AGENT']) && (!IS_PRO || !$this->isAutoCacheEngine())) {
if (preg_match(COMET_CACHE_EXCLUDE_AGENTS, $_SERVER['HTTP_USER_AGENT'])) {
- return $this->maybeSetDebugInfo(NC_DEBUG_EXCLUDED_AGENTS);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_EXCLUDED_AGENTS);
}
}
if (COMET_CACHE_EXCLUDE_REFS && !empty($_REQUEST['_wp_http_referer'])) {
if (preg_match(COMET_CACHE_EXCLUDE_REFS, stripslashes($_REQUEST['_wp_http_referer']))) {
- return $this->maybeSetDebugInfo(NC_DEBUG_EXCLUDED_REFS);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_EXCLUDED_REFS);
}
}
if (COMET_CACHE_EXCLUDE_REFS && !empty($_SERVER['HTTP_REFERER'])) {
if (preg_match(COMET_CACHE_EXCLUDE_REFS, $_SERVER['HTTP_REFERER'])) {
- return $this->maybeSetDebugInfo(NC_DEBUG_EXCLUDED_REFS);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_EXCLUDED_REFS);
}
}
$this->protocol = $this->isSsl() ? 'https://' : 'http://';
@@ -257,59 +257,59 @@ public function outputBufferCallbackHandler($buffer, $phase)
return false; // Don't cache an empty buffer.
}
if (!isset($GLOBALS[GLOBAL_NS.'_shutdown_flag'])) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_EARLY_BUFFER_TERMINATION);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_EARLY_BUFFER_TERMINATION);
}
if (defined('COMET_CACHE_ALLOWED') && !COMET_CACHE_ALLOWED) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_COMET_CACHE_ALLOWED_CONSTANT);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_COMET_CACHE_ALLOWED_CONSTANT);
}
if (isset($_SERVER['COMET_CACHE_ALLOWED']) && !$_SERVER['COMET_CACHE_ALLOWED']) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_COMET_CACHE_ALLOWED_SERVER_VAR);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_COMET_CACHE_ALLOWED_SERVER_VAR);
}
if (defined('DONOTCACHEPAGE')) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_DONOTCACHEPAGE_CONSTANT);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_DONOTCACHEPAGE_CONSTANT);
}
if (isset($_SERVER['DONOTCACHEPAGE'])) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_DONOTCACHEPAGE_SERVER_VAR);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_DONOTCACHEPAGE_SERVER_VAR);
}
if ((!IS_PRO || !COMET_CACHE_WHEN_LOGGED_IN) && $this->is_user_logged_in) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_IS_LOGGED_IN_USER);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_IS_LOGGED_IN_USER);
}
if ((!IS_PRO || !COMET_CACHE_WHEN_LOGGED_IN) && $this->isLikeUserLoggedIn()) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_IS_LIKE_LOGGED_IN_USER);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_IS_LIKE_LOGGED_IN_USER);
}
if (!COMET_CACHE_CACHE_NONCE_VALUES && preg_match('/\b(?:_wpnonce|akismet_comment_nonce)\b/', $cache)) {
if (IS_PRO && COMET_CACHE_WHEN_LOGGED_IN && $this->isLikeUserLoggedIn()) {
if (!COMET_CACHE_CACHE_NONCE_VALUES_WHEN_LOGGED_IN) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_IS_LOGGED_IN_USER_NONCE);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_IS_LOGGED_IN_USER_NONCE);
}
} else { // Use the default debug notice for nonce conflicts.
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_PAGE_CONTAINS_NONCE);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_PAGE_CONTAINS_NONCE);
} // An nonce makes the page dynamic; i.e., NOT cache compatible.
}
if ($this->is_404 && !COMET_CACHE_CACHE_404_REQUESTS) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_404_REQUEST);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_404_REQUEST);
}
if (stripos($cache, '') !== false) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_WP_ERROR_PAGE);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_WP_ERROR_PAGE);
}
if (!$this->functionIsPossible('http_response_code')) {
if (stripos($cache, 'database error') !== false) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_WP_ERROR_PAGE);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_WP_ERROR_PAGE);
}
}
if (!$this->hasACacheableContentType()) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_UNCACHEABLE_CONTENT_TYPE);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_UNCACHEABLE_CONTENT_TYPE);
}
if (!$this->hasACacheableStatus()) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_UNCACHEABLE_STATUS);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_UNCACHEABLE_STATUS);
}
if ($this->is_maintenance) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_MAINTENANCE_PLUGIN);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_MAINTENANCE_PLUGIN);
}
if ($this->functionIsPossible('zlib_get_coding_type') && zlib_get_coding_type()
&& (!($zlib_oc = ini_get('zlib.output_compression')) || !filter_var($zlib_oc, FILTER_VALIDATE_BOOLEAN))
) {
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_OB_ZLIB_CODING_TYPE);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_OB_ZLIB_CODING_TYPE);
}
# Lock the cache directory while writes take place here.
@@ -337,7 +337,7 @@ public function outputBufferCallbackHandler($buffer, $phase)
throw new \Exception(sprintf(__('Unable to create symlink: `%1$s` » `%2$s`. Possible permissions issue (or race condition), please check your cache directory: `%3$s`.', SLUG_TD), $this->cache_file, $this->cache_file_404, COMET_CACHE_DIR));
}
$this->cacheUnlock($cache_lock); // Release.
- return (boolean) $this->maybeSetDebugInfo(NC_DEBUG_1ST_TIME_404_SYMLINK);
+ return (boolean) $this->maybeSetDebugInfo($this::NC_DEBUG_1ST_TIME_404_SYMLINK);
}
/* ------- Otherwise, we need to construct & store a new cache file. ----------------------------------------------- */
diff --git a/src/includes/traits/Ac/PostloadUtils.php b/src/includes/traits/Ac/PostloadUtils.php
index aa3f8d82..7a411b49 100644
--- a/src/includes/traits/Ac/PostloadUtils.php
+++ b/src/includes/traits/Ac/PostloadUtils.php
@@ -176,7 +176,7 @@ public function maybeStartObWhenLoggedInPostload()
}
if (!($this->user_token = $this->userToken())) {
if (!$this->user_login_cookie_expired_or_invalid) {
- return $this->maybeSetDebugInfo(NC_DEBUG_NO_USER_TOKEN);
+ return $this->maybeSetDebugInfo($this::NC_DEBUG_NO_USER_TOKEN);
}
}
$this->cache_path = $this->buildCachePath($this->protocol.$this->host_token.$_SERVER['REQUEST_URI'], $this->user_token, $this->version_salt);
From e6aea6d7b74a53ef9d606b4c8de211026a59f7b7 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 09:43:08 -0500
Subject: [PATCH 019/112] Convert to Traits: Use proper docBlock syntax in
src/includes/traits/
See websharks/comet-cache#635
---
src/includes/traits/Ac/AbortUtils.php | 2 +-
src/includes/traits/Ac/AcPluginUtils.php | 2 +-
src/includes/traits/Ac/BrowserUtils.php | 2 +-
src/includes/traits/Ac/HtmlCUtils.php | 2 +-
src/includes/traits/Ac/NcDebugUtils.php | 8 ++---
src/includes/traits/Ac/ObUtils.php | 24 +++++++--------
src/includes/traits/Ac/PostloadUtils.php | 30 +++++++++----------
src/includes/traits/Ac/ShutdownUtils.php | 2 +-
src/includes/traits/Plugin/ActionUtils.php | 2 +-
src/includes/traits/Plugin/AdminBarUtils.php | 10 +++----
src/includes/traits/Plugin/AutoCacheUtils.php | 2 +-
src/includes/traits/Plugin/BbPressUtils.php | 6 ++--
src/includes/traits/Plugin/CdnUtils.php | 2 +-
src/includes/traits/Plugin/CleanupUtils.php | 2 +-
src/includes/traits/Plugin/CondUtils.php | 2 +-
src/includes/traits/Plugin/CronUtils.php | 6 ++--
src/includes/traits/Plugin/DbUtils.php | 2 +-
src/includes/traits/Plugin/DirUtils.php | 4 +--
src/includes/traits/Plugin/HtaccessUtils.php | 20 ++++++-------
src/includes/traits/Plugin/HtmlCUtils.php | 2 +-
src/includes/traits/Plugin/InstallUtils.php | 26 ++++++++--------
src/includes/traits/Plugin/MenuPageUtils.php | 22 +++++++-------
src/includes/traits/Plugin/NoticeUtils.php | 20 ++++++-------
src/includes/traits/Plugin/OptionUtils.php | 6 ++--
src/includes/traits/Plugin/PostUtils.php | 4 +--
src/includes/traits/Plugin/StatsUtils.php | 2 +-
src/includes/traits/Plugin/UpdateUtils.php | 8 ++---
src/includes/traits/Plugin/UrlUtils.php | 2 +-
src/includes/traits/Plugin/UserUtils.php | 18 +++++------
src/includes/traits/Plugin/WcpAuthorUtils.php | 2 +-
src/includes/traits/Plugin/WcpCdnUtils.php | 4 +--
.../traits/Plugin/WcpCommentUtils.php | 4 +--
src/includes/traits/Plugin/WcpEvalUtils.php | 4 +--
src/includes/traits/Plugin/WcpFeedUtils.php | 2 +-
.../traits/Plugin/WcpHomeBlogUtils.php | 4 +--
src/includes/traits/Plugin/WcpHtmlCUtils.php | 4 +--
.../traits/Plugin/WcpJetpackUtils.php | 2 +-
.../traits/Plugin/WcpOpcacheUtils.php | 6 ++--
src/includes/traits/Plugin/WcpPluginUtils.php | 2 +-
.../traits/Plugin/WcpPostTypeUtils.php | 2 +-
src/includes/traits/Plugin/WcpPostUtils.php | 4 +--
.../traits/Plugin/WcpS2cleanUtils.php | 4 +--
.../traits/Plugin/WcpSettingUtils.php | 2 +-
.../traits/Plugin/WcpSitemapUtils.php | 2 +-
src/includes/traits/Plugin/WcpTermUtils.php | 2 +-
.../traits/Plugin/WcpTransientUtils.php | 4 +--
.../traits/Plugin/WcpUpdaterUtils.php | 2 +-
src/includes/traits/Plugin/WcpUrlUtils.php | 2 +-
src/includes/traits/Plugin/WcpUserUtils.php | 12 ++++----
src/includes/traits/Plugin/WcpUtils.php | 24 +++++++--------
.../traits/Plugin/WcpWooCommerceUtils.php | 2 +-
src/includes/traits/Shared/BlogUtils.php | 2 +-
src/includes/traits/Shared/CacheDirUtils.php | 20 ++++++-------
src/includes/traits/Shared/CacheLockUtils.php | 4 +--
src/includes/traits/Shared/CachePathUtils.php | 16 +++++-----
.../traits/Shared/ConditionalUtils.php | 28 ++++++++---------
.../traits/Shared/DomainMappingUtils.php | 14 ++++-----
src/includes/traits/Shared/EscapeUtils.php | 2 +-
src/includes/traits/Shared/FsUtils.php | 18 +++++------
src/includes/traits/Shared/HookUtils.php | 24 +++++++--------
src/includes/traits/Shared/HttpUtils.php | 10 +++----
src/includes/traits/Shared/I18nUtils.php | 6 ++--
src/includes/traits/Shared/IpAddrUtils.php | 4 +--
src/includes/traits/Shared/PatternUtils.php | 4 +--
src/includes/traits/Shared/ReplaceUtils.php | 4 +--
src/includes/traits/Shared/ServerUtils.php | 6 ++--
src/includes/traits/Shared/StringUtils.php | 4 +--
src/includes/traits/Shared/SysUtils.php | 6 ++--
src/includes/traits/Shared/TokenUtils.php | 18 +++++------
src/includes/traits/Shared/TrimUtils.php | 2 +-
src/includes/traits/Shared/UrlUtils.php | 8 ++---
71 files changed, 268 insertions(+), 268 deletions(-)
diff --git a/src/includes/traits/Ac/AbortUtils.php b/src/includes/traits/Ac/AbortUtils.php
index b70a48d2..f72430a5 100644
--- a/src/includes/traits/Ac/AbortUtils.php
+++ b/src/includes/traits/Ac/AbortUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait AbortUtils {
- /*
+ /**
* Ignores user aborts; when/if the Auto-Cache Engine is running.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Ac/AcPluginUtils.php b/src/includes/traits/Ac/AcPluginUtils.php
index 8a4357da..fa7b5d75 100644
--- a/src/includes/traits/Ac/AcPluginUtils.php
+++ b/src/includes/traits/Ac/AcPluginUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait AcPluginUtils {
- /*
+ /**
* Loads any advanced cache plugin files found inside `/wp-content/ac-plugins`.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Ac/BrowserUtils.php b/src/includes/traits/Ac/BrowserUtils.php
index fb8e87b4..09485622 100644
--- a/src/includes/traits/Ac/BrowserUtils.php
+++ b/src/includes/traits/Ac/BrowserUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait BrowserUtils {
- /*
+ /**
* Sends no-cache headers (if applicable).
*
* @since 150422 Rewrite. Enhanced/altered 151220.
diff --git a/src/includes/traits/Ac/HtmlCUtils.php b/src/includes/traits/Ac/HtmlCUtils.php
index ceab2e20..c498ab58 100644
--- a/src/includes/traits/Ac/HtmlCUtils.php
+++ b/src/includes/traits/Ac/HtmlCUtils.php
@@ -5,7 +5,7 @@
use WebSharks\CometCache\Pro\Classes;
trait HtmlCUtils {
- /*
+ /**
* Runs HTML Compressor (if applicable).
*
* @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
diff --git a/src/includes/traits/Ac/NcDebugUtils.php b/src/includes/traits/Ac/NcDebugUtils.php
index dccaa91b..47d4fa00 100644
--- a/src/includes/traits/Ac/NcDebugUtils.php
+++ b/src/includes/traits/Ac/NcDebugUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait NcDebugUtils {
- /*
+ /**
* An array of debug info.
*
* @since 150422 Rewrite.
@@ -13,7 +13,7 @@ trait NcDebugUtils {
*/
public $debug_info = ['reason_code' => '', 'reason' => ''];
- /*
+ /**
* Used to setup debug info (if enabled).
*
* @since 150422 Rewrite.
@@ -33,7 +33,7 @@ public function maybeSetDebugInfo($reason_code, $reason = '')
$this->debug_info = ['reason_code' => $reason_code, 'reason' => $reason];
}
- /*
+ /**
* Echoes `NC_DEBUG_` info in the WordPress `shutdown` phase (if applicable).
*
* @since 150422 Rewrite.
@@ -56,7 +56,7 @@ public function maybeEchoNcDebugInfo()
}
}
- /*
+ /**
* Gets `NC_DEBUG_` info (if applicable).
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Ac/ObUtils.php b/src/includes/traits/Ac/ObUtils.php
index ba22e8ec..bfcd91ef 100644
--- a/src/includes/traits/Ac/ObUtils.php
+++ b/src/includes/traits/Ac/ObUtils.php
@@ -5,7 +5,7 @@
trait ObUtils {
- /*
+ /**
* Calculated protocol; one of `http://` or `https://`.
*
* @since 150422 Rewrite.
@@ -14,7 +14,7 @@ trait ObUtils {
*/
public $rotocol = '';
- /*
+ /**
* Host token for this request.
*
* @since 150821 Improving multisite compat.
@@ -23,7 +23,7 @@ trait ObUtils {
*/
public $host_token = '';
- /*
+ /**
* Host base/dir tokens for this request.
*
* @since 150821 Improving multisite compat.
@@ -32,7 +32,7 @@ trait ObUtils {
*/
public $host_base_dir_tokens = '';
- /*
+ /**
* Calculated version salt; set by site configuration data.
*
* @since 150422 Rewrite.
@@ -41,7 +41,7 @@ trait ObUtils {
*/
public $version_salt = '';
- /*
+ /**
* Relative cache path for the current request.
*
* @since 150422 Rewrite.
@@ -50,7 +50,7 @@ trait ObUtils {
*/
public $cache_path = '';
- /*
+ /**
* Absolute cache file path for the current request.
*
* @since 150422 Rewrite.
@@ -59,7 +59,7 @@ trait ObUtils {
*/
public $cache_file = '';
- /*
+ /**
* Relative 404 cache path for the current request.
*
* @since 150422 Rewrite.
@@ -68,7 +68,7 @@ trait ObUtils {
*/
public $cache_path_404 = '';
- /*
+ /**
* Absolute 404 cache file path for the current request.
*
* @since 150422 Rewrite.
@@ -77,7 +77,7 @@ trait ObUtils {
*/
public $cache_file_404 = '';
- /*
+ /**
* Version salt followed by the current request location.
*
* @since 150422 Rewrite.
@@ -86,7 +86,7 @@ trait ObUtils {
*/
public $salt_location = '';
- /*
+ /**
* Calculated max age; i.e., before expiration.
*
* @since 151002 Load average checks in pro version.
@@ -95,7 +95,7 @@ trait ObUtils {
*/
public $cache_max_age = 0;
- /*
+ /**
* Start output buffering (if applicable); or serve a cache file (if possible).
*
* @since 150422 Rewrite.
@@ -227,7 +227,7 @@ public function maybeStartOutputBuffering()
return; // Return value not applicable.
}
- /*
+ /**
* Output buffer handler; i.e. the cache file generator.
*
* @note We CANNOT depend on any WP functionality here; it will cause problems.
diff --git a/src/includes/traits/Ac/PostloadUtils.php b/src/includes/traits/Ac/PostloadUtils.php
index 7a411b49..7bbe8710 100644
--- a/src/includes/traits/Ac/PostloadUtils.php
+++ b/src/includes/traits/Ac/PostloadUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait PostloadUtils {
- /*
+ /**
* Have we caught the main WP loaded being loaded yet?
*
* @since 150422 Rewrite.
@@ -15,7 +15,7 @@ trait PostloadUtils {
*/
public $is_wp_loaded_query = false;
- /*
+ /**
* Is the current request a WordPress 404 error?
*
* @since 150422 Rewrite.
@@ -26,7 +26,7 @@ trait PostloadUtils {
*/
public $is_404 = false;
- /*
+ /**
* Last HTTP status code passed through {@link \status_header}.
*
* @since 150422 Rewrite.
@@ -37,7 +37,7 @@ trait PostloadUtils {
*/
public $http_status = 0;
- /*
+ /**
* Is the current request a WordPress content type?
*
* @since 150422 Rewrite.
@@ -48,7 +48,7 @@ trait PostloadUtils {
*/
public $is_a_wp_content_type = false;
- /*
+ /**
* Current WordPress {@link \content_url()}.
*
* @since 150422 Rewrite.
@@ -59,7 +59,7 @@ trait PostloadUtils {
*/
public $content_url = '';
- /*
+ /**
* Flag for {@link \is_user_loged_in()}.
*
* @since 150422 Rewrite.
@@ -70,7 +70,7 @@ trait PostloadUtils {
*/
public $is_user_logged_in = false;
- /*
+ /**
* Flag for {@link \is_maintenance()}.
*
* @since 150422 Rewrite.
@@ -81,7 +81,7 @@ trait PostloadUtils {
*/
public $is_maintenance = false;
- /*
+ /**
* Array of data targeted at the postload phase.
*
* @since 150422 Rewrite.
@@ -99,7 +99,7 @@ trait PostloadUtils {
];
/*[pro strip-from="lite"]*/
- /*
+ /**
* Calculated user token; applicable w/ user postload enabled.
*
* @since 150422 Rewrite.
@@ -110,7 +110,7 @@ trait PostloadUtils {
/*[/pro]*/
/*[pro strip-from="lite"]*/
- /*
+ /**
* Sets a flag for possible invalidation upon certain actions in the postload phase.
*
* @since 150422 Rewrite.
@@ -138,7 +138,7 @@ public function maybePostloadInvalidateWhenLoggedIn()
/*[/pro]*/
/*[pro strip-from="lite"]*/
- /*
+ /**
* Invalidates cache files for a user (if applicable).
*
* @since 150422 Rewrite.
@@ -160,7 +160,7 @@ public function maybeInvalidateWhenLoggedInPostload()
/*[/pro]*/
/*[pro strip-from="lite"]*/
- /*
+ /**
* Starts output buffering in the postload phase (i.e. a bit later);
* when/if user caching is enabled; and if applicable.
*
@@ -206,7 +206,7 @@ public function maybeStartObWhenLoggedInPostload()
}
/*[/pro]*/
- /*
+ /**
* Filters WP {@link \status_header()} (if applicable).
*
* @since 150422 Rewrite.
@@ -231,7 +231,7 @@ function ($status_header, $status_code) use ($_this) {
);
}
- /*
+ /**
* Hooks `NC_DEBUG_` info into the WordPress `shutdown` phase (if applicable).
*
* @since 150422 Rewrite.
@@ -253,7 +253,7 @@ public function maybeSetDebugInfoPostload()
add_action('shutdown', [$this, 'maybeEchoNcDebugInfo'], PHP_INT_MAX - 10);
}
- /*
+ /**
* Grab details from WP and the Comet Cache plugin itself,
* after the main query is loaded (if at all possible).
*
diff --git a/src/includes/traits/Ac/ShutdownUtils.php b/src/includes/traits/Ac/ShutdownUtils.php
index c8010c1b..5cf8e91f 100644
--- a/src/includes/traits/Ac/ShutdownUtils.php
+++ b/src/includes/traits/Ac/ShutdownUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait ShutdownUtils {
- /*
+ /**
* Registers a shutdown flag.
*
* @since 140605 Improving output buffer.
diff --git a/src/includes/traits/Plugin/ActionUtils.php b/src/includes/traits/Plugin/ActionUtils.php
index 7ec47e61..d648052a 100644
--- a/src/includes/traits/Plugin/ActionUtils.php
+++ b/src/includes/traits/Plugin/ActionUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait ActionUtils {
- /*
+ /**
* Plugin action handler.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/AdminBarUtils.php b/src/includes/traits/Plugin/AdminBarUtils.php
index b2087252..ebefc67d 100644
--- a/src/includes/traits/Plugin/AdminBarUtils.php
+++ b/src/includes/traits/Plugin/AdminBarUtils.php
@@ -5,7 +5,7 @@
use WebSharks\CometCache\Pro\Classes;
trait AdminBarUtils {
- /*
+ /**
* Showing admin bar.
*
* @since 151002 Improving admin bar.
@@ -77,7 +77,7 @@ public function adminBarShowing($feature = '')
return $showing;
}
- /*
+ /**
* Filter WordPress admin bar.
*
* @since 150422 Rewrite.
@@ -287,7 +287,7 @@ public function adminBarMenu(\WP_Admin_Bar &$wp_admin_bar)
}
}
- /*
+ /**
* Injects `` tag w/ JSON-encoded data.
*
* @since 150422 Rewrite.
@@ -323,7 +323,7 @@ public function adminBarMetaTags()
' data-json="'.esc_attr(json_encode($vars)).'" id="'.esc_attr(GLOBAL_NS).'-admin-bar-vars" />'."\n";
}
- /*
+ /**
* Adds CSS for WordPress admin bar.
*
* @since 150422 Rewrite.
@@ -341,7 +341,7 @@ public function adminBarStyles()
wp_enqueue_style(GLOBAL_NS.'-admin-bar', $this->url('/src/client-s/css/admin-bar.min.css'), $deps, VERSION, 'all');
}
- /*
+ /**
* Adds JS for WordPress admin bar.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/AutoCacheUtils.php b/src/includes/traits/Plugin/AutoCacheUtils.php
index b954a1dd..60c43c5e 100644
--- a/src/includes/traits/Plugin/AutoCacheUtils.php
+++ b/src/includes/traits/Plugin/AutoCacheUtils.php
@@ -5,7 +5,7 @@
use WebSharks\CometCache\Pro\Classes;
trait AutoCacheUtils {
- /*
+ /**
* Runs the auto-cache engine via CRON job.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/BbPressUtils.php b/src/includes/traits/Plugin/BbPressUtils.php
index 9974d284..e7c0dc8e 100644
--- a/src/includes/traits/Plugin/BbPressUtils.php
+++ b/src/includes/traits/Plugin/BbPressUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait BbPressUtils {
- /*
+ /**
* Is bbPress active?
*
* @since 150821 Improving bbPress support.
@@ -16,7 +16,7 @@ public function isBbPressActive()
return class_exists('bbPress');
}
- /*
+ /**
* bbPress post types.
*
* @since 150821 Improving bbPress support.
@@ -39,7 +39,7 @@ public function bbPressPostTypes()
return $types;
}
- /*
+ /**
* bbPress post statuses.
*
* @since 150821 Improving bbPress support.
diff --git a/src/includes/traits/Plugin/CdnUtils.php b/src/includes/traits/Plugin/CdnUtils.php
index 4e1b20d1..1f0eeaf1 100644
--- a/src/includes/traits/Plugin/CdnUtils.php
+++ b/src/includes/traits/Plugin/CdnUtils.php
@@ -6,7 +6,7 @@
trait CdnUtils {
- /*
+ /**
* Bumps CDN invalidation counter.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/CleanupUtils.php b/src/includes/traits/Plugin/CleanupUtils.php
index 680d1350..09469fcf 100644
--- a/src/includes/traits/Plugin/CleanupUtils.php
+++ b/src/includes/traits/Plugin/CleanupUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait CleanupUtils {
- /*
+ /**
* Runs cleanup routine via CRON job.
*
* @since 151002 While working on directory stats.
diff --git a/src/includes/traits/Plugin/CondUtils.php b/src/includes/traits/Plugin/CondUtils.php
index bab55884..9f8a9e0b 100644
--- a/src/includes/traits/Plugin/CondUtils.php
+++ b/src/includes/traits/Plugin/CondUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait CondUtils {
- /*
+ /**
* Is pro preview?
*
* @since 150511 Rewrite.
diff --git a/src/includes/traits/Plugin/CronUtils.php b/src/includes/traits/Plugin/CronUtils.php
index e26c0cb1..63d6c7b4 100644
--- a/src/includes/traits/Plugin/CronUtils.php
+++ b/src/includes/traits/Plugin/CronUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait CronUtils {
- /*
+ /**
* Extends WP-Cron schedules.
*
* @since 150422 Rewrite.
@@ -24,7 +24,7 @@ public function extendCronSchedules($schedules)
return $schedules;
}
- /*
+ /**
* Checks Cron setup, validates schedules, and reschedules events if necessary.
*
* @attaches-to `init` hook.
@@ -62,7 +62,7 @@ public function checkCronSetup()
}
}
- /*
+ /**
* Resets `crons_setup` and clears WP-Cron schedules.
*
* @since 151220 Fixing bug with Auto-Cache Engine cron disappearing in some scenarios
diff --git a/src/includes/traits/Plugin/DbUtils.php b/src/includes/traits/Plugin/DbUtils.php
index b2dab2df..cb96e802 100644
--- a/src/includes/traits/Plugin/DbUtils.php
+++ b/src/includes/traits/Plugin/DbUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait DbUtils {
- /*
+ /**
* WordPress database instance.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/DirUtils.php b/src/includes/traits/Plugin/DirUtils.php
index b6e06537..cf9b9243 100644
--- a/src/includes/traits/Plugin/DirUtils.php
+++ b/src/includes/traits/Plugin/DirUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait DirUtils {
- /*
+ /**
* This constructs an absolute server directory path (no trailing slashes);
* which is always nested into {@link \WP_CONTENT_DIR} and the configured `base_dir` option value.
*
@@ -32,7 +32,7 @@ public function wpContentBaseDirTo($rel_dir_file)
return $wp_content_base_dir_to;
}
- /*
+ /**
* This constructs a relative/base directory path (no leading/trailing slashes).
* Always relative to {@link \WP_CONTENT_DIR}. Depends on the configured `base_dir` option value.
*
diff --git a/src/includes/traits/Plugin/HtaccessUtils.php b/src/includes/traits/Plugin/HtaccessUtils.php
index 1f2779ee..53b465be 100644
--- a/src/includes/traits/Plugin/HtaccessUtils.php
+++ b/src/includes/traits/Plugin/HtaccessUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait HtaccessUtils {
- /*
+ /**
* Unique comment marker.
*
* @since 151220 Enhancing `.htaccess` tweaks.
@@ -13,7 +13,7 @@ trait HtaccessUtils {
*/
public $htaccess_marker = 'WmVuQ2FjaGU';
- /*
+ /**
* Plugin options that have associated htaccess rules.
*
* @since 160103 Improving `.htaccess` tweaks.
@@ -24,7 +24,7 @@ trait HtaccessUtils {
*/
public $options_with_htaccess_rules = ['cdn_enable'];
- /*
+ /**
* Add template blocks to `/.htaccess` file.
*
* @since 151114 Adding `.htaccess` tweaks.
@@ -88,7 +88,7 @@ public function addWpHtaccess()
return true; // Added successfully.
}
- /*
+ /**
* Remove template blocks from `/.htaccess` file.
*
* @since 151114 Adding `.htaccess` tweaks.
@@ -124,7 +124,7 @@ public function removeWpHtaccess()
return true; // Removed successfully.
}
- /*
+ /**
* Finds absolute server path to `/.htaccess` file.
*
* @since 151114 Adding `.htaccess` tweaks.
@@ -143,7 +143,7 @@ public function findHtaccessFile()
return $file;
}
- /*
+ /**
* Determines if there are any plugin options enabled that require htaccess rules to be added.
*
* @since 160103 Improving `.htaccess` tweaks.
@@ -163,7 +163,7 @@ public function needHtaccessRules()
return false; // No, there are no options enabled that require htaccess rules.
}
- /*
+ /**
* Utility method used to check if htaccess file contains $htaccess_marker
*
* @since 151114 Adding `.htaccess` tweaks.
@@ -193,7 +193,7 @@ public function findHtaccessMarker($htaccess_marker = '')
return true; // Htaccess has the marker
}
- /*
+ /**
* Gets contents of `/.htaccess` file with exclusive lock to read+write. If file doesn't exist, we attempt to create it.
*
* @since 151220 Improving `.htaccess` utils.
@@ -232,7 +232,7 @@ public function readHtaccessFile($htaccess_file = '')
}
}
- /*
+ /**
* Writes to `/.htaccess` file using provided file pointer.
*
* @since 151220 Improving `.htaccess` utils.
@@ -269,7 +269,7 @@ public function writeHtaccessFile(array $htaccess, $require_marker = true, $htac
return true;
}
- /*
+ /**
* Utility method used to unlock and close htaccess file resource.
*
* @since 151114 Adding `.htaccess` tweaks.
diff --git a/src/includes/traits/Plugin/HtmlCUtils.php b/src/includes/traits/Plugin/HtmlCUtils.php
index 160ec7ff..e500b96c 100644
--- a/src/includes/traits/Plugin/HtmlCUtils.php
+++ b/src/includes/traits/Plugin/HtmlCUtils.php
@@ -5,7 +5,7 @@
use WebSharks\CometCache\Pro\Classes;
trait HtmlCUtils {
- /*
+ /**
* Adds marker for the HTML Compressor.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/InstallUtils.php b/src/includes/traits/Plugin/InstallUtils.php
index e974af84..a83e2ddd 100644
--- a/src/includes/traits/Plugin/InstallUtils.php
+++ b/src/includes/traits/Plugin/InstallUtils.php
@@ -5,7 +5,7 @@
trait InstallUtils {
- /*
+ /**
* Plugin activation hook.
*
* @since 150422 Rewrite.
@@ -33,7 +33,7 @@ public function activate()
$this->autoClearCache();
}
- /*
+ /**
* Check current plugin version that is installed in WP.
*
* @since 150422 Rewrite.
@@ -61,7 +61,7 @@ public function checkVersion()
$this->enqueueMainNotice(sprintf(__('%1$s: detected a new version of itself. Recompiling w/ latest version... wiping the cache... all done :-)', SLUG_TD), esc_html(NAME)), ['push_to_top' => true]);
}
- /*
+ /**
* Plugin deactivation hook.
*
* @since 150422 Rewrite.
@@ -79,7 +79,7 @@ public function deactivate()
$this->resetCronSetup();
}
- /*
+ /**
* Plugin uninstall hook.
*
* @since 150422 Rewrite.
@@ -124,7 +124,7 @@ public function uninstall()
}
}
- /*
+ /**
* Adds `define('WP_CACHE', TRUE);` to the `/wp-config.php` file.
*
* @since 150422 Rewrite.
@@ -173,7 +173,7 @@ public function addWpCacheToWpConfig()
return $wp_config_file_contents;
}
- /*
+ /**
* Removes `define('WP_CACHE', TRUE);` from the `/wp-config.php` file.
*
* @since 150422 Rewrite.
@@ -219,7 +219,7 @@ public function removeWpCacheFromWpConfig()
return $wp_config_file_contents;
}
- /*
+ /**
* Checks to make sure the `advanced-cache.php` file still exists;
* and if it doesn't, the `advanced-cache.php` is regenerated automatically.
*
@@ -260,7 +260,7 @@ public function checkAdvancedCache()
}
}
- /*
+ /**
* Creates and adds the `advanced-cache.php` file.
*
* @since 150422 Rewrite.
@@ -390,7 +390,7 @@ public function addAdvancedCache()
return true;
}
- /*
+ /**
* Removes the `advanced-cache.php` file.
*
* @since 150422 Rewrite.
@@ -430,7 +430,7 @@ public function removeAdvancedCache()
return true;
}
- /*
+ /**
* Deletes the `advanced-cache.php` file.
*
* @since 150422 Rewrite.
@@ -460,7 +460,7 @@ public function deleteAdvancedCache()
return true; // Deletion success.
}
- /*
+ /**
* Checks to make sure the `[SHORT_NAME]-blog-paths` file still exists;
* and if it doesn't, the `[SHORT_NAME]-blog-paths` file is regenerated automatically.
*
@@ -496,7 +496,7 @@ public function checkBlogPaths()
}
}
- /*
+ /**
* Creates and/or updates the `[SHORT_NAME]-blog-paths` file.
*
* @since 150422 Rewrite.
@@ -554,7 +554,7 @@ public function updateBlogPaths($enable_live_network_counts = null)
return $value; // Pass through untouched (always).
}
- /*
+ /**
* Deletes base directory.
*
* @since 151002 Improving multisite compat.
diff --git a/src/includes/traits/Plugin/MenuPageUtils.php b/src/includes/traits/Plugin/MenuPageUtils.php
index 8d426a58..c37accfc 100644
--- a/src/includes/traits/Plugin/MenuPageUtils.php
+++ b/src/includes/traits/Plugin/MenuPageUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait MenuPageUtils {
- /*
+ /**
* Adds CSS for administrative menu pages.
*
* @since 150422 Rewrite.
@@ -21,7 +21,7 @@ public function enqueueAdminStyles()
wp_enqueue_style(GLOBAL_NS, $this->url('/src/client-s/css/menu-pages.min.css'), $deps, VERSION, 'all');
}
- /*
+ /**
* Adds JS for administrative menu pages.
*
* @since 150422 Rewrite.
@@ -62,7 +62,7 @@ public function enqueueAdminScripts()
);
}
- /*
+ /**
* Creates network admin menu pages.
*
* @since 150422 Rewrite.
@@ -91,7 +91,7 @@ public function addNetworkMenuPages()
} /*[/pro]*/
}
- /*
+ /**
* Creates admin menu pages.
*
* @since 150422 Rewrite.
@@ -119,7 +119,7 @@ public function addMenuPages()
/*[/pro]*/
}
- /*
+ /**
* Adds link(s) to Comet Cache row on the WP plugins page.
*
* @since 150422 Rewrite.
@@ -144,7 +144,7 @@ public function addSettingsLink($links)
return $links;
}
- /*
+ /**
* Fills menu page inline SVG icon color.
*
* @since 150422 Rewrite.
@@ -173,7 +173,7 @@ public function colorSvgMenuIcon($svg)
return str_replace(' fill="currentColor"', ' fill="'.esc_attr($use_icon_fill_color).'"', $svg);
}
- /*
+ /**
* Loads the admin menu page options.
*
* @since 150422 Rewrite.
@@ -184,7 +184,7 @@ public function menuPageOptions()
}
/*[pro strip-from="lite"]*/
- /*
+ /**
* Loads admin menu page for stats.
*
* @since 151002 Directory stats.
@@ -196,7 +196,7 @@ public function menuPageStats()
/*[/pro]*/
/*[pro strip-from="lite"]*/
- /*
+ /**
* Loads admin menu page for pro updater.
*
* @since 150422 Rewrite.
@@ -207,7 +207,7 @@ public function menuPageProUpdater()
}
/*[/pro]*/
- /*
+ /**
* WordPress admin icon color schemes.
*
* @since 150422 Rewrite.
@@ -228,7 +228,7 @@ public function menuPageProUpdater()
'coffee' => ['base' => '#F3F2F1', 'focus' => '#FFFFFF', 'current' => '#FFFFFF'],
];
- /*
+ /**
* On a specific menu page?
*
* @since 151002 Improving multisite compat.
diff --git a/src/includes/traits/Plugin/NoticeUtils.php b/src/includes/traits/Plugin/NoticeUtils.php
index 6e4d3d6a..fe0459fa 100644
--- a/src/includes/traits/Plugin/NoticeUtils.php
+++ b/src/includes/traits/Plugin/NoticeUtils.php
@@ -8,7 +8,7 @@ trait NoticeUtils {
* Notice queue handlers.
*/
- /*
+ /**
* Enqueue an administrative notice.
*
* @since 150422 Rewrite. Improved 151002.
@@ -43,7 +43,7 @@ public function enqueueNotice($notice, array $args = [], $blog_id = 0)
return $key; // For dismissals.
}
- /*
+ /**
* Dismiss an administrative notice.
*
* @since 151002 Improving multisite compat.
@@ -79,7 +79,7 @@ public function dismissNotice($key_to_dismiss, $blog_id = 0)
return $notices; // All remaining notices.
}
- /*
+ /**
* Enqueue an administrative error notice.
*
* @since 150422 Rewrite. Improved 151002.
@@ -89,7 +89,7 @@ public function enqueueError($notice, array $args = [], $blog_id = 0)
return $this->enqueueNotice($notice, array_merge($args, ['class' => 'error']), $blog_id);
}
- /*
+ /**
* Enqueue an administrative notice (main site).
*
* @since 151002. Improving multisite compat.
@@ -99,7 +99,7 @@ public function enqueueMainNotice($notice, array $args = [])
return $this->enqueueNotice($notice, $args, -1);
}
- /*
+ /**
* Enqueue an administrative error notice (main site).
*
* @since 151002. Improving multisite compat.
@@ -109,7 +109,7 @@ public function enqueueMainError($notice, array $args = [])
return $this->enqueueNotice($notice, array_merge($args, ['class' => 'error']), -1);
}
- /*
+ /**
* Dismiss an administrative notice (main site).
*
* @since 151002 Improving multisite compat.
@@ -123,7 +123,7 @@ public function dismissMainNotice($key_to_dismiss)
* Notice display handler.
*/
- /*
+ /**
* Render admin notices.
*
* @since 150422 Rewrite. Improved 151002.
@@ -181,7 +181,7 @@ public function allAdminNotices()
* Notice getter/setter.
*/
- /*
+ /**
* Get admin notices.
*
* @since 151002 Improving multisite compat.
@@ -222,7 +222,7 @@ public function getNotices($blog_id = 0)
return $notices;
}
- /*
+ /**
* Update admin notices.
*
* @since 151002 Improving multisite compat.
@@ -255,7 +255,7 @@ public function updateNotices(array $notices, $blog_id = 0)
* Notice property utilities.
*/
- /*
+ /**
* Normalize notice elements.
*
* @since 151002 Improving multisite compat.
diff --git a/src/includes/traits/Plugin/OptionUtils.php b/src/includes/traits/Plugin/OptionUtils.php
index 93c78630..db404387 100644
--- a/src/includes/traits/Plugin/OptionUtils.php
+++ b/src/includes/traits/Plugin/OptionUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait OptionUtils {
- /*
+ /**
* Get plugin options.
*
* @since 151002 Improving multisite compat.
@@ -38,7 +38,7 @@ public function getOptions()
return $this->options; // Plugin options.
}
- /*
+ /**
* Update plugin options.
*
* @since 151002 Improving multisite compat.
@@ -62,7 +62,7 @@ public function updateOptions(array $options)
return $this->getOptions();
}
- /*
+ /**
* Restore default plugin options.
*
* @since 151002 Improving multisite compat.
diff --git a/src/includes/traits/Plugin/PostUtils.php b/src/includes/traits/Plugin/PostUtils.php
index 69431ec5..1b0f7f0d 100644
--- a/src/includes/traits/Plugin/PostUtils.php
+++ b/src/includes/traits/Plugin/PostUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait PostUtils {
- /*
+ /**
* All post statuses.
*
* @since 150821 Improving bbPress support.
@@ -22,7 +22,7 @@ public function postStatuses()
return $statuses;
}
- /*
+ /**
* All built-in post statuses.
*
* @since 150821 Improving bbPress support.
diff --git a/src/includes/traits/Plugin/StatsUtils.php b/src/includes/traits/Plugin/StatsUtils.php
index f250958d..10a1a5e2 100644
--- a/src/includes/traits/Plugin/StatsUtils.php
+++ b/src/includes/traits/Plugin/StatsUtils.php
@@ -5,7 +5,7 @@
use WebSharks\CometCache\Pro\Classes;
trait StatsUtils {
- /*
+ /**
* Pings our stats log w/ anonymous details.
*
* @since 150716 Adding stats logging.
diff --git a/src/includes/traits/Plugin/UpdateUtils.php b/src/includes/traits/Plugin/UpdateUtils.php
index d17efe19..c5196d1f 100644
--- a/src/includes/traits/Plugin/UpdateUtils.php
+++ b/src/includes/traits/Plugin/UpdateUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait UpdateUtils {
- /*
+ /**
* Checks for a new lite release.
*
* @since 151220 Show version number in plugin options.
@@ -48,7 +48,7 @@ public function maybeCheckLatestLiteVersion()
}
/*[pro strip-from="lite"]*/
- /*
+ /**
* Checks for a new pro release.
*
* @since 150422 Rewrite.
@@ -89,7 +89,7 @@ public function maybeCheckLatestProVersion()
}
}
- /*
+ /**
* Modifies transient data associated with this plugin.
*
* @since 150422 Rewrite.
@@ -140,7 +140,7 @@ public function preSiteTransientUpdatePlugins($transient)
return $transient; // Nodified now.
}
- /*
+ /**
* Appends hidden inputs for pro updater when FTP credentials are requested by WP.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/UrlUtils.php b/src/includes/traits/Plugin/UrlUtils.php
index 4ba05dee..f8295ec1 100644
--- a/src/includes/traits/Plugin/UrlUtils.php
+++ b/src/includes/traits/Plugin/UrlUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait UrlUtils {
- /*
+ /**
* URL to a Comet Cache plugin file.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/UserUtils.php b/src/includes/traits/Plugin/UserUtils.php
index 3e26d30c..e2417382 100644
--- a/src/includes/traits/Plugin/UserUtils.php
+++ b/src/includes/traits/Plugin/UserUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait UserUtils {
- /*
+ /**
* Current user can clear the cache?
*
* @since 151002 Enhancing user permissions.
@@ -37,7 +37,7 @@ public function currentUserCanClearCache()
return ($can = false);
}
- /*
+ /**
* Alias for currentUserCanClearCache()
*
* @since 151002 Enhancing user permissions.
@@ -49,7 +49,7 @@ public function currentUserCanWipeCache()
return call_user_func_array([$this, 'currentUserCanClearCache'], func_get_args());
}
- /*
+ /**
* Current user can clear the opcache?
*
* @since 151114 Enhancing user permissions.
@@ -72,7 +72,7 @@ public function currentUserCanClearOpCache()
return ($can = false);
}
- /*
+ /**
* Alias for currentUserCanClearOpCache()
*
* @since 151114 Enhancing user permissions.
@@ -84,7 +84,7 @@ public function currentUserCanWipeOpCache()
return call_user_func_array([$this, 'currentUserCanClearOpCache'], func_get_args());
}
- /*
+ /**
* Current user can clear the CDN cache?
*
* @since 151114 Enhancing user permissions.
@@ -107,7 +107,7 @@ public function currentUserCanClearCdnCache()
return ($can = false);
}
- /*
+ /**
* Alias for currentUserCanClearCdnCache()
*
* @since 151114 Enhancing user permissions.
@@ -119,7 +119,7 @@ public function currentUserCanWipeCdnCache()
return call_user_func_array([$this, 'currentUserCanClearCdnCache'], func_get_args());
}
- /*
+ /**
* Current user can clear expired transients?
*
* @since 151220 Enhancing user permissions.
@@ -142,7 +142,7 @@ public function currentUserCanClearExpiredTransients()
return ($can = false);
}
- /*
+ /**
* Alias for currentUserCanClearExpiredTransients()
*
* @since 151220 Enhancing user permissions.
@@ -154,7 +154,7 @@ public function currentUserCanWipeExpiredTransients()
return call_user_func_array([$this, 'currentUserCanClearExpiredTransients'], func_get_args());
}
- /*
+ /**
* Current user can see stats?
*
* @since 151002 Enhancing user permissions.
diff --git a/src/includes/traits/Plugin/WcpAuthorUtils.php b/src/includes/traits/Plugin/WcpAuthorUtils.php
index 1f49dd82..74e69023 100644
--- a/src/includes/traits/Plugin/WcpAuthorUtils.php
+++ b/src/includes/traits/Plugin/WcpAuthorUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpAuthorUtils {
- /*
+ /**
* Automatically clears cache files for the author page(s).
*
* @attaches-to `post_updated` hook.
diff --git a/src/includes/traits/Plugin/WcpCdnUtils.php b/src/includes/traits/Plugin/WcpCdnUtils.php
index 7047e6a1..0ae80491 100644
--- a/src/includes/traits/Plugin/WcpCdnUtils.php
+++ b/src/includes/traits/Plugin/WcpCdnUtils.php
@@ -5,7 +5,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpCdnUtils {
- /*
+ /**
* Wipes out entire CDN cache.
*
* @since 151002 Implementing CDN cache wiping.
@@ -31,7 +31,7 @@ public function wipeCdnCache($manually = false, $maybe = true)
return (integer) $this->options['cdn_invalidation_counter'];
}
- /*
+ /**
* Clears the CDN cache.
*
* @since 151002 Implementing CDN cache clearing.
diff --git a/src/includes/traits/Plugin/WcpCommentUtils.php b/src/includes/traits/Plugin/WcpCommentUtils.php
index 6a09de3e..b8acc8bb 100644
--- a/src/includes/traits/Plugin/WcpCommentUtils.php
+++ b/src/includes/traits/Plugin/WcpCommentUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpCommentUtils {
- /*
+ /**
* Automatically clears cache files for a post associated with a particular comment.
*
* @since 150422 Rewrite.
@@ -51,7 +51,7 @@ public function autoClearCommentPostCache($comment_id)
return $counter;
}
- /*
+ /**
* Automatically clears cache files for a post associated with a particular comment.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/WcpEvalUtils.php b/src/includes/traits/Plugin/WcpEvalUtils.php
index e540cf38..44583577 100644
--- a/src/includes/traits/Plugin/WcpEvalUtils.php
+++ b/src/includes/traits/Plugin/WcpEvalUtils.php
@@ -6,7 +6,7 @@
trait WcpEvalUtils {
- /*
+ /**
* Wipe (i.e., eval) custom code.
*
* @since 151002 Enhancing eval support.
@@ -35,7 +35,7 @@ public function wipeEvalCode($manually = false, $maybe = true)
return ($result = ob_get_clean());
}
- /*
+ /**
* Clear (i.e., eval) custom code.
*
* @since 151002 Enhancing eval support.
diff --git a/src/includes/traits/Plugin/WcpFeedUtils.php b/src/includes/traits/Plugin/WcpFeedUtils.php
index 9e87f207..5c0f445b 100644
--- a/src/includes/traits/Plugin/WcpFeedUtils.php
+++ b/src/includes/traits/Plugin/WcpFeedUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpFeedUtils {
- /*
+ /**
* Automatically clears cache files related to XML feeds.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/WcpHomeBlogUtils.php b/src/includes/traits/Plugin/WcpHomeBlogUtils.php
index c46bfb29..4c221208 100644
--- a/src/includes/traits/Plugin/WcpHomeBlogUtils.php
+++ b/src/includes/traits/Plugin/WcpHomeBlogUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpHomeBlogUtils {
- /*
+ /**
* Automatically clears cache files for the home page.
*
* @since 150422 Rewrite.
@@ -48,7 +48,7 @@ public function autoClearHomePageCache()
return $counter;
}
- /*
+ /**
* Automatically clears cache files for the posts page.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/WcpHtmlCUtils.php b/src/includes/traits/Plugin/WcpHtmlCUtils.php
index 42ec0a98..ebcb84af 100644
--- a/src/includes/traits/Plugin/WcpHtmlCUtils.php
+++ b/src/includes/traits/Plugin/WcpHtmlCUtils.php
@@ -5,7 +5,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpHtmlCUtils {
- /*
+ /**
* Wipes out all HTML Compressor cache files.
*
* @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
@@ -37,7 +37,7 @@ public function wipeHtmlCCache($manually = false)
return $counter;
}
- /*
+ /**
* Clear all HTML Compressor cache files for the current blog.
*
* @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
diff --git a/src/includes/traits/Plugin/WcpJetpackUtils.php b/src/includes/traits/Plugin/WcpJetpackUtils.php
index 702a9cd9..0c7b1b18 100644
--- a/src/includes/traits/Plugin/WcpJetpackUtils.php
+++ b/src/includes/traits/Plugin/WcpJetpackUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpJetpackUtils {
- /*
+ /**
* Automatically clears all cache files for current blog when JetPack Custom CSS is saved.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/WcpOpcacheUtils.php b/src/includes/traits/Plugin/WcpOpcacheUtils.php
index ca1b1de6..80b02f99 100644
--- a/src/includes/traits/Plugin/WcpOpcacheUtils.php
+++ b/src/includes/traits/Plugin/WcpOpcacheUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpOpcacheUtils {
- /*
+ /**
* Wipe (i.e., reset) OPCache.
*
* @since 151002 Adding OPCache support.
@@ -44,7 +44,7 @@ public function wipeOpcache($manually = false, $maybe = true, $files = [])
return $counter;
}
- /*
+ /**
* Clear (i.e., reset) OPCache.
*
* @since 151002 Adding OPCache support.
@@ -62,7 +62,7 @@ public function clearOpcache($manually = false, $maybe = true)
return 0; // Not applicable.
}
- /*
+ /**
* Clear AC class file from Opcache (by force).
*
* @since 151215 Adding OPCache support.
diff --git a/src/includes/traits/Plugin/WcpPluginUtils.php b/src/includes/traits/Plugin/WcpPluginUtils.php
index 75a507e2..f5675dd6 100644
--- a/src/includes/traits/Plugin/WcpPluginUtils.php
+++ b/src/includes/traits/Plugin/WcpPluginUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpPluginUtils {
- /*
+ /**
* Automatically wipes/clears on plugin activation/deactivation.
*
* @since 151220 Adding auto-wipe|clear on plugin activations/deactivations.
diff --git a/src/includes/traits/Plugin/WcpPostTypeUtils.php b/src/includes/traits/Plugin/WcpPostTypeUtils.php
index faa5682f..34947d8d 100644
--- a/src/includes/traits/Plugin/WcpPostTypeUtils.php
+++ b/src/includes/traits/Plugin/WcpPostTypeUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpPostTypeUtils {
- /*
+ /**
* Automatically clears cache files for a custom post type archive view.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/WcpPostUtils.php b/src/includes/traits/Plugin/WcpPostUtils.php
index a82fe962..439cd184 100644
--- a/src/includes/traits/Plugin/WcpPostUtils.php
+++ b/src/includes/traits/Plugin/WcpPostUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpPostUtils {
- /*
+ /**
* Automatically clears cache files for a particular post.
*
* @attaches-to `save_post` hook.
@@ -122,7 +122,7 @@ public function auto_clear_post_cache()
return call_user_func_array([$this, 'autoClearPostCache'], func_get_args());
}
- /*
+ /**
* Handles post status transitioning.
*
* @attaches-to `pre_post_update` hook.
diff --git a/src/includes/traits/Plugin/WcpS2cleanUtils.php b/src/includes/traits/Plugin/WcpS2cleanUtils.php
index 61d312ec..3c0e6cc6 100644
--- a/src/includes/traits/Plugin/WcpS2cleanUtils.php
+++ b/src/includes/traits/Plugin/WcpS2cleanUtils.php
@@ -5,7 +5,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpS2cleanUtils {
- /*
+ /**
* Wipe (i.e., reset) s2Clean cache.
*
* @since 151002 While adding OPCache support.
@@ -30,7 +30,7 @@ public function wipeS2CleanCache($manually = false, $maybe = true)
return $counter;
}
- /*
+ /**
* Clear (i.e., reset) s2Clean cache.
*
* @since 151002 While adding OPCache support.
diff --git a/src/includes/traits/Plugin/WcpSettingUtils.php b/src/includes/traits/Plugin/WcpSettingUtils.php
index 7f76836f..6c629922 100644
--- a/src/includes/traits/Plugin/WcpSettingUtils.php
+++ b/src/includes/traits/Plugin/WcpSettingUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpSettingUtils {
- /*
+ /**
* Automatically clears all cache files for current blog under various conditions;
* used to check for conditions that don't have a hook that we can attach to.
*
diff --git a/src/includes/traits/Plugin/WcpSitemapUtils.php b/src/includes/traits/Plugin/WcpSitemapUtils.php
index b0dace02..88a346ab 100644
--- a/src/includes/traits/Plugin/WcpSitemapUtils.php
+++ b/src/includes/traits/Plugin/WcpSitemapUtils.php
@@ -5,7 +5,7 @@
trait WcpSitemapUtils {
- /*
+ /**
* Automatically clears cache files related to XML sitemaps.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/WcpTermUtils.php b/src/includes/traits/Plugin/WcpTermUtils.php
index dd3bffb5..a44697e8 100644
--- a/src/includes/traits/Plugin/WcpTermUtils.php
+++ b/src/includes/traits/Plugin/WcpTermUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpTermUtils {
- /*
+ /**
* Automatically clears cache files for terms associated with a post.
*
* @attaches-to `added_term_relationship` hook.
diff --git a/src/includes/traits/Plugin/WcpTransientUtils.php b/src/includes/traits/Plugin/WcpTransientUtils.php
index 0e8ed9c4..0c6226a2 100644
--- a/src/includes/traits/Plugin/WcpTransientUtils.php
+++ b/src/includes/traits/Plugin/WcpTransientUtils.php
@@ -6,7 +6,7 @@
trait WcpTransientUtils
{
- /*
+ /**
* Automatically wipes expired transients.
*
* @since 151220 Adding support for expired transients.
@@ -65,7 +65,7 @@ public function wipeExpiredTransients($manually = false, $maybe = true)
return $counter;
}
- /*
+ /**
* Automatically clears expired transients.
*
* @since 151220 Adding support for expired transients.
diff --git a/src/includes/traits/Plugin/WcpUpdaterUtils.php b/src/includes/traits/Plugin/WcpUpdaterUtils.php
index b6e918e5..43d5920f 100644
--- a/src/includes/traits/Plugin/WcpUpdaterUtils.php
+++ b/src/includes/traits/Plugin/WcpUpdaterUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpUpdaterUtils {
- /*
+ /**
* Automatically clears all cache files for current blog when WordPress core, or an active component, is upgraded.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/WcpUrlUtils.php b/src/includes/traits/Plugin/WcpUrlUtils.php
index 9fcc9aef..0ae4e774 100644
--- a/src/includes/traits/Plugin/WcpUrlUtils.php
+++ b/src/includes/traits/Plugin/WcpUrlUtils.php
@@ -5,7 +5,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpUtlUtils {
- /*
+ /**
* Automatically clears cache files for a list of custom URLs.
*
* @since 151114 Adding support for a custom list of URLs.
diff --git a/src/includes/traits/Plugin/WcpUserUtils.php b/src/includes/traits/Plugin/WcpUserUtils.php
index 78464b79..4966ed8c 100644
--- a/src/includes/traits/Plugin/WcpUserUtils.php
+++ b/src/includes/traits/Plugin/WcpUserUtils.php
@@ -5,7 +5,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpUserUtils {
- /*
+ /**
* Clears cache files associated with a particular user.
*
* @since 150422 Rewrite.
@@ -59,7 +59,7 @@ public function auto_clear_user_cache()
return call_user_func_array([$this, 'autoClearUserCache'], func_get_args());
}
- /*
+ /**
* Automatically clears cache files associated with a particular user.
*
* @since 150422 Rewrite.
@@ -73,7 +73,7 @@ public function autoClearUserCacheA1($user_id)
$this->autoClearUserCache($user_id);
}
- /*
+ /**
* Automatically clears cache files associated with a particular user.
*
* @since 151220 Using `updated_user_meta` instead of `update_user_metadata`
@@ -88,7 +88,7 @@ public function autoClearUserCacheA2($meta_id, $object_id)
$this->autoClearUserCache($object_id);
}
- /*
+ /**
* Automatically clears cache files associated with a particular user.
*
* @since 150422 Rewrite.
@@ -108,7 +108,7 @@ public function autoClearUserCacheFA2($value, $user_id)
return $value; // Filter.
}
- /*
+ /**
* Automatically clears cache files associated with a particular user.
*
* @since 150422 Rewrite.
@@ -125,7 +125,7 @@ public function autoClearUserCacheA4($_, $__, $___, $user_id)
$this->autoClearUserCache($user_id);
}
- /*
+ /**
* Automatically clears cache files associated with current user.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Plugin/WcpUtils.php b/src/includes/traits/Plugin/WcpUtils.php
index 54d6ce0e..4514e7b2 100644
--- a/src/includes/traits/Plugin/WcpUtils.php
+++ b/src/includes/traits/Plugin/WcpUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpUtils {
- /*
+ /**
* Used for temporarily storing the permalink for posts transitioning from
* `publish` or `private` post status to `pending` or `draft` post status.
*
@@ -15,7 +15,7 @@ trait WcpUtils {
*/
public $pre_post_update_post_permalink = [];
- /*
+ /**
* Wipes out all cache files.
*
* @since 150422 Rewrite.
@@ -68,7 +68,7 @@ public function wipe_cache()
return call_user_func_array([$this, 'wipeCache'], func_get_args());
}
- /*
+ /**
* Clears cache files (current blog).
*
* @since 150422 Rewrite.
@@ -121,7 +121,7 @@ public function clear_cache()
return call_user_func_array([$this, 'clearCache'], func_get_args());
}
- /*
+ /**
* Purges expired cache files (current blog).
*
* @since 150422 Rewrite.
@@ -162,7 +162,7 @@ public function purge_cache()
return call_user_func_array([$this, 'purgeCache'], func_get_args());
}
- /*
+ /**
* Wurges (purges) all expired cache files; like wipe, but expired files only.
*
* @since 151002 Look at entire cache directory.
@@ -195,7 +195,7 @@ public function wurgeCache($manually = false)
return $counter;
}
- /*
+ /**
* Automatically wipes out all cache files.
*
* @attaches-to Nothing at this time.
@@ -233,7 +233,7 @@ public function autoWipeCache()
return $counter;
}
- /*
+ /**
* Automatically clears all cache files (current host).
*
* @attaches-to `switch_theme` hook.
@@ -282,7 +282,7 @@ public function autoClearCache()
return $counter;
}
- /*
+ /**
* Automatically purges all cache files (current host).
*
* @attaches-to Nothing at this time.
@@ -319,7 +319,7 @@ public function autoPurgeCache()
return $counter;
}
- /*
+ /**
* Automatically wurges all cache files.
*
* @attaches-to Nothing at this time.
@@ -356,7 +356,7 @@ public function autoWurgeCache()
return $counter;
}
- /*
+ /**
* Allows a site owner to disable the automatic cache wiping routines.
*
* This is done by filtering `'.__GLOBAL_NS__.'_disable_auto_wipe_cache_routines` to return TRUE,
@@ -379,7 +379,7 @@ public function disableAutoWipeCacheRoutines()
return $is_disabled;
}
- /*
+ /**
* Allows a site owner to disable the automatic cache clearing routines.
*
* This is done by filtering `'.__GLOBAL_NS__.'_disable_auto_clear_cache_routines` to return TRUE,
@@ -402,7 +402,7 @@ public function disableAutoClearCacheRoutines()
return $is_disabled;
}
- /*
+ /**
* Allows a site owner to disable the automatic cache purging routines.
*
* This is done by filtering `'.__GLOBAL_NS__.'_disable_auto_purge_cache_routines` to return TRUE,
diff --git a/src/includes/traits/Plugin/WcpWooCommerceUtils.php b/src/includes/traits/Plugin/WcpWooCommerceUtils.php
index 4e518f01..28379548 100644
--- a/src/includes/traits/Plugin/WcpWooCommerceUtils.php
+++ b/src/includes/traits/Plugin/WcpWooCommerceUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait WcpWooCommerceUtils {
- /*
+ /**
* Automatically clears cache file for a WooCommerce Product when its stock is changed.
*
* @since 151220 Improving WooCommerce Compatibility.
diff --git a/src/includes/traits/Shared/BlogUtils.php b/src/includes/traits/Shared/BlogUtils.php
index e9c2af67..1cbfc46f 100644
--- a/src/includes/traits/Shared/BlogUtils.php
+++ b/src/includes/traits/Shared/BlogUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait BlogUtils {
- /*
+ /**
* Get blog details.
*
* @since 150821 Improving multisite compat.
diff --git a/src/includes/traits/Shared/CacheDirUtils.php b/src/includes/traits/Shared/CacheDirUtils.php
index de98c05b..8d39c338 100644
--- a/src/includes/traits/Shared/CacheDirUtils.php
+++ b/src/includes/traits/Shared/CacheDirUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait CacheDirUtils {
- /*
+ /**
* Cache directory path.
*
* @since 150422 Rewrite.
@@ -30,7 +30,7 @@ public function cacheDir($rel_path = '')
return rtrim($cache_dir, '/').($rel_path ? '/'.ltrim($rel_path) : '');
}
- /*
+ /**
* Wipe files from the cache directory (for all hosts/blogs);
* i.e., those that match a specific regex pattern.
*
@@ -45,7 +45,7 @@ public function wipeFilesFromCacheDir($regex)
return $this->deleteFilesFromCacheDir($regex);
}
- /*
+ /**
* Clear files from the cache directory (for the current host);
* i.e., those that match a specific regex pattern.
*
@@ -60,7 +60,7 @@ public function clearFilesFromHostCacheDir($regex)
return $this->deleteFilesFromHostCacheDir($regex);
}
- /*
+ /**
* Wurge (purge) files from the cache directory (for all hosts/blogs);
* i.e., those that match a specific regex pattern.
*
@@ -75,7 +75,7 @@ public function wurgeFilesFromCacheDir($regex)
return $this->deleteFilesFromCacheDir($regex, true);
}
- /*
+ /**
* Purge files from the cache directory (for the current host);
* i.e., those that match a specific regex pattern.
*
@@ -90,7 +90,7 @@ public function purgeFilesFromHostCacheDir($regex)
return $this->deleteFilesFromHostCacheDir($regex, true);
}
- /*
+ /**
* Delete files from the cache directory (for all hosts/blogs);
* i.e., those that match a specific regex pattern.
*
@@ -233,7 +233,7 @@ public function deleteFilesFromCacheDir($regex, $check_max_age = false)
return $counter;
}
- /*
+ /**
* Delete files from the cache directory (for the current host);
* i.e., those that match a specific regex pattern.
*
@@ -431,7 +431,7 @@ public function deleteFilesFromHostCacheDir(
return $counter;
}
- /*
+ /**
* Delete all files/dirs from a directory (for all schemes/hosts);
* including `[SHORT_NAME]-` prefixed files; or anything else for that matter.
*
@@ -537,7 +537,7 @@ public function deleteAllFilesDirsIn($dir, $delete_dir_too = false)
return $counter;
}
- /*
+ /**
* Erase all files/dirs from a directory (for all schemes/hosts);
* including `[SHORT_NAME]-` prefixed files; or anything else for that matter.
*
@@ -625,7 +625,7 @@ public function eraseAllFilesDirsIn($dir, $erase_dir_too = false)
return $counter;
}
- /*
+ /**
* Try to erase all files/dirs from a directory (for all schemes/hosts);
* including `[SHORT_NAME]-` prefixed files; or anything else for that matter.
*
diff --git a/src/includes/traits/Shared/CacheLockUtils.php b/src/includes/traits/Shared/CacheLockUtils.php
index 10f3d4b9..6dd03b37 100644
--- a/src/includes/traits/Shared/CacheLockUtils.php
+++ b/src/includes/traits/Shared/CacheLockUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait CacheLockUtils {
- /*
+ /**
* Get an exclusive lock on the cache directory.
*
* @since 150422 Rewrite.
@@ -58,7 +58,7 @@ public function cacheLock()
return ['type' => 'flock', 'resource' => $resource];
}
- /*
+ /**
* Release an exclusive lock on the cache directory.
*
* @since 150422 Rewrite. Updated 151002 to remove the `array` typecast.
diff --git a/src/includes/traits/Shared/CachePathUtils.php b/src/includes/traits/Shared/CachePathUtils.php
index 9f0ca635..671c516e 100644
--- a/src/includes/traits/Shared/CachePathUtils.php
+++ b/src/includes/traits/Shared/CachePathUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait CachePathUtils {
- /*
+ /**
* Cache-path suffix frag (regex).
*
* @since 151220 Enhancing translation support.
@@ -21,7 +21,7 @@ public function cachePathRegexSuffixFrag($regex_suffix_frag = CACHE_PATH_REGEX_D
return (string) $regex_suffix_frag;
}
- /*
+ /**
* Default cache-path suffix frag (regex).
*
* @since 151220 Enhancing translation support.
@@ -41,7 +41,7 @@ public function cachePathRegexDefaultSuffixFrag()
}
}
- /*
+ /**
* Converts a URL into a `cache/path` based on input `$flags`.
*
* @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
@@ -181,7 +181,7 @@ public function buildCachePath($url, $with_user_token = '', $with_version_salt =
return $cache_path;
}
- /*
+ /**
* Regex pattern for a call to `deleteFilesFromCacheDir()`.
*
* @since 151114 Updated to support an arbitrary URL instead of a regex frag.
@@ -212,7 +212,7 @@ public function buildCachePathRegex($url, $regex_suffix_frag = CACHE_PATH_REGEX_
return '/^'.$cache_path_regex.$regex_suffix_frag.'/i';
}
- /*
+ /**
* Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
*
* @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
@@ -259,7 +259,7 @@ public function buildHostCachePathRegex($url, $regex_suffix_frag = CACHE_PATH_RE
return '/^'.$abs_relative_cache_path_regex.$regex_suffix_frag.'/i';
}
- /*
+ /**
* Regex pattern for a call to `deleteFilesFromCacheDir()`.
*
* @since 151114 Improving watered-down regex syntax.
@@ -293,7 +293,7 @@ public function buildCachePathRegexFromWcUrl($url, $regex_suffix_frag = CACHE_PA
return '/^'.$cache_path_regex.$regex_suffix_frag.'/i';
}
- /*
+ /**
* Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
*
* @since 150422 Rewrite. Updated 151002 w/ multisite compat. improvements.
@@ -337,7 +337,7 @@ public function buildHostCachePathRegexFragsFromWcUris($uris, $regex_suffix_frag
return $uri_patterns ? '(?:'.implode('|', array_unique($uri_patterns)).')'.$regex_suffix_frag : '';
}
- /*
+ /**
* Regex pattern for a call to `deleteFilesFromCacheDir()`.
*
* @since 151114 Moving this low-level routine into a method of a different name.
diff --git a/src/includes/traits/Shared/ConditionalUtils.php b/src/includes/traits/Shared/ConditionalUtils.php
index cad12724..9e89a59d 100644
--- a/src/includes/traits/Shared/ConditionalUtils.php
+++ b/src/includes/traits/Shared/ConditionalUtils.php
@@ -30,7 +30,7 @@ trait ConditionalUtils {
'__halt_compiler' => '__halt_compiler',
];
- /*
+ /**
* Is AdvancedCache class?
*
* @since 150821 Improving multisite compat.
@@ -42,7 +42,7 @@ public function isAdvancedCache()
return $this instanceof Classes\AdvancedCache;
}
- /*
+ /**
* Is Plugin class?
*
* @since 150821 Improving multisite compat.
@@ -54,7 +54,7 @@ public function isPlugin()
return $this instanceof Classes\Plugin;
}
- /*
+ /**
* Is the current request method `POST`, `PUT` or `DELETE`?
*
* @since 150422 Rewrite.
@@ -79,7 +79,7 @@ public function isPostPutDeleteRequest()
return ($is = false);
}
- /*
+ /**
* Does the current request include an uncacheable query string?
*
* @since 151002 Improving Nginx support.
@@ -106,7 +106,7 @@ public function requestContainsUncacheableQueryVars()
return ($is = false);
}
- /*
+ /**
* Is the current request method is uncacheable?
*
* @since 150422 Rewrite.
@@ -131,7 +131,7 @@ public function isUncacheableRequestMethod()
return ($is = false);
}
- /*
+ /**
* Should the current user should be considered a logged-in user?
*
* @since 150422 Rewrite.
@@ -173,7 +173,7 @@ public function isLikeUserLoggedIn()
return ($is = false);
}
- /*
+ /**
* Are we in a LOCALHOST environment?
*
* @since 150422 Rewrite.
@@ -197,7 +197,7 @@ public function isLocalhost()
}
/*[pro strip-from="lite"]*/
- /*
+ /**
* Is the current request for the Auto-Cache Engine?
*
* @since 150422 Rewrite.
@@ -220,7 +220,7 @@ public function isAutoCacheEngine()
}
/*[/pro]*/
- /*
+ /**
* Is the current request for a feed?
*
* @since 150422 Rewrite.
@@ -245,7 +245,7 @@ public function isFeed()
return ($is = false);
}
- /*
+ /**
* Is a document/string an HTML/XML doc; or no?
*
* @since 150422 Rewrite.
@@ -271,7 +271,7 @@ public function isHtmlXmlDoc($doc)
return ($is = false);
}
- /*
+ /**
* Does the current request have a cacheable content type?
*
* @since 150422 Rewrite.
@@ -302,7 +302,7 @@ public function hasACacheableContentType()
return ($is = true);
}
- /*
+ /**
* Does the current request have a cacheable HTTP status code?
*
* @since 150422 Rewrite.
@@ -335,7 +335,7 @@ public function hasACacheableStatus()
return ($is = true);
}
- /*
+ /**
* Checks if a PHP extension is loaded up.
*
* @since 150422 Rewrite.
@@ -356,7 +356,7 @@ public function isExtensionLoaded($extension)
return ($is = (boolean) extension_loaded($extension));
}
- /*
+ /**
* Is a particular function possible in every way?
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Shared/DomainMappingUtils.php b/src/includes/traits/Shared/DomainMappingUtils.php
index 1a03bf3a..40586f6d 100644
--- a/src/includes/traits/Shared/DomainMappingUtils.php
+++ b/src/includes/traits/Shared/DomainMappingUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait DomainMappingUtils {
- /*
+ /**
* Can consider domain mapping?
*
* @since 150821 Improving multisite compat.
@@ -26,7 +26,7 @@ public function canConsiderDomainMapping()
return ($can = false); // Cannot consider.
}
- /*
+ /**
* Domain mapping?
*
* @since 150821 Improving multisite compat.
@@ -48,7 +48,7 @@ public function isDomainMapping()
return ($is = 0); // Not domain mapping.
}
- /*
+ /**
* Filters a URL in order to apply domain mapping.
*
* @since 150821 Improving multisite compat.
@@ -91,7 +91,7 @@ public function domainMappingUrlFilter($url)
return ($url = $this->unParseUrl($url_parts));
}
- /*
+ /**
* Filters a URL in order to remove domain mapping.
*
* @since 150821 Improving multisite compat.
@@ -129,7 +129,7 @@ public function domainMappingReverseUrlFilter($url)
return ($url = $this->unParseUrl($url_parts));
}
- /*
+ /**
* Converts a host into a mapped blog ID.
*
* @since 150821 Improving multisite compat.
@@ -180,7 +180,7 @@ public function domainMappingBlogId($url = '', $domain = '')
return ($blog_id = (integer) $blog_id);
}
- /*
+ /**
* Converts a blog ID into a mapped domain.
*
* @since 150821 Improving multisite compat.
@@ -233,7 +233,7 @@ public function domainMappingBlogDomain($blog_id = 0, $fallback = false)
return ($domain = strtolower((string) $domain));
}
- /*
+ /**
* Converts a blog ID into mapped domains (plural).
*
* @since 150821 Improving multisite compat.
diff --git a/src/includes/traits/Shared/EscapeUtils.php b/src/includes/traits/Shared/EscapeUtils.php
index d82dbe26..21093f5e 100644
--- a/src/includes/traits/Shared/EscapeUtils.php
+++ b/src/includes/traits/Shared/EscapeUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait EscapeUtils {
- /*
+ /**
* Escape single quotes.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Shared/FsUtils.php b/src/includes/traits/Shared/FsUtils.php
index a17ae409..5f2bed8a 100644
--- a/src/includes/traits/Shared/FsUtils.php
+++ b/src/includes/traits/Shared/FsUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait FsUtils {
- /*
+ /**
* Normalizes directory/file separators.
*
* @since 150422 Rewrite.
@@ -42,7 +42,7 @@ public function nDirSeps($dir_file, $allow_trailing_slash = false)
return $dir_file; // Normalized now.
}
- /*
+ /**
* Acquires system tmp directory path.
*
* @since 150422 Rewrite.
@@ -92,7 +92,7 @@ public function getTmpDir()
return ($dir = '');
}
- /*
+ /**
* Finds absolute server path to `/wp-config.php` file.
*
* @since 150422 Rewrite.
@@ -115,7 +115,7 @@ public function findWpConfigFile()
return $file;
}
- /*
+ /**
* Adds a tmp name suffix to a directory/file path.
*
* @since 150422 Rewrite.
@@ -132,7 +132,7 @@ public function addTmpSuffix($dir_file)
return $dir_file.'-'.str_replace('.', '', uniqid('', true)).'-tmp';
}
- /*
+ /**
* Recursive directory iterator based on a regex pattern.
*
* @since 150422 Rewrite.
@@ -158,7 +158,7 @@ public function dirRegexIteration($dir, $regex = '')
return $iterator_iterator; // Iterate everything.
}
- /*
+ /**
* Abbreviated byte notation for file sizes.
*
* @since 151002 Adding a few statistics.
@@ -186,7 +186,7 @@ public function bytesAbbr($bytes, $precision = 2)
return $abbr_bytes.' '.$abbr;
}
- /*
+ /**
* Converts an abbreviated byte notation into bytes.
*
* @since 151002 Adding a few statistics.
@@ -228,7 +228,7 @@ public function abbrBytes($string)
return (float) $value;
}
- /*
+ /**
* Directory stats.
*
* @since 151002 Adding a few statistics.
@@ -324,7 +324,7 @@ public function getDirRegexStats($dir, $regex = '', $include_paths = false, $che
return $stats;
}
- /*
+ /**
* Apache `.htaccess` rules that deny public access to the contents of a directory.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Shared/HookUtils.php b/src/includes/traits/Shared/HookUtils.php
index 47c69685..26b5f1e8 100644
--- a/src/includes/traits/Shared/HookUtils.php
+++ b/src/includes/traits/Shared/HookUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait HookUtils {
- /*
+ /**
* Array of hooks.
*
* @since 150422 Rewrite.
@@ -13,7 +13,7 @@ trait HookUtils {
*/
public $hooks = [];
- /*
+ /**
* Assigns an ID to each callable attached to a hook/filter.
*
* @since 150422 Rewrite.
@@ -44,7 +44,7 @@ public function hookId($function)
throw new \Exception(__('Invalid hook.', SLUG_TD));
}
- /*
+ /**
* Adds a new hook (works with both actions & filters).
*
* @since 150422 Rewrite.
@@ -73,7 +73,7 @@ public function addHook($hook, $function, $priority = 10, $accepted_args = 1)
return true; // Always returns true.
}
- /*
+ /**
* Adds a new action hook.
*
* @since 150422 Rewrite.
@@ -93,7 +93,7 @@ public function add_action()
return call_user_func_array([$this, 'addAction'], func_get_args());
}
- /*
+ /**
* Adds a new filter.
*
* @since 150422 Rewrite.
@@ -113,7 +113,7 @@ public function add_filter()
return call_user_func_array([$this, 'addFilter'], func_get_args());
}
- /*
+ /**
* Removes a hook (works with both actions & filters).
*
* @since 150422 Rewrite.
@@ -144,7 +144,7 @@ public function removeHook($hook, $function, $priority = 10)
return true; // Existed before it was removed.
}
- /*
+ /**
* Removes an action.
*
* @since 150422 Rewrite.
@@ -156,7 +156,7 @@ public function removeAction()
return call_user_func_array([$this, 'removeHook'], func_get_args());
}
- /*
+ /**
* Removes a filter.
*
* @since 150422 Rewrite.
@@ -168,7 +168,7 @@ public function removeFilter()
return call_user_func_array([$this, 'removeHook'], func_get_args());
}
- /*
+ /**
* Runs any callables attached to an action.
*
* @since 150422 Rewrite.
@@ -196,7 +196,7 @@ public function doAction($hook)
unset($_hook_action, $_action); // Housekeeping.
}
- /*
+ /**
* Runs any callables attached to a filter.
*
* @since 150422 Rewrite.
@@ -230,7 +230,7 @@ public function applyFilters($hook, $value)
return $value; // With applied filters.
}
- /*
+ /**
* Does an action w/ back compat. for ZenCache.
*
* @since 150422 Rewrite.
@@ -251,7 +251,7 @@ public function doWpAction($hook)
}
}
- /*
+ /**
* Applies filters w/ back compat. for ZenCache.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Shared/HttpUtils.php b/src/includes/traits/Shared/HttpUtils.php
index 57b1350d..29f11b93 100644
--- a/src/includes/traits/Shared/HttpUtils.php
+++ b/src/includes/traits/Shared/HttpUtils.php
@@ -5,7 +5,7 @@
trait HttpUtils
{
- /*
+ /**
* Current HTTP protocol.
*
* @since 150422 Rewrite.
@@ -26,7 +26,7 @@ public function httpProtocol()
return $protocol;
}
- /*
+ /**
* PHP {@link headers_list()} + HTTP status.
*
* @since 150422 Rewrite.
@@ -48,7 +48,7 @@ public function headersList()
return $headers;
}
- /*
+ /**
* PHP {@link headers_list()} + HTTP status.
*
* @since 150422 Rewrite.
@@ -126,7 +126,7 @@ public function cacheableHeadersList()
return $headers;
}
- /*
+ /**
* HTTP status code.
*
* @since 150422 Rewrite.
@@ -162,7 +162,7 @@ public function httpStatus()
return $status;
}
- /*
+ /**
* Sends no-cache headers.
*
* @since 151220 Enhancing no-cache headers.
diff --git a/src/includes/traits/Shared/I18nUtils.php b/src/includes/traits/Shared/I18nUtils.php
index 6c4b0655..01903fff 100644
--- a/src/includes/traits/Shared/I18nUtils.php
+++ b/src/includes/traits/Shared/I18nUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait I18nUtils {
- /*
+ /**
* `X file` or `X files`, translated w/ singlular/plural context.
*
* @since 150422 Rewrite.
@@ -19,7 +19,7 @@ public function i18nFiles($counter)
return sprintf(_n('%1$s file', '%1$s files', $counter, SLUG_TD), $counter);
}
- /*
+ /**
* `X directory` or `X directories`, translated w/ singlular/plural context.
*
* @since 150422 Rewrite.
@@ -34,7 +34,7 @@ public function i18nDirs($counter)
return sprintf(_n('%1$s directory', '%1$s directories', $counter, SLUG_TD), $counter);
}
- /*
+ /**
* `X file/directory` or `X files/directories`, translated w/ singlular/plural context.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Shared/IpAddrUtils.php b/src/includes/traits/Shared/IpAddrUtils.php
index 015818ba..4e20bdc2 100644
--- a/src/includes/traits/Shared/IpAddrUtils.php
+++ b/src/includes/traits/Shared/IpAddrUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait IpAddrUtils {
- /*
+ /**
* Get the current visitor's real IP address.
*
* @since 150422 Rewrite.
@@ -57,7 +57,7 @@ public function currentIp()
return ($ip = 'unknown'); // Not possible.
}
- /*
+ /**
* Gets a valid/public IP address.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Shared/PatternUtils.php b/src/includes/traits/Shared/PatternUtils.php
index 4fd4094c..f0e89017 100644
--- a/src/includes/traits/Shared/PatternUtils.php
+++ b/src/includes/traits/Shared/PatternUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait PatternUtils {
- /*
+ /**
* Convert line-delimited patterns to a regex.
*
* @since 151114 Enhancing exclusion pattern support.
@@ -24,7 +24,7 @@ public function lineDelimitedPatternsToRegex($patterns)
return $regex;
}
- /*
+ /**
* Convert watered-down regex to actual regex.
*
* @since 151114 Enhancing exclusion pattern support.
diff --git a/src/includes/traits/Shared/ReplaceUtils.php b/src/includes/traits/Shared/ReplaceUtils.php
index e741426e..79a8333b 100644
--- a/src/includes/traits/Shared/ReplaceUtils.php
+++ b/src/includes/traits/Shared/ReplaceUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait ReplaceUtils {
- /*
+ /**
* String replace ONE time.
*
* @since 150422 Rewrite.
@@ -31,7 +31,7 @@ public function strReplaceOnce($needle, $replace, $haystack, $caSe_insensitive =
return (string) substr_replace($haystack, $replace, $needle_strpos, strlen($needle));
}
- /*
+ /**
* String replace ONE time (caSe-insensitive).
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Shared/ServerUtils.php b/src/includes/traits/Shared/ServerUtils.php
index 935f3741..6b034962 100644
--- a/src/includes/traits/Shared/ServerUtils.php
+++ b/src/includes/traits/Shared/ServerUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait ServerUtils {
- /*
+ /**
* Is running on Apache?
*
* @since 151002 This is Apache?
@@ -27,7 +27,7 @@ public function isApache()
return ($is = false);
}
- /*
+ /**
* Is running on Nginx?
*
* @since 151002 This is Nginx?
@@ -47,7 +47,7 @@ public function isNginx()
return ($is = false);
}
- /*
+ /**
* Is running on Windows IIS?
*
* @since 151002 This is Windows IIS?
diff --git a/src/includes/traits/Shared/StringUtils.php b/src/includes/traits/Shared/StringUtils.php
index 43abf532..aa292511 100644
--- a/src/includes/traits/Shared/StringUtils.php
+++ b/src/includes/traits/Shared/StringUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait StringUtils {
- /*
+ /**
* Clips string(s) to X chars deeply.
*
* @since 151114 Adding string utils.
@@ -44,7 +44,7 @@ public function clip($value, $max_length = 80, $force_ellipsis = false)
return $string;
}
- /*
+ /**
* Mid-clips string(s) to X chars deeply.
*
* @since 151114 Adding string utils.
diff --git a/src/includes/traits/Shared/SysUtils.php b/src/includes/traits/Shared/SysUtils.php
index fba8642c..7e787e6b 100644
--- a/src/includes/traits/Shared/SysUtils.php
+++ b/src/includes/traits/Shared/SysUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait SysUtils {
- /*
+ /**
* System load averages.
*
* @since 151002 Adding cache directory statistics.
@@ -29,7 +29,7 @@ public function sysLoadAverages()
return $averages;
}
- /*
+ /**
* System memory info.
*
* @since 151002 Adding cache directory statistics.
@@ -73,7 +73,7 @@ public function sysMemoryStatus()
return $status;
}
- /*
+ /**
* System opcache status/details.
*
* @since 151002 Adding cache directory statistics.
diff --git a/src/includes/traits/Shared/TokenUtils.php b/src/includes/traits/Shared/TokenUtils.php
index 5a3655eb..a7035119 100644
--- a/src/includes/traits/Shared/TokenUtils.php
+++ b/src/includes/traits/Shared/TokenUtils.php
@@ -5,7 +5,7 @@
trait TokenUtils {
/*[pro strip-from="lite"]*/
- /*
+ /**
* A simple utility flag.
*
* @since 150422 Rewrite.
@@ -15,7 +15,7 @@ trait TokenUtils {
public $user_login_cookie_expired_or_invalid = false;
/*[/pro]*/
- /*
+ /**
* Current host.
*
* @since 150422 Rewrite.
@@ -63,7 +63,7 @@ public function hostToken($dashify = false, $consider_domain_mapping = false, $c
return $token;
}
- /*
+ /**
* Host for a specific blog.
*
* @since 150821 Improving multisite compat.
@@ -109,7 +109,7 @@ public function hostTokenForBlog($dashify = false, $consider_domain_mapping = fa
return $token;
}
- /*
+ /**
* Current site's base directory.
*
* @since 150422 Rewrite.
@@ -152,7 +152,7 @@ public function hostBaseToken($dashify = false, $consider_domain_mapping = false
return $token;
}
- /*
+ /**
* Current blog's sub-directory.
*
* @since 150422 Rewrite.
@@ -211,7 +211,7 @@ public function hostDirToken($dashify = false, $consider_domain_mapping = false,
return $token;
}
- /*
+ /**
* A blog's sub-directory.
*
* @since 150821 Improving multisite compat.
@@ -265,7 +265,7 @@ public function hostDirTokenForBlog($dashify = false, $consider_domain_mapping =
return $token;
}
- /*
+ /**
* Current site's base directory & current blog's sub-directory.
*
* @since 150422 Rewrite.
@@ -292,7 +292,7 @@ public function hostBaseDirTokens($dashify = false, $consider_domain_mapping = f
return ($tokens = preg_replace('/\/+/', '/', $tokens));
}
- /*
+ /**
* A site's base directory & a blog's sub-directory.
*
* @since 150821 Improving multisite compat.
@@ -317,7 +317,7 @@ public function hostBaseDirTokensForBlog($dashify = false, $consider_domain_mapp
}
/*[pro strip-from="lite"]*/
- /*
+ /**
* Produces a token based on the current user.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Shared/TrimUtils.php b/src/includes/traits/Shared/TrimUtils.php
index 4c4f1fe7..e9c74925 100644
--- a/src/includes/traits/Shared/TrimUtils.php
+++ b/src/includes/traits/Shared/TrimUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait TrimUtils {
- /*
+ /**
* Trims strings deeply.
*
* @since 150422 Rewrite.
diff --git a/src/includes/traits/Shared/UrlUtils.php b/src/includes/traits/Shared/UrlUtils.php
index 77e1b530..9989f184 100644
--- a/src/includes/traits/Shared/UrlUtils.php
+++ b/src/includes/traits/Shared/UrlUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
trait UrlUtils {
- /*
+ /**
* Parses a URL.
*
* @since 150821 Improving multisite compat.
@@ -39,7 +39,7 @@ public function parseUrl($url_uri_qsl, $component = -1)
}
}
- /*
+ /**
* Unparses a URL.
*
* @since 150821 Improving multisite compat.
@@ -93,7 +93,7 @@ public function unParseUrl(array $parts)
return $scheme.$user.$pass.$host.$port.$path.$query.$fragment;
}
- /*
+ /**
* Is the current request over SSL?
*
* @since 150422 Rewrite.
@@ -125,7 +125,7 @@ public function isSsl()
return ($is = false);
}
- /*
+ /**
* Current URL.
*
* @since 150821 Improving multisite compat.
From d83df25e79e69390e029ea05f62f675a4d641204 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 09:59:23 -0500
Subject: [PATCH 020/112] Convert to Traits: Fix spelling mistake in Trait name
See websharks/comet-cache#635
---
src/includes/traits/Plugin/WcpUrlUtils.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/includes/traits/Plugin/WcpUrlUtils.php b/src/includes/traits/Plugin/WcpUrlUtils.php
index 0ae4e774..470f1d83 100644
--- a/src/includes/traits/Plugin/WcpUrlUtils.php
+++ b/src/includes/traits/Plugin/WcpUrlUtils.php
@@ -4,7 +4,7 @@
use WebSharks\CometCache\Pro\Classes;
-trait WcpUtlUtils {
+trait WcpUrlUtils {
/**
* Automatically clears cache files for a list of custom URLs.
*
From 79c41a1dab8291e42525aa3d740631cee7014efc Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 09:59:49 -0500
Subject: [PATCH 021/112] Convert to Traits: Add `use Traits\` to Plugin and
AdvancedCache
See websharks/comet-cache#635
---
src/includes/classes/AdvancedCache.php | 32 ++++++++++++
src/includes/classes/Plugin.php | 67 ++++++++++++++++++++++++++
2 files changed, 99 insertions(+)
diff --git a/src/includes/classes/AdvancedCache.php b/src/includes/classes/AdvancedCache.php
index 50c18e7e..35ab82e1 100644
--- a/src/includes/classes/AdvancedCache.php
+++ b/src/includes/classes/AdvancedCache.php
@@ -1,6 +1,8 @@
Date: Sun, 28 Feb 2016 10:04:00 -0500
Subject: [PATCH 022/112] Convert to Traits: Convert CachePathConsts to
interface
See websharks/comet-cache#635
---
src/includes/classes/AdvancedCache.php | 2 +-
src/includes/classes/Plugin.php | 2 +-
.../interfaces/Shared/CachePathConsts.php | 141 +++++++++++++++++
.../traits/Shared/CachePathConsts.php | 142 ------------------
4 files changed, 143 insertions(+), 144 deletions(-)
create mode 100644 src/includes/interfaces/Shared/CachePathConsts.php
delete mode 100644 src/includes/traits/Shared/CachePathConsts.php
diff --git a/src/includes/classes/AdvancedCache.php b/src/includes/classes/AdvancedCache.php
index 35ab82e1..9b5e9990 100644
--- a/src/includes/classes/AdvancedCache.php
+++ b/src/includes/classes/AdvancedCache.php
@@ -10,7 +10,7 @@
*
* @since 150422 Rewrite.
*/
-class AdvancedCache extends AbsBaseAp implements Interfaces\Shared\NcDebugConsts
+class AdvancedCache extends AbsBaseAp implements Interfaces\Shared\NcDebugConsts, Interfaces\Shared\CachePathConsts
{
use Traits\Shared\BlogUtils;
use Traits\Shared\CacheDirUtils;
diff --git a/src/includes/classes/Plugin.php b/src/includes/classes/Plugin.php
index 3fe785a2..14eed4a2 100644
--- a/src/includes/classes/Plugin.php
+++ b/src/includes/classes/Plugin.php
@@ -10,7 +10,7 @@
*
* @since 150422 Rewrite.
*/
-class Plugin extends AbsBaseAp implements Interfaces\Shared\NcDebugConsts
+class Plugin extends AbsBaseAp implements Interfaces\Shared\NcDebugConsts, Interfaces\Shared\CachePathConsts
{
use Traits\Shared\BlogUtils;
use Traits\Shared\CacheDirUtils;
diff --git a/src/includes/interfaces/Shared/CachePathConsts.php b/src/includes/interfaces/Shared/CachePathConsts.php
new file mode 100644
index 00000000..6756d04f
--- /dev/null
+++ b/src/includes/interfaces/Shared/CachePathConsts.php
@@ -0,0 +1,141 @@
+
Date: Sun, 28 Feb 2016 10:06:55 -0500
Subject: [PATCH 023/112] Convert to Traits: Add $this:: to CACHE_PATH_
See websharks/comet-cache#635
---
src/includes/classes/DirStats.php | 2 +-
src/includes/classes/FeedUtils.php | 6 +-
src/includes/traits/Shared/CacheDirUtils.php | 2 +-
src/includes/traits/Shared/CachePathUtils.php | 72 +++++++++----------
4 files changed, 41 insertions(+), 41 deletions(-)
diff --git a/src/includes/classes/DirStats.php b/src/includes/classes/DirStats.php
index 8f428fe1..9a58047d 100644
--- a/src/includes/classes/DirStats.php
+++ b/src/includes/classes/DirStats.php
@@ -562,7 +562,7 @@ public function forHostCache(
foreach (array('http', 'https') as $_host_scheme) {
$_host_url = $_host_scheme.'://'.$host_token.$host_base_dir_tokens;
- $_host_cache_path_flags = CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
+ $_host_cache_path_flags = $this::CACHE_PATH_NO_PATH_INDEX | $this::CACHE_PATH_NO_QUV | $this::CACHE_PATH_NO_EXT;
$_host_cache_path = $this->plugin->buildCachePath($_host_url, '', '', $_host_cache_path_flags);
$_host_cache_dir = $this->plugin->nDirSeps($cache_dir.'/'.$_host_cache_path); // Normalize path.
$_check_disk_stats = $___considering_domain_mapping || isset($stats->disk_total_space) ? false : true;
diff --git a/src/includes/classes/FeedUtils.php b/src/includes/classes/FeedUtils.php
index 400f34d9..bec02a79 100644
--- a/src/includes/classes/FeedUtils.php
+++ b/src/includes/classes/FeedUtils.php
@@ -229,8 +229,8 @@ public function convertVariationsToHostCachePathRegexFrags(array $variations)
$regex_frags = array();
$is_multisite = is_multisite();
$can_consider_domain_mapping = $is_multisite && $this->plugin->canConsiderDomainMapping();
- $flags = CACHE_PATH_NO_SCHEME | CACHE_PATH_NO_HOST // Default flags.
- | CACHE_PATH_NO_USER | CACHE_PATH_NO_VSALT | CACHE_PATH_NO_EXT;
+ $flags = $this::CACHE_PATH_NO_SCHEME | $this::CACHE_PATH_NO_HOST // Default flags.
+ | $this::CACHE_PATH_NO_USER | $this::CACHE_PATH_NO_VSALT | $this::CACHE_PATH_NO_EXT;
// Flags: note that we DO allow for query string data in these regex fragments.
foreach ($variations as $_key => $_url) {
@@ -252,7 +252,7 @@ public function convertVariationsToHostCachePathRegexFrags(array $variations)
if (is_string($_key) && strpos($_key, '::') !== false && strpos($_url, '*') !== false) {
list($_feed_type, $_wildcard_regex) = explode('::', $_key, 2); // This regex replaces wildcards.
- $_cache_path = $this->plugin->buildCachePath($_url, '', '', $flags | CACHE_PATH_ALLOW_WILDCARDS);
+ $_cache_path = $this->plugin->buildCachePath($_url, '', '', $flags | $this::CACHE_PATH_ALLOW_WILDCARDS);
$_relative_cache_path = preg_replace('/^'.preg_quote($_host_cache_path, '/').'(?:\/|$)/i', '', $_cache_path);
$_relative_cache_path_regex = preg_replace('/\\\\\*/', $_wildcard_regex, preg_quote($_relative_cache_path, '/'));
} else {
diff --git a/src/includes/traits/Shared/CacheDirUtils.php b/src/includes/traits/Shared/CacheDirUtils.php
index 8d39c338..9f222b45 100644
--- a/src/includes/traits/Shared/CacheDirUtils.php
+++ b/src/includes/traits/Shared/CacheDirUtils.php
@@ -296,7 +296,7 @@ public function deleteFilesFromHostCacheDir(
foreach (['http', 'https'] as $_host_scheme) {
$_host_url = $_host_scheme.'://'.$host_token.$host_base_dir_tokens;
- $_host_cache_path_flags = CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
+ $_host_cache_path_flags = $this::CACHE_PATH_NO_PATH_INDEX | $this::CACHE_PATH_NO_QUV | $this::CACHE_PATH_NO_EXT;
$_host_cache_path = $this->buildCachePath($_host_url, '', '', $_host_cache_path_flags);
$_host_cache_dir = $this->nDirSeps($cache_dir.'/'.$_host_cache_path); // Normalize.
diff --git a/src/includes/traits/Shared/CachePathUtils.php b/src/includes/traits/Shared/CachePathUtils.php
index 671c516e..dfeaf7c0 100644
--- a/src/includes/traits/Shared/CachePathUtils.php
+++ b/src/includes/traits/Shared/CachePathUtils.php
@@ -13,9 +13,9 @@ trait CachePathUtils {
*
* @return string Cache-path suffix frag (regex).
*/
- public function cachePathRegexSuffixFrag($regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ public function cachePathRegexSuffixFrag($regex_suffix_frag = $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
{
- if ($regex_suffix_frag === CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG) {
+ if ($regex_suffix_frag === $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG) {
return $this->cachePathRegexDefaultSuffixFrag();
}
return (string) $regex_suffix_frag;
@@ -49,11 +49,11 @@ public function cachePathRegexDefaultSuffixFrag()
* @param string $url The input URL to convert.
* @param string $with_user_token Optional user token (if applicable).
* @param string $with_version_salt Optional version salt (if applicable).
- * @param int $flags Optional flags. A bitmask via `CACHE_PATH_*` constants.
+ * @param int $flags Optional flags. A bitmask via `$this::CACHE_PATH_*` constants.
*
* @return string The resulting `cache/path` based on the input `$url` & `$flags`.
*/
- public function buildCachePath($url, $with_user_token = '', $with_version_salt = '', $flags = CACHE_PATH_DEFAULT)
+ public function buildCachePath($url, $with_user_token = '', $with_version_salt = '', $flags = $this::CACHE_PATH_DEFAULT)
{
# Force parameter types.
@@ -69,8 +69,8 @@ public function buildCachePath($url, $with_user_token = '', $with_version_salt =
# Deal w/ domain mapping considerations.
- if ($flags & CACHE_PATH_CONSIDER_DOMAIN_MAPPING && $is_multisite && $can_consider_domain_mapping) {
- if ($flags & CACHE_PATH_REVERSE_DOMAIN_MAPPING) {
+ if ($flags & $this::CACHE_PATH_CONSIDER_DOMAIN_MAPPING && $is_multisite && $can_consider_domain_mapping) {
+ if ($flags & $this::CACHE_PATH_REVERSE_DOMAIN_MAPPING) {
$url = $this->domainMappingReverseUrlFilter($url);
} else {
$url = $this->domainMappingUrlFilter($url);
@@ -100,10 +100,10 @@ public function buildCachePath($url, $with_user_token = '', $with_version_salt =
# Build and return the cache path.
- if (!($flags & CACHE_PATH_NO_SCHEME)) {
+ if (!($flags & $this::CACHE_PATH_NO_SCHEME)) {
$cache_path .= $url_parts['scheme'].'/';
}
- if (!($flags & CACHE_PATH_NO_HOST)) {
+ if (!($flags & $this::CACHE_PATH_NO_HOST)) {
$cache_path .= $url_parts['host'].'/';
// Put multisite sub-roots into a host directory of their own.
@@ -113,7 +113,7 @@ public function buildCachePath($url, $with_user_token = '', $with_version_salt =
$cache_path = rtrim($cache_path, '/').$host_base_dir_suffix.'/';
}
}
- if (!($flags & CACHE_PATH_NO_PATH)) {
+ if (!($flags & $this::CACHE_PATH_NO_PATH)) {
if (isset($url_parts['path'][201])) {
$_path_tmp = '/'; // Initialize tmp path.
foreach (explode('/', $url_parts['path']) as $_path_component) {
@@ -135,12 +135,12 @@ public function buildCachePath($url, $with_user_token = '', $with_version_salt =
if (!empty($url_parts['path']) && strlen($url_parts['path'] = trim($url_parts['path'], '\\/'." \t\n\r\0\x0B"))) {
$cache_path .= $url_parts['path'].'/'; // Add the path as it exists.
- if (!($flags & CACHE_PATH_NO_PATH_INDEX) && $is_multisite && $is_a_multisite_base_dir_root) {
+ if (!($flags & $this::CACHE_PATH_NO_PATH_INDEX) && $is_multisite && $is_a_multisite_base_dir_root) {
// We should build an `index/` when this ends with a multisite [[/base]/child1] root.
// e.g., `http/example-com[[-base]-child1][[/base]/child1]` is a root directory.
$cache_path .= 'index/'; // Use an index suffix.
}
- } elseif (!($flags & CACHE_PATH_NO_PATH_INDEX)) {
+ } elseif (!($flags & $this::CACHE_PATH_NO_PATH_INDEX)) {
$cache_path .= 'index/';
}
}
@@ -149,18 +149,18 @@ public function buildCachePath($url, $with_user_token = '', $with_version_salt =
}
$cache_path = str_replace('.', '-', strtolower($cache_path));
- if (!($flags & CACHE_PATH_NO_QUV)) {
- if (!($flags & CACHE_PATH_NO_QUERY)) {
+ if (!($flags & $this::CACHE_PATH_NO_QUV)) {
+ if (!($flags & $this::CACHE_PATH_NO_QUERY)) {
if (isset($url_parts['query']) && $url_parts['query'] !== '') {
$cache_path = rtrim($cache_path, '/').'.q/'.md5($url_parts['query']).'/';
}
}
- if (!($flags & CACHE_PATH_NO_USER)) {
+ if (!($flags & $this::CACHE_PATH_NO_USER)) {
if ($with_user_token !== '') {
$cache_path = rtrim($cache_path, '/').'.u/'.str_replace(['/', '\\'], '-', $with_user_token).'/';
}
}
- if (!($flags & CACHE_PATH_NO_VSALT)) {
+ if (!($flags & $this::CACHE_PATH_NO_VSALT)) {
if ($with_version_salt !== '') {
$cache_path = rtrim($cache_path, '/').'.v/'.str_replace(['/', '\\'], '-', $with_version_salt).'/';
}
@@ -168,14 +168,14 @@ public function buildCachePath($url, $with_user_token = '', $with_version_salt =
}
$cache_path = trim(preg_replace(['/\/+/', '/\.+/'], ['/', '.'], $cache_path), '/');
- if ($flags & CACHE_PATH_ALLOW_WD_REGEX) {
+ if ($flags & $this::CACHE_PATH_ALLOW_WD_REGEX) {
$cache_path = preg_replace('/[^a-z0-9\/.*\^$]/i', '-', $cache_path);
- } elseif ($flags & CACHE_PATH_ALLOW_WILDCARDS) {
+ } elseif ($flags & $this::CACHE_PATH_ALLOW_WILDCARDS) {
$cache_path = preg_replace('/[^a-z0-9\/.*]/i', '-', $cache_path);
} else {
$cache_path = preg_replace('/[^a-z0-9\/.]/i', '-', $cache_path);
}
- if (!($flags & CACHE_PATH_NO_EXT)) {
+ if (!($flags & $this::CACHE_PATH_NO_EXT)) {
$cache_path .= '.html';
}
return $cache_path;
@@ -193,19 +193,19 @@ public function buildCachePath($url, $with_user_token = '', $with_version_salt =
* @param string $regex_suffix_frag Regex fragment to come after the `$regex_frag`.
* Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
* Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
- * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
+ * See also: {@link $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
*
* @return string Regex pattern for a call to `deleteFilesFromCacheDir()`.
*/
- public function buildCachePathRegex($url, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ public function buildCachePathRegex($url, $regex_suffix_frag = $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
{
$url = trim((string) $url);
$regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
$cache_path_regex = ''; // Initialize regex.
if ($url) {
- $flags = CACHE_PATH_NO_SCHEME // Scheme added below.
- | CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
+ $flags = $this::CACHE_PATH_NO_SCHEME // Scheme added below.
+ | $this::CACHE_PATH_NO_PATH_INDEX | $this::CACHE_PATH_NO_QUV | $this::CACHE_PATH_NO_EXT;
$cache_path = $this->buildCachePath($url, '', '', $flags); // Without the scheme.
$cache_path_regex = isset($cache_path[0]) ? '\/https?\/'.preg_quote($cache_path, '/') : '';
}
@@ -224,11 +224,11 @@ public function buildCachePathRegex($url, $regex_suffix_frag = CACHE_PATH_REGEX_
* @param string $regex_suffix_frag Regex fragment to come after the relative cache/path regex frag.
* Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
* Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
- * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
+ * See also: {@link $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
*
* @return string Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
*/
- public function buildHostCachePathRegex($url, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ public function buildHostCachePathRegex($url, $regex_suffix_frag = $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
{
$url = trim((string) $url);
$regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
@@ -242,8 +242,8 @@ public function buildHostCachePathRegex($url, $regex_suffix_frag = CACHE_PATH_RE
$is_url_domain_mapped = $url && $this->domainMappingBlogId($url);
}
if ($url && ($url_parts = $this->parseUrl($url)) && !empty($url_parts['host'])) {
- $flags = CACHE_PATH_NO_SCHEME | CACHE_PATH_NO_HOST
- | CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
+ $flags = $this::CACHE_PATH_NO_SCHEME | $this::CACHE_PATH_NO_HOST
+ | $this::CACHE_PATH_NO_PATH_INDEX | $this::CACHE_PATH_NO_QUV | $this::CACHE_PATH_NO_EXT;
$host_base_dir_tokens = $this->hostBaseDirTokens(false, $is_url_domain_mapped, !empty($url_parts['path']) ? $url_parts['path'] : '/');
$host_url = rtrim('http://'.$url_parts['host'].$host_base_dir_tokens, '/');
@@ -274,19 +274,19 @@ public function buildHostCachePathRegex($url, $regex_suffix_frag = CACHE_PATH_RE
* @param string $regex_suffix_frag Regex fragment to come after the `$regex_frag`.
* Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
* Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
- * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
+ * See also: {@link $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
*
* @return string Regex pattern for a call to `deleteFilesFromCacheDir()`.
*/
- public function buildCachePathRegexFromWcUrl($url, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ public function buildCachePathRegexFromWcUrl($url, $regex_suffix_frag = $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
{
$url = trim((string) $url, '^$');
$regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
$cache_path_regex = ''; // Initialize regex.
if ($url) { // After `^$` trimming above.
- $flags = CACHE_PATH_ALLOW_WILDCARDS | CACHE_PATH_NO_SCHEME
- | CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
+ $flags = $this::CACHE_PATH_ALLOW_WILDCARDS | $this::CACHE_PATH_NO_SCHEME
+ | $this::CACHE_PATH_NO_PATH_INDEX | $this::CACHE_PATH_NO_QUV | $this::CACHE_PATH_NO_EXT;
$cache_path = $this->buildCachePath($url, '', '', $flags); // Without the scheme.
$cache_path_regex = isset($cache_path[0]) ? '\/https?\/'.$this->wdRegexToActualRegexFrag($cache_path) : '';
}
@@ -304,18 +304,18 @@ public function buildCachePathRegexFromWcUrl($url, $regex_suffix_frag = CACHE_PA
* @param string $regex_suffix_frag Regex fragment to come after each relative cache/path.
* Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
* Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
- * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
+ * See also: {@link $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
*
* @return string Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
*/
- public function buildHostCachePathRegexFragsFromWcUris($uris, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ public function buildHostCachePathRegexFragsFromWcUris($uris, $regex_suffix_frag = $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
{
$uris = trim((string) $uris);
$regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
$_this = $this; // Reference for the closure below.
- $flags = CACHE_PATH_ALLOW_WILDCARDS | CACHE_PATH_NO_SCHEME | CACHE_PATH_NO_HOST
- | CACHE_PATH_NO_PATH_INDEX | CACHE_PATH_NO_QUV | CACHE_PATH_NO_EXT;
+ $flags = $this::CACHE_PATH_ALLOW_WILDCARDS | $this::CACHE_PATH_NO_SCHEME | $this::CACHE_PATH_NO_HOST
+ | $this::CACHE_PATH_NO_PATH_INDEX | $this::CACHE_PATH_NO_QUV | $this::CACHE_PATH_NO_EXT;
$host = 'doesnt-matter.foo.bar';
$host_url = rtrim('http://'.$host, '/');
@@ -349,11 +349,11 @@ public function buildHostCachePathRegexFragsFromWcUris($uris, $regex_suffix_frag
* @param string $regex_suffix_frag Regex fragment to come after the `$regex_frag`.
* Defaults to: `(?:\/index)?(?:\.|\/(?:page\/[0-9]+|comment\-page\-[0-9]+)[.\/])`.
* Note: this should NOT have delimiters; i.e. do NOT start or end with `/`.
- * See also: {@link CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
+ * See also: {@link $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG}.
*
* @return string Regex pattern for a call to `deleteFilesFromCacheDir()`.
*/
- public function assembleCachePathRegex($regex_frag, $regex_suffix_frag = CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ public function assembleCachePathRegex($regex_frag, $regex_suffix_frag = $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
{
$regex_frag = (string) $regex_frag;
$regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
From 70da555f2303c005e99317bb4b32c456058998ef Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 10:20:47 -0500
Subject: [PATCH 024/112] Convert to Traits: Remove Closure setup from
constructors
See websharks/comet-cache#635
---
src/includes/classes/AbsBaseAp.php | 10 ----------
src/includes/classes/AdvancedCache.php | 10 ----------
src/includes/classes/Plugin.php | 10 ----------
3 files changed, 30 deletions(-)
diff --git a/src/includes/classes/AbsBaseAp.php b/src/includes/classes/AbsBaseAp.php
index 4a5ee3a0..825257bb 100644
--- a/src/includes/classes/AbsBaseAp.php
+++ b/src/includes/classes/AbsBaseAp.php
@@ -16,16 +16,6 @@ abstract class AbsBaseAp extends AbsBase
public function __construct()
{
parent::__construct();
-
- $closures_dir = dirname(dirname(__FILE__)).'/closures/Shared';
- $self = $this; // Reference for closures.
-
- foreach (scandir($closures_dir) as $_closure) {
- if (substr($_closure, -4) === '.php') {
- require $closures_dir.'/'.$_closure;
- }
- }
- unset($_closure); // Housekeeping.
}
/**
diff --git a/src/includes/classes/AdvancedCache.php b/src/includes/classes/AdvancedCache.php
index 9b5e9990..fe9d6259 100644
--- a/src/includes/classes/AdvancedCache.php
+++ b/src/includes/classes/AdvancedCache.php
@@ -69,16 +69,6 @@ public function __construct()
{
parent::__construct();
- $closures_dir = dirname(dirname(__FILE__)).'/closures/Ac';
- $self = $this; // Reference for closures.
-
- foreach (scandir($closures_dir) as $_closure) {
- if (substr($_closure, -4) === '.php') {
- require $closures_dir.'/'.$_closure;
- }
- }
- unset($_closure); // Housekeeping.
-
if (!defined('WP_CACHE') || !WP_CACHE || !COMET_CACHE_ENABLE) {
return; // Not enabled.
}
diff --git a/src/includes/classes/Plugin.php b/src/includes/classes/Plugin.php
index 14eed4a2..da929379 100644
--- a/src/includes/classes/Plugin.php
+++ b/src/includes/classes/Plugin.php
@@ -213,17 +213,7 @@ public function __construct($enable_hooks = true)
{
parent::__construct();
- $closures_dir = dirname(dirname(__FILE__)).'/closures/Plugin';
- $self = $this; // Reference for closures.
-
- foreach (scandir($closures_dir) as $_closure) {
- if (substr($_closure, -4) === '.php') {
- require $closures_dir.'/'.$_closure;
- }
- }
- unset($_closure); // Housekeeping.
/* -------------------------------------------------------------- */
-
if (!($this->enable_hooks = (boolean) $enable_hooks)) {
return; // Stop here; construct without hooks.
}
From 506b970b6dbf8e20c64bc7cfe74dd100e1ed40ef Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 10:28:17 -0500
Subject: [PATCH 025/112] Convert to Traits: Convert `new ClassName` to `new
Classes\ClassName`
See websharks/comet-cache#635
---
src/includes/classes/MenuPage.php | 8 +++++---
src/includes/classes/Plugin.php | 4 +++-
src/includes/plugin.php | 6 ++++--
src/includes/uninstall.php | 6 ++++--
4 files changed, 16 insertions(+), 8 deletions(-)
diff --git a/src/includes/classes/MenuPage.php b/src/includes/classes/MenuPage.php
index 9299c59a..361905df 100644
--- a/src/includes/classes/MenuPage.php
+++ b/src/includes/classes/MenuPage.php
@@ -1,6 +1,8 @@
options['enable'] && $this->options['cdn_enable']) {
add_action('upgrader_process_complete', array($this, 'bumpCdnInvalidationCounter'), 10, 0);
if (!is_admin()) { // Don't even bother in the admin area.
- new CdnFilters(); // Setup CDN filters.
+ new Classes\CdnFilters(); // Setup CDN filters.
}
}
/*[/pro]*/
diff --git a/src/includes/plugin.php b/src/includes/plugin.php
index ecf15d66..54681bef 100644
--- a/src/includes/plugin.php
+++ b/src/includes/plugin.php
@@ -6,13 +6,15 @@
*/
namespace WebSharks\CometCache\Pro;
+use WebSharks\CometCache\Pro\Classes;
+
if (!defined('WPINC')) {
exit('Do NOT access this file directly: '.basename(__FILE__));
}
require_once dirname(__FILE__).'/stub.php';
-if (!Conflicts::check()) {
- $GLOBALS[GLOBAL_NS] = new Plugin();
+if (!Classes\Conflicts::check()) {
+ $GLOBALS[GLOBAL_NS] = new Classes\Plugin();
$GLOBALS['zencache'] = $GLOBALS[GLOBAL_NS]; // Back compat.
$GLOBALS['quick_cache'] = $GLOBALS[GLOBAL_NS]; // Back compat.
diff --git a/src/includes/uninstall.php b/src/includes/uninstall.php
index 12d11c93..7fb5304d 100644
--- a/src/includes/uninstall.php
+++ b/src/includes/uninstall.php
@@ -6,6 +6,8 @@
*/
namespace WebSharks\CometCache\Pro;
+use WebSharks\CometCache\Pro\Classes;
+
if (!defined('WPINC')) {
exit('Do NOT access this file directly: '.basename(__FILE__));
}
@@ -13,7 +15,7 @@
$GLOBALS[GLOBAL_NS.'_uninstalling'] = true; // Needs to be set before calling Conflicts class
-if (!Conflicts::check()) {
- $GLOBALS[GLOBAL_NS] = new Plugin(false);
+if (!Classes\Conflicts::check()) {
+ $GLOBALS[GLOBAL_NS] = new Classes\Plugin(false);
$GLOBALS[GLOBAL_NS]->uninstall();
}
From d8e4b06a346096becac306a8372bc26879b6ab4f Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 10:30:48 -0500
Subject: [PATCH 026/112] Convert to Traits: Move Shared Traits to AbsBaseAp
See websharks/comet-cache#635
---
src/includes/classes/AbsBaseAp.php | 23 +++++++++++++++++++++++
src/includes/classes/AdvancedCache.php | 21 ---------------------
src/includes/classes/Plugin.php | 21 ---------------------
3 files changed, 23 insertions(+), 42 deletions(-)
diff --git a/src/includes/classes/AbsBaseAp.php b/src/includes/classes/AbsBaseAp.php
index 825257bb..8a008015 100644
--- a/src/includes/classes/AbsBaseAp.php
+++ b/src/includes/classes/AbsBaseAp.php
@@ -1,6 +1,8 @@
Date: Sun, 28 Feb 2016 10:49:59 -0500
Subject: [PATCH 027/112] Convert to Traits: Use self::CACHE_PATH_* in function
definition
See websharks/comet-cache#635
---
src/includes/traits/Shared/CachePathUtils.php | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/src/includes/traits/Shared/CachePathUtils.php b/src/includes/traits/Shared/CachePathUtils.php
index dfeaf7c0..9d97c441 100644
--- a/src/includes/traits/Shared/CachePathUtils.php
+++ b/src/includes/traits/Shared/CachePathUtils.php
@@ -13,7 +13,7 @@ trait CachePathUtils {
*
* @return string Cache-path suffix frag (regex).
*/
- public function cachePathRegexSuffixFrag($regex_suffix_frag = $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ public function cachePathRegexSuffixFrag($regex_suffix_frag = self::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
{
if ($regex_suffix_frag === $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG) {
return $this->cachePathRegexDefaultSuffixFrag();
@@ -53,7 +53,7 @@ public function cachePathRegexDefaultSuffixFrag()
*
* @return string The resulting `cache/path` based on the input `$url` & `$flags`.
*/
- public function buildCachePath($url, $with_user_token = '', $with_version_salt = '', $flags = $this::CACHE_PATH_DEFAULT)
+ public function buildCachePath($url, $with_user_token = '', $with_version_salt = '', $flags = self::CACHE_PATH_DEFAULT)
{
# Force parameter types.
@@ -197,7 +197,7 @@ public function buildCachePath($url, $with_user_token = '', $with_version_salt =
*
* @return string Regex pattern for a call to `deleteFilesFromCacheDir()`.
*/
- public function buildCachePathRegex($url, $regex_suffix_frag = $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ public function buildCachePathRegex($url, $regex_suffix_frag = self::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
{
$url = trim((string) $url);
$regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
@@ -228,7 +228,7 @@ public function buildCachePathRegex($url, $regex_suffix_frag = $this::CACHE_PATH
*
* @return string Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
*/
- public function buildHostCachePathRegex($url, $regex_suffix_frag = $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ public function buildHostCachePathRegex($url, $regex_suffix_frag = self::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
{
$url = trim((string) $url);
$regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
@@ -278,7 +278,7 @@ public function buildHostCachePathRegex($url, $regex_suffix_frag = $this::CACHE_
*
* @return string Regex pattern for a call to `deleteFilesFromCacheDir()`.
*/
- public function buildCachePathRegexFromWcUrl($url, $regex_suffix_frag = $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ public function buildCachePathRegexFromWcUrl($url, $regex_suffix_frag = self::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
{
$url = trim((string) $url, '^$');
$regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
@@ -308,7 +308,7 @@ public function buildCachePathRegexFromWcUrl($url, $regex_suffix_frag = $this::C
*
* @return string Regex pattern for a call to `deleteFilesFromHostCacheDir()`.
*/
- public function buildHostCachePathRegexFragsFromWcUris($uris, $regex_suffix_frag = $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ public function buildHostCachePathRegexFragsFromWcUris($uris, $regex_suffix_frag = self::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
{
$uris = trim((string) $uris);
$regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
@@ -353,7 +353,7 @@ public function buildHostCachePathRegexFragsFromWcUris($uris, $regex_suffix_frag
*
* @return string Regex pattern for a call to `deleteFilesFromCacheDir()`.
*/
- public function assembleCachePathRegex($regex_frag, $regex_suffix_frag = $this::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
+ public function assembleCachePathRegex($regex_frag, $regex_suffix_frag = self::CACHE_PATH_REGEX_DEFAULT_SUFFIX_FRAG)
{
$regex_frag = (string) $regex_frag;
$regex_suffix_frag = $this->cachePathRegexSuffixFrag($regex_suffix_frag);
From 76952d09ed3f8e9e4a34a9f394ac533080e014d2 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 10:55:17 -0500
Subject: [PATCH 028/112] Convert to Traits: Add Classes\\ to back compat. in
stub.php
See websharks/comet-cache#635
---
src/includes/stub.php | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/src/includes/stub.php b/src/includes/stub.php
index 8a41732f..8afe25dc 100644
--- a/src/includes/stub.php
+++ b/src/includes/stub.php
@@ -30,9 +30,9 @@
unset(${__FILE__}); // Housekeeping.
// Fixes PHP Fatal error with upgrades from v160211
-class_alias(__NAMESPACE__.'\\AdvCacheBackCompat', 'WebSharks\\Comet_Cache\\AdvCacheBackCompat');
-class_alias(__NAMESPACE__.'\\AdvancedCache', 'WebSharks\\Comet_Cache\\AdvancedCache');
+class_alias(__NAMESPACE__.'\\Classes\\AdvCacheBackCompat', 'WebSharks\\Comet_Cache\\AdvCacheBackCompat');
+class_alias(__NAMESPACE__.'\\Classes\\AdvancedCache', 'WebSharks\\Comet_Cache\\AdvancedCache');
/*[pro strip-from="lite"]*/
-class_alias(__NAMESPACE__.'\\AdvCacheBackCompat', 'WebSharks\\Comet_Cache\\Pro\\AdvCacheBackCompat');
-class_alias(__NAMESPACE__.'\\AdvancedCache', 'WebSharks\\Comet_Cache\\Pro\\AdvancedCache');
+class_alias(__NAMESPACE__.'\\Classes\\AdvCacheBackCompat', 'WebSharks\\Comet_Cache\\Pro\\AdvCacheBackCompat');
+class_alias(__NAMESPACE__.'\\Classes\\AdvancedCache', 'WebSharks\\Comet_Cache\\Pro\\AdvancedCache');
/*[/pro]*/
From 2c605562086694969bb2af37c87c97e1252424df Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 14:07:37 -0500
Subject: [PATCH 029/112] Convert to Traits: Define constants in each
sub-namespace
See websharks/comet-cache#635
---
src/includes/stub.php | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/src/includes/stub.php b/src/includes/stub.php
index 8afe25dc..ec96b653 100644
--- a/src/includes/stub.php
+++ b/src/includes/stub.php
@@ -27,6 +27,17 @@
define(__NAMESPACE__.'\\PLUGIN_FILE', ${__FILE__}['plugin']);
define(__NAMESPACE__.'\\IS_PRO', ${__FILE__}['is_pro']);
+foreach (['Classes', 'Traits\\Shared', 'Traits\\Ac', 'Traits\\Plugin', 'Interfaces\\Shared'] as ${__FILE__}['_sub_namespace']) {
+ define(__NAMESPACE__.'\\'.${__FILE__}['_sub_namespace'].'\\SHORT_NAME', SHORT_NAME);
+ define(__NAMESPACE__.'\\'.${__FILE__}['_sub_namespace'].'\\NAME', NAME);
+ define(__NAMESPACE__.'\\'.${__FILE__}['_sub_namespace'].'\\DOMAIN', DOMAIN);
+ define(__NAMESPACE__.'\\'.${__FILE__}['_sub_namespace'].'\\GLOBAL_NS', GLOBAL_NS);
+ define(__NAMESPACE__.'\\'.${__FILE__}['_sub_namespace'].'\\SLUG_TD', SLUG_TD);
+ define(__NAMESPACE__.'\\'.${__FILE__}['_sub_namespace'].'\\VERSION', VERSION);
+ define(__NAMESPACE__.'\\'.${__FILE__}['_sub_namespace'].'\\PLUGIN_FILE', PLUGIN_FILE);
+ define(__NAMESPACE__.'\\'.${__FILE__}['_sub_namespace'].'\\IS_PRO', IS_PRO);
+}
+
unset(${__FILE__}); // Housekeeping.
// Fixes PHP Fatal error with upgrades from v160211
From 03677c0e7c357a752fed8469810eeee30ba41431 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Sun, 28 Feb 2016 15:39:39 -0500
Subject: [PATCH 030/112] Remove duplicate newsletter links from Pro Updater
page.
---
src/includes/classes/MenuPageProUpdater.php | 2 --
1 file changed, 2 deletions(-)
diff --git a/src/includes/classes/MenuPageProUpdater.php b/src/includes/classes/MenuPageProUpdater.php
index bc4893f2..7afed579 100644
--- a/src/includes/classes/MenuPageProUpdater.php
+++ b/src/includes/classes/MenuPageProUpdater.php
@@ -35,8 +35,6 @@ public function __construct()
echo ' '."\n";
diff --git a/src/includes/classes/VsUpgrades.php b/src/includes/classes/VsUpgrades.php
index 608b56d3..18cf54fd 100644
--- a/src/includes/classes/VsUpgrades.php
+++ b/src/includes/classes/VsUpgrades.php
@@ -140,7 +140,7 @@ protected function fromLte151114()
return; // Template blocks are already gone.
}
if ($htaccess = $this->plugin->readHtaccessFile($htaccess_file)) {
- if (is_dir($templates_dir = dirname(dirname(__FILE__)).'/templates/htaccess/back-compat')) {
+ if (is_dir($templates_dir = dirname(__DIR__).'/templates/htaccess/back-compat')) {
$htaccess['file_contents'] = str_replace(file_get_contents($templates_dir.'/v151114.txt'), '', $htaccess['file_contents']);
$htaccess['file_contents'] = str_replace(file_get_contents($templates_dir.'/v151114-2.txt'), '', $htaccess['file_contents']);
$htaccess['file_contents'] = trim($htaccess['file_contents']);
diff --git a/src/includes/plugin.php b/src/includes/plugin.php
index 54681bef..d5f60024 100644
--- a/src/includes/plugin.php
+++ b/src/includes/plugin.php
@@ -11,7 +11,7 @@
if (!defined('WPINC')) {
exit('Do NOT access this file directly: '.basename(__FILE__));
}
-require_once dirname(__FILE__).'/stub.php';
+require_once __DIR__.'/stub.php';
if (!Classes\Conflicts::check()) {
$GLOBALS[GLOBAL_NS] = new Classes\Plugin();
@@ -19,6 +19,6 @@
$GLOBALS['quick_cache'] = $GLOBALS[GLOBAL_NS]; // Back compat.
add_action('plugins_loaded', function() {
- require_once dirname(__FILE__).'/api.php';
+ require_once __DIR__.'/api.php';
});
}
diff --git a/src/includes/stub.php b/src/includes/stub.php
index ec96b653..00965802 100644
--- a/src/includes/stub.php
+++ b/src/includes/stub.php
@@ -9,11 +9,11 @@
if (!defined('WPINC')) {
exit('Do NOT access this file directly: '.basename(__FILE__));
}
-require_once dirname(dirname(__FILE__)).'/vendor/autoload.php';
-require_once dirname(__FILE__).'/functions/i18n-utils.php';
+require_once dirname(__DIR__).'/vendor/autoload.php';
+require_once __DIR__.'/functions/i18n-utils.php';
${__FILE__}['version'] = '160227'; //version//
-${__FILE__}['plugin'] = dirname(dirname(dirname(__FILE__)));
+${__FILE__}['plugin'] = dirname(dirname(__DIR__));
${__FILE__}['plugin'] .= '/'.basename(${__FILE__}['plugin']).'.php';
${__FILE__}['ns_path'] = str_replace('\\', '/', __NAMESPACE__); // To dir/path.
${__FILE__}['is_pro'] = strtolower(basename(${__FILE__}['ns_path'])) === 'pro';
diff --git a/src/includes/traits/Plugin/HtaccessUtils.php b/src/includes/traits/Plugin/HtaccessUtils.php
index 53b465be..c6f9afa0 100644
--- a/src/includes/traits/Plugin/HtaccessUtils.php
+++ b/src/includes/traits/Plugin/HtaccessUtils.php
@@ -57,7 +57,7 @@ public function addWpHtaccess()
}
$template_blocks = ''; // Initialize.
- if (is_dir($templates_dir = dirname(dirname(dirname(__FILE__))).'/templates/htaccess')) {
+ if (is_dir($templates_dir = dirname(dirname(__DIR__)).'/templates/htaccess')) {
foreach (scandir($templates_dir) as $_template_file) {
switch ($_template_file) {
/*[pro strip-from="lite"]*/
diff --git a/src/includes/traits/Plugin/InstallUtils.php b/src/includes/traits/Plugin/InstallUtils.php
index a83e2ddd..86b52ea6 100644
--- a/src/includes/traits/Plugin/InstallUtils.php
+++ b/src/includes/traits/Plugin/InstallUtils.php
@@ -277,7 +277,7 @@ public function addAdvancedCache()
$cache_dir = $this->cacheDir();
$advanced_cache_file = WP_CONTENT_DIR.'/advanced-cache.php';
$advanced_cache_check_file = $cache_dir.'/'.strtolower(SHORT_NAME).'-advanced-cache';
- $advanced_cache_template = dirname(dirname(dirname(__FILE__))).'/templates/advanced-cache.txt';
+ $advanced_cache_template = dirname(dirname(__DIR__)).'/templates/advanced-cache.txt';
if (is_file($advanced_cache_file) && !is_writable($advanced_cache_file)) {
return false; // Not possible to create.
diff --git a/src/includes/traits/Plugin/MenuPageUtils.php b/src/includes/traits/Plugin/MenuPageUtils.php
index c37accfc..056f29f4 100644
--- a/src/includes/traits/Plugin/MenuPageUtils.php
+++ b/src/includes/traits/Plugin/MenuPageUtils.php
@@ -74,7 +74,7 @@ public function addNetworkMenuPages()
if (!is_multisite()) {
return; // Not applicable.
}
- $icon = file_get_contents(dirname(dirname(dirname(dirname(__FILE__)))).'/client-s/images/inline-icon.svg');
+ $icon = file_get_contents(dirname(dirname(dirname(__DIR__))).'/client-s/images/inline-icon.svg');
$icon = 'data:image/svg+xml;base64,'.base64_encode($this->colorSvgMenuIcon($icon));
add_menu_page(NAME.(IS_PRO ? ' Pro' : ''), NAME.(IS_PRO ? ' Pro' : ''), $this->network_cap, GLOBAL_NS, [$this, 'menuPageOptions'], $icon);
@@ -103,7 +103,7 @@ public function addMenuPages()
if (is_multisite()) {
return; // Multisite networks MUST use network admin area.
}
- $icon = file_get_contents(dirname(dirname(dirname(dirname(__FILE__)))).'/client-s/images/inline-icon.svg');
+ $icon = file_get_contents(dirname(dirname(dirname(__DIR__))).'/client-s/images/inline-icon.svg');
$icon = 'data:image/svg+xml;base64,'.base64_encode($this->colorSvgMenuIcon($icon));
add_menu_page(NAME.(IS_PRO ? ' Pro' : ''), NAME.(IS_PRO ? ' Pro' : ''), $this->cap, GLOBAL_NS, [$this, 'menuPageOptions'], $icon);
diff --git a/src/includes/uninstall.php b/src/includes/uninstall.php
index 7fb5304d..0a6eca3e 100644
--- a/src/includes/uninstall.php
+++ b/src/includes/uninstall.php
@@ -11,7 +11,7 @@
if (!defined('WPINC')) {
exit('Do NOT access this file directly: '.basename(__FILE__));
}
-require_once dirname(__FILE__).'/stub.php';
+require_once __DIR__.'/stub.php';
$GLOBALS[GLOBAL_NS.'_uninstalling'] = true; // Needs to be set before calling Conflicts class
diff --git a/uninstall.php b/uninstall.php
index 703bf49f..1e4ab23b 100644
--- a/uninstall.php
+++ b/uninstall.php
@@ -3,6 +3,6 @@
exit('Do NOT access this file directly: '.basename(__FILE__));
}
$GLOBALS['wp_php_rv'] = '5.4'; //php-required-version//
-if (require(dirname(__FILE__).'/src/vendor/websharks/wp-php-rv/src/includes/check.php')) {
- require_once dirname(__FILE__).'/src/includes/uninstall.php';
+if (require(__DIR__.'/src/vendor/websharks/wp-php-rv/src/includes/check.php')) {
+ require_once __DIR__.'/src/includes/uninstall.php';
}
From be95571b334393d5b066d610e1e48ce02266e4a6 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Tue, 1 Mar 2016 10:32:02 -0500
Subject: [PATCH 039/112] Convert to Traits: Add `.build.php` script to
generate Traits use-list
See websharks/comet-cache#635
---
src/includes/traits/Ac/.build.php | 16 ++++++++++++++++
src/includes/traits/Plugin/.build.php | 16 ++++++++++++++++
src/includes/traits/Shared/.build.php | 16 ++++++++++++++++
3 files changed, 48 insertions(+)
create mode 100644 src/includes/traits/Ac/.build.php
create mode 100644 src/includes/traits/Plugin/.build.php
create mode 100644 src/includes/traits/Shared/.build.php
diff --git a/src/includes/traits/Ac/.build.php b/src/includes/traits/Ac/.build.php
new file mode 100644
index 00000000..2fb15131
--- /dev/null
+++ b/src/includes/traits/Ac/.build.php
@@ -0,0 +1,16 @@
+
Date: Tue, 1 Mar 2016 10:34:16 -0500
Subject: [PATCH 040/112] Convert to Traits: Fix docs in `.build.php`
See websharks/comet-cache#635
---
src/includes/traits/Ac/.build.php | 2 +-
src/includes/traits/Shared/.build.php | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/includes/traits/Ac/.build.php b/src/includes/traits/Ac/.build.php
index 2fb15131..56283255 100644
--- a/src/includes/traits/Ac/.build.php
+++ b/src/includes/traits/Ac/.build.php
@@ -3,7 +3,7 @@
* Generate use-list for Trait files in current directory
*
* When run inside a directory called `Plugin/`, with a PHP file inside `Plugin/` called `ActionUtils.php`,
- * this script will generate `use Traits\Plugin\ActionUtils`.
+ * this script will generate `use Traits\Plugin\ActionUtils;`.
*/
if ($_handle = opendir(__DIR__)) {
while (false !== ($_file = readdir($_handle))) {
diff --git a/src/includes/traits/Shared/.build.php b/src/includes/traits/Shared/.build.php
index 2fb15131..56283255 100644
--- a/src/includes/traits/Shared/.build.php
+++ b/src/includes/traits/Shared/.build.php
@@ -3,7 +3,7 @@
* Generate use-list for Trait files in current directory
*
* When run inside a directory called `Plugin/`, with a PHP file inside `Plugin/` called `ActionUtils.php`,
- * this script will generate `use Traits\Plugin\ActionUtils`.
+ * this script will generate `use Traits\Plugin\ActionUtils;`.
*/
if ($_handle = opendir(__DIR__)) {
while (false !== ($_file = readdir($_handle))) {
From b16561e24562759d8dbdd7f023a28c04bc20f1a6 Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Wed, 2 Mar 2016 08:57:49 -0500
Subject: [PATCH 041/112] Convert to Traits: Add TODO reminder in `.build.php`
See websharks/comet-cache#635
---
src/includes/traits/Ac/.build.php | 2 ++
src/includes/traits/Plugin/.build.php | 2 ++
src/includes/traits/Shared/.build.php | 2 ++
3 files changed, 6 insertions(+)
diff --git a/src/includes/traits/Ac/.build.php b/src/includes/traits/Ac/.build.php
index 56283255..68a6498f 100644
--- a/src/includes/traits/Ac/.build.php
+++ b/src/includes/traits/Ac/.build.php
@@ -4,6 +4,8 @@
*
* When run inside a directory called `Plugin/`, with a PHP file inside `Plugin/` called `ActionUtils.php`,
* this script will generate `use Traits\Plugin\ActionUtils;`.
+ *
+ * @TODO Automatically insert this list into appropriate PHP files.
*/
if ($_handle = opendir(__DIR__)) {
while (false !== ($_file = readdir($_handle))) {
diff --git a/src/includes/traits/Plugin/.build.php b/src/includes/traits/Plugin/.build.php
index 56283255..68a6498f 100644
--- a/src/includes/traits/Plugin/.build.php
+++ b/src/includes/traits/Plugin/.build.php
@@ -4,6 +4,8 @@
*
* When run inside a directory called `Plugin/`, with a PHP file inside `Plugin/` called `ActionUtils.php`,
* this script will generate `use Traits\Plugin\ActionUtils;`.
+ *
+ * @TODO Automatically insert this list into appropriate PHP files.
*/
if ($_handle = opendir(__DIR__)) {
while (false !== ($_file = readdir($_handle))) {
diff --git a/src/includes/traits/Shared/.build.php b/src/includes/traits/Shared/.build.php
index 56283255..68a6498f 100644
--- a/src/includes/traits/Shared/.build.php
+++ b/src/includes/traits/Shared/.build.php
@@ -4,6 +4,8 @@
*
* When run inside a directory called `Plugin/`, with a PHP file inside `Plugin/` called `ActionUtils.php`,
* this script will generate `use Traits\Plugin\ActionUtils;`.
+ *
+ * @TODO Automatically insert this list into appropriate PHP files.
*/
if ($_handle = opendir(__DIR__)) {
while (false !== ($_file = readdir($_handle))) {
From aaed2d5caaf3760111fa1a4ace4b23508cbf753b Mon Sep 17 00:00:00 2001
From: Raam Dev
Date: Wed, 2 Mar 2016 10:33:00 -0500
Subject: [PATCH 042/112] Reformat with PHP CS Fixer.
See websharks/comet-cache#635
---
plugin.php | 3 +-
src/includes/classes/AbsBase.php | 16 +-
src/includes/classes/AbsBaseAp.php | 1 -
src/includes/classes/Actions.php | 60 +++----
src/includes/classes/AdvCacheBackCompat.php | 6 +-
src/includes/classes/ApiBase.php | 1 +
src/includes/classes/AutoCache.php | 17 +-
src/includes/classes/CdnFilters.php | 62 ++++---
src/includes/classes/Conflicts.php | 16 +-
src/includes/classes/DirStats.php | 78 +++++----
src/includes/classes/FeedUtils.php | 22 +--
src/includes/classes/MenuPageOptions.php | 18 +-
src/includes/classes/MenuPageProUpdater.php | 7 +-
src/includes/classes/MenuPageStats.php | 5 +-
src/includes/classes/Plugin.php | 159 +++++++++---------
src/includes/classes/VsUpgrades.php | 5 +-
src/includes/functions/wp-cache-postload.php | 2 +-
.../interfaces/Shared/CachePathConsts.php | 5 +-
.../interfaces/Shared/NcDebugConsts.php | 5 +-
src/includes/plugin.php | 6 +-
src/includes/traits/Ac/AbortUtils.php | 3 +-
src/includes/traits/Ac/AcPluginUtils.php | 3 +-
src/includes/traits/Ac/BrowserUtils.php | 11 +-
src/includes/traits/Ac/HtmlCUtils.php | 3 +-
src/includes/traits/Ac/NcDebugUtils.php | 3 +-
src/includes/traits/Ac/ObUtils.php | 6 +-
src/includes/traits/Ac/PostloadUtils.php | 9 +-
src/includes/traits/Ac/ShutdownUtils.php | 3 +-
src/includes/traits/Plugin/ActionUtils.php | 3 +-
src/includes/traits/Plugin/AdminBarUtils.php | 9 +-
src/includes/traits/Plugin/AutoCacheUtils.php | 3 +-
src/includes/traits/Plugin/BbPressUtils.php | 3 +-
src/includes/traits/Plugin/CdnUtils.php | 4 +-
src/includes/traits/Plugin/CleanupUtils.php | 3 +-
src/includes/traits/Plugin/CondUtils.php | 3 +-
src/includes/traits/Plugin/CronUtils.php | 4 +-
src/includes/traits/Plugin/DbUtils.php | 3 +-
src/includes/traits/Plugin/DirUtils.php | 5 +-
src/includes/traits/Plugin/HtaccessUtils.php | 57 +++----
src/includes/traits/Plugin/HtmlCUtils.php | 3 +-
src/includes/traits/Plugin/InstallUtils.php | 6 +-
src/includes/traits/Plugin/MenuPageUtils.php | 5 +-
src/includes/traits/Plugin/NoticeUtils.php | 47 +++---
src/includes/traits/Plugin/OptionUtils.php | 3 +-
src/includes/traits/Plugin/PostUtils.php | 3 +-
src/includes/traits/Plugin/StatsUtils.php | 5 +-
src/includes/traits/Plugin/UpdateUtils.php | 3 +-
src/includes/traits/Plugin/UrlUtils.php | 3 +-
src/includes/traits/Plugin/UserUtils.php | 81 ++++-----
src/includes/traits/Plugin/WcpAuthorUtils.php | 5 +-
src/includes/traits/Plugin/WcpCdnUtils.php | 15 +-
.../traits/Plugin/WcpCommentUtils.php | 3 +-
src/includes/traits/Plugin/WcpEvalUtils.php | 10 +-
src/includes/traits/Plugin/WcpFeedUtils.php | 3 +-
.../traits/Plugin/WcpHomeBlogUtils.php | 3 +-
src/includes/traits/Plugin/WcpHtmlCUtils.php | 3 +-
.../traits/Plugin/WcpJetpackUtils.php | 3 +-
.../traits/Plugin/WcpOpcacheUtils.php | 17 +-
src/includes/traits/Plugin/WcpPluginUtils.php | 27 +--
.../traits/Plugin/WcpPostTypeUtils.php | 3 +-
src/includes/traits/Plugin/WcpPostUtils.php | 3 +-
.../traits/Plugin/WcpS2cleanUtils.php | 11 +-
.../traits/Plugin/WcpSettingUtils.php | 3 +-
.../traits/Plugin/WcpSitemapUtils.php | 4 +-
src/includes/traits/Plugin/WcpTermUtils.php | 3 +-
.../traits/Plugin/WcpTransientUtils.php | 44 ++---
.../traits/Plugin/WcpUpdaterUtils.php | 7 +-
src/includes/traits/Plugin/WcpUrlUtils.php | 25 +--
src/includes/traits/Plugin/WcpUserUtils.php | 21 +--
src/includes/traits/Plugin/WcpUtils.php | 3 +-
.../traits/Plugin/WcpWooCommerceUtils.php | 3 +-
src/includes/traits/Shared/BlogUtils.php | 5 +-
src/includes/traits/Shared/CacheDirUtils.php | 67 ++++----
src/includes/traits/Shared/CacheLockUtils.php | 10 +-
src/includes/traits/Shared/CachePathUtils.php | 106 ++++++------
.../traits/Shared/ConditionalUtils.php | 89 +++++-----
.../traits/Shared/DomainMappingUtils.php | 34 ++--
src/includes/traits/Shared/EscapeUtils.php | 9 +-
src/includes/traits/Shared/FsUtils.php | 36 ++--
src/includes/traits/Shared/HookUtils.php | 31 ++--
src/includes/traits/Shared/HttpUtils.php | 12 +-
src/includes/traits/Shared/I18nUtils.php | 9 +-
src/includes/traits/Shared/IpAddrUtils.php | 11 +-
src/includes/traits/Shared/PatternUtils.php | 3 +-
src/includes/traits/Shared/ReplaceUtils.php | 18 +-
src/includes/traits/Shared/ServerUtils.php | 19 ++-
src/includes/traits/Shared/StringUtils.php | 3 +-
src/includes/traits/Shared/SysUtils.php | 33 ++--
src/includes/traits/Shared/TokenUtils.php | 92 +++++-----
src/includes/traits/Shared/TrimUtils.php | 13 +-
src/includes/traits/Shared/UrlUtils.php | 19 ++-
91 files changed, 839 insertions(+), 790 deletions(-)
diff --git a/plugin.php b/plugin.php
index cdd74142..792a5a87 100644
--- a/plugin.php
+++ b/plugin.php
@@ -9,7 +9,7 @@
update_site_option('comet_cache_mbstring_deprecated_warning_bypass', time());
}
- ${__FILE__}['apc_enabled'] = (extension_loaded('apc') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) && filter_var(ini_get('apc.cache_by_default'), FILTER_VALIDATE_BOOLEAN) && stripos((string)ini_get('apc.filters'), 'comet-cache') === false) ? true : false;
+ ${__FILE__}['apc_enabled'] = (extension_loaded('apc') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) && filter_var(ini_get('apc.cache_by_default'), FILTER_VALIDATE_BOOLEAN) && stripos((string) ini_get('apc.filters'), 'comet-cache') === false) ? true : false;
if ((!version_compare(PHP_VERSION, '5.4', '>=') || ${__FILE__}['apc_enabled'])) { // If PHP <= 5.4 or APC is enabled
@@ -87,3 +87,4 @@
}
unset(${__FILE__}); // Housekeeping.
+
diff --git a/src/includes/classes/AbsBase.php b/src/includes/classes/AbsBase.php
index 5bd93003..dc809e9d 100644
--- a/src/includes/classes/AbsBase.php
+++ b/src/includes/classes/AbsBase.php
@@ -20,21 +20,21 @@ abstract class AbsBase
*
* @since 150422 Rewrite.
*/
- protected $cache = array();
+ protected $cache = [];
/**
* @type array Global static cache ref.
*
* @since 150422 Rewrite.
*/
- protected $static = array();
+ protected $static = [];
/**
* @type array Global static cache.
*
* @since 150422 Rewrite.
*/
- protected static $global_static = array();
+ protected static $global_static = [];
/**
* @type \stdClass Overload properties.
@@ -55,7 +55,7 @@ public function __construct()
$class = get_called_class();
if (empty(static::$global_static[$class])) {
- static::$global_static[$class] = array();
+ static::$global_static[$class] = [];
}
$this->static = &static::$global_static[$class];
@@ -76,7 +76,8 @@ public static function instance()
if (isset($instance)) {
return $instance;
}
- return ($instance = new static());
+
+ return $instance = new static();
}
/**
@@ -167,7 +168,7 @@ public function __unset($property)
* @note This function returns by reference. The use of `&` is highly recommended when calling this utility.
* See also:
*/
- public function &cacheKey($function, $args = array(), $___prop = 'cache')
+ public function &cacheKey($function, $args = [], $___prop = 'cache')
{
$function = (string) $function;
$args = (array) $args;
@@ -210,6 +211,7 @@ public function &cacheKey($function, $args = array(), $___prop = 'cache')
}
$cache_key = &$cache_key[$_key];
}
+
return $cache_key;
}
@@ -224,7 +226,7 @@ public function &cacheKey($function, $args = array(), $___prop = 'cache')
* @note This function returns by reference. The use of `&` is highly recommended when calling this utility.
* See also:
*/
- public function &staticKey($function, $args = array())
+ public function &staticKey($function, $args = [])
{
$key = &$this->cacheKey($function, $args, 'static');
diff --git a/src/includes/classes/AbsBaseAp.php b/src/includes/classes/AbsBaseAp.php
index 08635b9d..36c49265 100644
--- a/src/includes/classes/AbsBaseAp.php
+++ b/src/includes/classes/AbsBaseAp.php
@@ -2,7 +2,6 @@
namespace WebSharks\CometCache\Pro\Classes;
use WebSharks\CometCache\Pro\Traits;
-
use WebSharks\CometCache\Pro\Interfaces;
/**
diff --git a/src/includes/classes/Actions.php b/src/includes/classes/Actions.php
index 671af918..440acb4b 100644
--- a/src/includes/classes/Actions.php
+++ b/src/includes/classes/Actions.php
@@ -13,7 +13,7 @@ class Actions extends AbsBase
*
* @since 150422 Rewrite.
*/
- protected $allowed_actions = array(
+ protected $allowed_actions = [
'wipeCache',
'clearCache',
@@ -58,7 +58,7 @@ class Actions extends AbsBase
/*[/pro]*/
'dismissNotice',
- );
+ ];
/**
* Class constructor.
@@ -107,7 +107,7 @@ protected function wipeCache($args)
/*[/pro]*/
$redirect_to = self_admin_url('/admin.php');
- $query_args = array('page' => GLOBAL_NS, GLOBAL_NS.'_cache_wiped' => '1');
+ $query_args = ['page' => GLOBAL_NS, GLOBAL_NS.'_cache_wiped' => '1'];
$redirect_to = add_query_arg(urlencode_deep($query_args), $redirect_to);
wp_redirect($redirect_to).exit();
@@ -138,7 +138,7 @@ protected function clearCache($args)
/*[/pro]*/
$redirect_to = self_admin_url('/admin.php'); // Redirect preparations.
- $query_args = array('page' => GLOBAL_NS, GLOBAL_NS.'_cache_cleared' => '1');
+ $query_args = ['page' => GLOBAL_NS, GLOBAL_NS.'_cache_cleared' => '1'];
$redirect_to = add_query_arg(urlencode_deep($query_args), $redirect_to);
wp_redirect($redirect_to).exit();
@@ -392,7 +392,7 @@ protected function ajaxWipeExpiredTransients($args)
if (empty($_REQUEST['_wpnonce']) || !wp_verify_nonce($_REQUEST['_wpnonce'])) {
return; // Unauthenticated POST data.
}
- $counter = (int)($this->plugin->wipeExpiredTransients(true, false) / 2); // Divide in half for Dashboard message
+ $counter = (int) ($this->plugin->wipeExpiredTransients(true, false) / 2); // Divide in half for Dashboard message
$response = sprintf(__('Expired transients wiped successfully.
', SLUG_TD), esc_html(NAME));
$response .= sprintf(__('Wiped %1$s
expired transients.
', SLUG_TD), esc_html($counter));
@@ -417,7 +417,7 @@ protected function ajaxClearExpiredTransients($args)
if (empty($_REQUEST['_wpnonce']) || !wp_verify_nonce($_REQUEST['_wpnonce'])) {
return; // Unauthenticated POST data.
}
- $counter = (int)($this->plugin->clearExpiredTransients(true, false) / 2); // Divide in half for Dashboard message
+ $counter = (int) ($this->plugin->clearExpiredTransients(true, false) / 2); // Divide in half for Dashboard message
$response = sprintf(__('Expired transients cleared successfully.
', SLUG_TD), esc_html(NAME));
$response .= sprintf(__('Cleared %1$s
expired transients for this site.
', SLUG_TD), esc_html($counter));
@@ -449,7 +449,7 @@ protected function ajaxStats($args)
$is_multisite = is_multisite();
if (!$is_multisite || current_user_can($this->plugin->network_cap)) {
- $stats_data = array(
+ $stats_data = [
'forCache' => $dir_stats->forCache(),
'forHtmlCCache' => $dir_stats->forHtmlCCache(),
'largestCacheSize' => $dir_stats->largestCacheSize(),
@@ -458,20 +458,20 @@ protected function ajaxStats($args)
'sysLoadAverages' => $this->plugin->sysLoadAverages(),
'sysMemoryStatus' => $this->plugin->sysMemoryStatus(),
'sysOpcacheStatus' => $this->plugin->sysOpcacheStatus(),
- );
+ ];
if ($is_multisite) {
- $stats_data = array_merge($stats_data, array(
+ $stats_data = array_merge($stats_data, [
'forHostCache' => $dir_stats->forHostCache(),
'forHtmlCHostCache' => $dir_stats->forHtmlCHostCache(),
- ));
+ ]);
}
} else { // Stats for a child blog owner.
- $stats_data = array(
+ $stats_data = [
'forHostCache' => $dir_stats->forHostCache(),
'forHtmlCHostCache' => $dir_stats->forHtmlCHostCache(),
'largestHostCacheSize' => $dir_stats->largestHostCacheSize(),
'largestHostCacheCount' => $dir_stats->largestHostCacheCount(),
- );
+ ];
}
header('Content-Type: application/json; charset=UTF-8');
@@ -502,25 +502,25 @@ protected function ajaxDirStats($args)
$is_multisite = is_multisite();
if (!$is_multisite || current_user_can($this->plugin->network_cap)) {
- $dir_stats_data = array(
+ $dir_stats_data = [
'forCache' => $dir_stats->forCache(),
'forHtmlCCache' => $dir_stats->forHtmlCCache(),
'largestCacheSize' => $dir_stats->largestCacheSize(),
'largestCacheCount' => $dir_stats->largestCacheCount(),
- );
+ ];
if ($is_multisite) {
- $dir_stats_data = array_merge($dir_stats_data, array(
+ $dir_stats_data = array_merge($dir_stats_data, [
'forHostCache' => $dir_stats->forHostCache(),
'forHtmlCHostCache' => $dir_stats->forHtmlCHostCache(),
- ));
+ ]);
}
} else { // Stats for a child blog owner.
- $dir_stats_data = array(
+ $dir_stats_data = [
'forHostCache' => $dir_stats->forHostCache(),
'forHtmlCHostCache' => $dir_stats->forHtmlCHostCache(),
'largestHostCacheSize' => $dir_stats->largestHostCacheSize(),
'largestHostCacheCount' => $dir_stats->largestHostCacheCount(),
- );
+ ];
}
header('Content-Type: application/json; charset=UTF-8');
@@ -560,7 +560,7 @@ protected function saveOptions($args)
delete_transient(GLOBAL_NS.'-'.md5($this->plugin->options['auto_cache_sitemap_url']));
$redirect_to = self_admin_url('/admin.php'); // Redirect preparations.
- $query_args = array('page' => GLOBAL_NS, GLOBAL_NS.'_updated' => '1');
+ $query_args = ['page' => GLOBAL_NS, GLOBAL_NS.'_updated' => '1'];
$this->plugin->autoWipeCache(); // May produce a notice.
@@ -625,7 +625,7 @@ protected function restoreDefaultOptions($args)
$this->plugin->restoreDefaultOptions(); // Restore defaults.
$redirect_to = self_admin_url('/admin.php'); // Redirect preparations.
- $query_args = array('page' => GLOBAL_NS, GLOBAL_NS.'_restored' => '1');
+ $query_args = ['page' => GLOBAL_NS, GLOBAL_NS.'_restored' => '1'];
$this->plugin->autoWipeCache(); // May produce a notice.
@@ -736,15 +736,15 @@ protected function proUpdate($args)
$args['password'] = $this->plugin->options['pro_update_password'];
}
$product_api_url = 'https://'.urlencode(DOMAIN).'/';
- $product_api_input_vars = array(
- 'product_api' => array(
+ $product_api_input_vars = [
+ 'product_api' => [
'action' => 'latest_pro_update',
'stable' => $args['check_stable'],
'username' => $args['username'],
'password' => $args['password'],
- ),
- );
- $product_api_response = wp_remote_post($product_api_url, array('body' => $product_api_input_vars));
+ ],
+ ];
+ $product_api_response = wp_remote_post($product_api_url, ['body' => $product_api_input_vars]);
$product_api_response = json_decode(wp_remote_retrieve_body($product_api_response));
if (!is_object($product_api_response) || !empty($product_api_response->error) || empty($product_api_response->pro_version) || empty($product_api_response->pro_zip)) {
@@ -754,23 +754,23 @@ protected function proUpdate($args)
$error = __('Unknown error. Please wait 15 minutes and try again.', SLUG_TD);
}
$redirect_to = self_admin_url('/admin.php'); // Redirect preparations.
- $query_args = array('page' => GLOBAL_NS.'-pro-updater', GLOBAL_NS.'_error' => $error);
+ $query_args = ['page' => GLOBAL_NS.'-pro-updater', GLOBAL_NS.'_error' => $error];
$redirect_to = add_query_arg(urlencode_deep($query_args), $redirect_to);
wp_redirect($redirect_to).exit();
}
- $this->plugin->updateOptions(array(
+ $this->plugin->updateOptions([
'last_pro_update_check' => time(),
'pro_update_check' => $args['check'],
'pro_update_check_stable' => $args['check_stable'],
'pro_update_username' => $args['username'],
'pro_update_password' => $args['password'],
'latest_pro_version' => $product_api_response->pro_version,
- ));
+ ]);
$this->plugin->dismissMainNotice('new-pro-version-available');
$redirect_to = self_admin_url('/update.php');
- $query_args = array( // Like a normal WP plugin.
+ $query_args = [ // Like a normal WP plugin.
'action' => 'upgrade-plugin',
'plugin' => plugin_basename(PLUGIN_FILE),
'_wpnonce' => wp_create_nonce('upgrade-plugin_'.plugin_basename(PLUGIN_FILE)),
@@ -779,7 +779,7 @@ protected function proUpdate($args)
GLOBAL_NS.'_update_pro_version' => $product_api_response->pro_version,
GLOBAL_NS.'_update_pro_zip' => base64_encode($product_api_response->pro_zip),
// @TODO Encrypt/decrypt to avoid mod_security issues. Base64 is not enough.
- );
+ ];
$redirect_to = add_query_arg(urlencode_deep($query_args), $redirect_to);
wp_redirect($redirect_to).exit();
diff --git a/src/includes/classes/AdvCacheBackCompat.php b/src/includes/classes/AdvCacheBackCompat.php
index 84ff021e..338e5012 100644
--- a/src/includes/classes/AdvCacheBackCompat.php
+++ b/src/includes/classes/AdvCacheBackCompat.php
@@ -15,11 +15,11 @@ class AdvCacheBackCompat
*/
public static function zcRequestVars()
{
- $super_gs = array(
+ $super_gs = [
'_GET' => &$_GET,
'_REQUEST' => &$_REQUEST,
- );
- $zc_suffixes = array('AC', 'ABC');
+ ];
+ $zc_suffixes = ['AC', 'ABC'];
foreach ($super_gs as $_super_g_key => &$_super_g_value) {
foreach ($zc_suffixes as $_zc_suffix) {
diff --git a/src/includes/classes/ApiBase.php b/src/includes/classes/ApiBase.php
index 9318f0e2..2c73349f 100644
--- a/src/includes/classes/ApiBase.php
+++ b/src/includes/classes/ApiBase.php
@@ -100,6 +100,7 @@ public static function clearPost($post_id)
public static function clearUrl($url)
{
$regex = $GLOBALS[GLOBAL_NS]->buildCachePathRegexFromWcUrl($url);
+
return $GLOBALS[GLOBAL_NS]->deleteFilesFromCacheDir($regex);
}
diff --git a/src/includes/classes/AutoCache.php b/src/includes/classes/AutoCache.php
index 039559b6..80328fef 100644
--- a/src/includes/classes/AutoCache.php
+++ b/src/includes/classes/AutoCache.php
@@ -1,4 +1,5 @@
plugin->options['auto_cache_other_urls'];
$other_urls = preg_split('/\s+/', $other_urls, -1, PREG_SPLIT_NO_EMPTY);
- $blogs = array((object) array('ID' => null, 'other' => $other_urls));
+ $blogs = [(object) ['ID' => null, 'other' => $other_urls]];
$is_multisite = is_multisite(); // Multisite network?
$can_consider_domain_mapping = $is_multisite && $this->plugin->canConsiderDomainMapping();
@@ -84,7 +85,7 @@ protected function run()
shuffle($blogs); // Randomize; i.e. don't always start from the top.
foreach ($blogs as $_blog) {
- $_blog_sitemap_urls = $_blog_other_urls = $_blog_urls = array();
+ $_blog_sitemap_urls = $_blog_other_urls = $_blog_urls = [];
if (!isset($_blog->ID)) { // `home_url()` fallback.
$_blog_url = rtrim(network_home_url('', 'http'), '/');
@@ -154,11 +155,11 @@ protected function autoCacheUrl($url)
$url,
wp_remote_get(
$url,
- array(
+ [
'blocking' => false,
'user-agent' => $this->plugin->options['auto_cache_user_agent'].
'; '.GLOBAL_NS.' '.VERSION,
- )
+ ]
)
);
}
@@ -248,7 +249,7 @@ protected function logAutoCacheRun($total_urls, $total_time)
*/
protected function getSitemapUrlsDeep($sitemap, $___recursive = false)
{
- $urls = array();
+ $urls = [];
$xml_reader = new \XMLReader();
$failure = ''; // Initialize.
@@ -297,7 +298,7 @@ protected function getSitemapUrlsDeep($sitemap, $___recursive = false)
*/
protected function xmlGetSitemapIndexUrlsDeep(\XMLReader $xml_reader)
{
- $urls = array(); // Initialize.
+ $urls = []; // Initialize.
if ($xml_reader->name === 'sitemapindex') {
while ($xml_reader->read()) {
@@ -319,6 +320,7 @@ protected function xmlGetSitemapIndexUrlsDeep(\XMLReader $xml_reader)
}
}
}
+
return $urls; // All sitemap URLs from this `` node; deeply.
}
}
@@ -334,7 +336,7 @@ protected function xmlGetSitemapIndexUrlsDeep(\XMLReader $xml_reader)
*/
protected function xmlGetUrlsetUrls(\XMLReader $xml_reader)
{
- $urls = array(); // Initialize.
+ $urls = []; // Initialize.
if ($xml_reader->name === 'urlset') {
while ($xml_reader->read()) {
@@ -356,6 +358,7 @@ protected function xmlGetUrlsetUrls(\XMLReader $xml_reader)
}
}
}
+
return $urls; // All sitemap URLs from this `` node.
}
}
diff --git a/src/includes/classes/CdnFilters.php b/src/includes/classes/CdnFilters.php
index 874e2e8d..7c67b358 100644
--- a/src/includes/classes/CdnFilters.php
+++ b/src/includes/classes/CdnFilters.php
@@ -1,4 +1,5 @@
cdn_over_ssl = (boolean) $this->plugin->options['cdn_over_ssl'];
+ $this->cdn_over_ssl = (boolean) $this->plugin->options['cdn_over_ssl'];
$this->cdn_when_logged_in = (boolean) $this->plugin->options['cdn_when_logged_in'];
// Whitelisted extensions; MUST have these at all times.
@@ -179,7 +180,7 @@ public function __construct()
if ($cdn_whitelisted_uri_patterns) {
$this->cdn_whitelisted_uri_patterns = '/(?:'.implode('|', array_map(function ($pattern) {
- return preg_replace(array('/\\\\\*/', '/\\\\\^/'), array('.*?', '[^\/]*?'), preg_quote('/'.ltrim($pattern, '/'), '/'));
+ return preg_replace(['/\\\\\*/', '/\\\\\^/'], ['.*?', '[^\/]*?'], preg_quote('/'.ltrim($pattern, '/'), '/'));
}, $cdn_whitelisted_uri_patterns)).')/i'; // CaSe inSensitive.
}
// Blacklisted URI patterns; if applicable.
@@ -198,7 +199,7 @@ public function __construct()
if ($cdn_blacklisted_uri_patterns) {
$this->cdn_blacklisted_uri_patterns = '/(?:'.implode('|', array_map(function ($pattern) {
- return preg_replace(array('/\\\\\*/', '/\\\\\^/'), array('.*?', '[^\/]*?'), preg_quote('/'.ltrim($pattern, '/'), '/'));
+ return preg_replace(['/\\\\\*/', '/\\\\\^/'], ['.*?', '[^\/]*?'], preg_quote('/'.ltrim($pattern, '/'), '/'));
}, $cdn_blacklisted_uri_patterns)).')/i'; // CaSe inSensitive.
}
// Maybe attach filters.
@@ -252,41 +253,41 @@ protected function maybeSetupFilters()
$this->started_wp_footer_action_hook = true;
}, -PHP_INT_MAX); // The very first hook, ideally.
- add_filter('home_url', array($this, 'urlFilter'), PHP_INT_MAX - 10, 4);
- add_filter('site_url', array($this, 'urlFilter'), PHP_INT_MAX - 10, 4);
+ add_filter('home_url', [$this, 'urlFilter'], PHP_INT_MAX - 10, 4);
+ add_filter('site_url', [$this, 'urlFilter'], PHP_INT_MAX - 10, 4);
- add_filter('network_home_url', array($this, 'urlFilter'), PHP_INT_MAX - 10, 3);
- add_filter('network_site_url', array($this, 'urlFilter'), PHP_INT_MAX - 10, 3);
+ add_filter('network_home_url', [$this, 'urlFilter'], PHP_INT_MAX - 10, 3);
+ add_filter('network_site_url', [$this, 'urlFilter'], PHP_INT_MAX - 10, 3);
- add_filter('content_url', array($this, 'urlFilter'), PHP_INT_MAX - 10, 2);
- add_filter('plugins_url', array($this, 'urlFilter'), PHP_INT_MAX - 10, 2);
+ add_filter('content_url', [$this, 'urlFilter'], PHP_INT_MAX - 10, 2);
+ add_filter('plugins_url', [$this, 'urlFilter'], PHP_INT_MAX - 10, 2);
- add_filter('wp_get_attachment_url', array($this, 'urlFilter'), PHP_INT_MAX - 10, 1);
+ add_filter('wp_get_attachment_url', [$this, 'urlFilter'], PHP_INT_MAX - 10, 1);
- add_filter('script_loader_src', array($this, 'urlFilter'), PHP_INT_MAX - 10, 1);
- add_filter('style_loader_src', array($this, 'urlFilter'), PHP_INT_MAX - 10, 1);
+ add_filter('script_loader_src', [$this, 'urlFilter'], PHP_INT_MAX - 10, 1);
+ add_filter('style_loader_src', [$this, 'urlFilter'], PHP_INT_MAX - 10, 1);
- add_filter('the_content', array($this, 'contentFilter'), PHP_INT_MAX - 10, 1);
- add_filter('get_the_excerpt', array($this, 'contentFilter'), PHP_INT_MAX - 10, 1);
- add_filter('widget_text', array($this, 'contentFilter'), PHP_INT_MAX - 10, 1);
+ add_filter('the_content', [$this, 'contentFilter'], PHP_INT_MAX - 10, 1);
+ add_filter('get_the_excerpt', [$this, 'contentFilter'], PHP_INT_MAX - 10, 1);
+ add_filter('widget_text', [$this, 'contentFilter'], PHP_INT_MAX - 10, 1);
if ($this->htmlc_enable) {
// If the HTML Compressor is enabled, attach early hook. Runs later.
if (empty($GLOBALS['WebSharks\\HtmlCompressor_early_hooks']) || !is_array($GLOBALS['WebSharks\\HtmlCompressor_early_hooks'])) {
- $GLOBALS['WebSharks\\HtmlCompressor_early_hooks'] = array(); // Initialize.
+ $GLOBALS['WebSharks\\HtmlCompressor_early_hooks'] = []; // Initialize.
}
- $GLOBALS['WebSharks\\HtmlCompressor_early_hooks'][] = array(
+ $GLOBALS['WebSharks\\HtmlCompressor_early_hooks'][] = [
'hook' => 'css_url()', // Filters CSS `url()`s.
- 'function' => array($this, 'htmlCUrlFilter'),
+ 'function' => [$this, 'htmlCUrlFilter'],
'priority' => PHP_INT_MAX - 10,
'accepted_args' => 1,
- );
- $GLOBALS['WebSharks\\HtmlCompressor_early_hooks'][] = array(
+ ];
+ $GLOBALS['WebSharks\\HtmlCompressor_early_hooks'][] = [
'hook' => 'part_url', // Filters JS/CSS parts.
- 'function' => array($this, 'htmlCUrlFilter'),
+ 'function' => [$this, 'htmlCUrlFilter'],
'priority' => PHP_INT_MAX - 10,
'accepted_args' => 2,
- );
+ ];
}
}
@@ -362,6 +363,7 @@ public function contentFilter($string)
$string = preg_replace_callback($regex_url_attrs, function ($m) {
unset($m[0]); // Discard full match.
$m[6] = $this->filterUrl($m[6], null, true, null);
+
return implode('', $m); // Concatenate all parts.
}, $string); // End content filter.
@@ -434,6 +436,7 @@ public function filterUrl($url_uri_qsl, $scheme = null, $esc = false, $for = nul
if ($this->cdn_invalidation_var && $this->cdn_invalidation_counter) {
$url = add_query_arg($this->cdn_invalidation_var, $this->cdn_invalidation_counter, $url);
}
+
return $esc ? esc_attr($url) : $url;
}
@@ -490,6 +493,7 @@ protected function localFile($url_uri_qsl)
if (!($extension = $this->extension($parsed['path']))) {
return; // No extension; i.e. not a file.
}
+
return (object) compact('scheme', 'host', 'uri', 'extension');
}
@@ -507,6 +511,7 @@ protected function extension($path)
if (!($path = trim((string) $path))) {
return ''; // No path.
}
+
return strtolower(ltrim((string) strrchr(basename($path), '.'), '.'));
}
@@ -518,9 +523,9 @@ protected function extension($path)
protected function parseCdnHosts()
{
$lines = (string) $this->cdn_hosts;
- $this->cdn_hosts = array(); // Initialize.
+ $this->cdn_hosts = []; // Initialize.
- $lines = str_replace(array("\r\n", "\r"), "\n", $lines);
+ $lines = str_replace(["\r\n", "\r"], "\n", $lines);
$lines = trim(strtolower($lines)); // Force all mappings to lowercase.
$lines = preg_split('/['."\r\n".']+/', $lines, null, PREG_SPLIT_NO_EMPTY);
@@ -531,7 +536,7 @@ protected function parseCdnHosts()
if (strpos($_line, '=') !== false) {
$_parts = explode('=', $_line, 2);
} else {
- $_parts = array($this->local_host, $_line);
+ $_parts = [$this->local_host, $_line];
}
$_parts = $this->plugin->trimDeep($_parts);
@@ -567,15 +572,16 @@ public static function defaultWhitelistedExtensions()
{
$extensions = array_keys(wp_get_mime_types());
$extensions = explode('|', strtolower(implode('|', $extensions)));
- $extensions = array_merge($extensions, array('eot', 'ttf', 'otf', 'woff'));
+ $extensions = array_merge($extensions, ['eot', 'ttf', 'otf', 'woff']);
if (($permalink_structure = get_option('permalink_structure'))) {
if (strcasecmp(substr($permalink_structure, -5), '.html') === 0) {
- $extensions = array_diff($extensions, array('html'));
+ $extensions = array_diff($extensions, ['html']);
} elseif (strcasecmp(substr($permalink_structure, -4), '.htm') === 0) {
- $extensions = array_diff($extensions, array('htm'));
+ $extensions = array_diff($extensions, ['htm']);
}
}
+
return array_unique($extensions);
}
}
diff --git a/src/includes/classes/Conflicts.php b/src/includes/classes/Conflicts.php
index a5489f4e..c7385021 100644
--- a/src/includes/classes/Conflicts.php
+++ b/src/includes/classes/Conflicts.php
@@ -18,6 +18,7 @@ public static function check()
if (static::doCheck()) {
static::maybeEnqueueNotice();
}
+
return $GLOBALS[GLOBAL_NS.'_conflicting_plugin'];
}
@@ -31,13 +32,13 @@ protected static function doCheck()
if (!empty($GLOBALS[GLOBAL_NS.'_conflicting_plugin'])) {
return $GLOBALS[GLOBAL_NS.'_conflicting_plugin'];
}
- $conflicting_plugin_slugs = array(
+ $conflicting_plugin_slugs = [
'zencache', 'zencache-pro', 'quick-cache', 'quick-cache-pro',
str_replace('_', '-', GLOBAL_NS).(IS_PRO ? '' : '-pro'),
'wp-super-cache', 'w3-total-cache', 'hyper-cache', 'wp-rocket',
- );
- $active_plugins = (array) get_option('active_plugins', array());
- $active_sitewide_plugins = is_multisite() ? array_keys((array) get_site_option('active_sitewide_plugins', array())) : array();
+ ];
+ $active_plugins = (array) get_option('active_plugins', []);
+ $active_sitewide_plugins = is_multisite() ? array_keys((array) get_site_option('active_sitewide_plugins', [])) : [];
$active_plugins = array_unique(array_merge($active_plugins, $active_sitewide_plugins));
foreach ($active_plugins as $_active_plugin_basename) {
@@ -45,16 +46,17 @@ protected static function doCheck()
continue; // Nothing to check in this case.
}
if (in_array($_active_plugin_slug, $conflicting_plugin_slugs, true)) {
- if (empty($GLOBALS[GLOBAL_NS.'_uninstalling']) && is_admin() && in_array($_active_plugin_slug, array('comet-cache', 'comet-cache-pro', 'zencache', 'zencache-pro', 'quick-cache', 'quick-cache-pro'), true)) {
+ if (empty($GLOBALS[GLOBAL_NS.'_uninstalling']) && is_admin() && in_array($_active_plugin_slug, ['comet-cache', 'comet-cache-pro', 'zencache', 'zencache-pro', 'quick-cache', 'quick-cache-pro'], true)) {
add_action('admin_init', function () use ($_active_plugin_basename) {
deactivate_plugins($_active_plugin_basename, true);
}, -1000);
} else {
- return ($GLOBALS[GLOBAL_NS.'_conflicting_plugin'] = $_active_plugin_slug);
+ return $GLOBALS[GLOBAL_NS.'_conflicting_plugin'] = $_active_plugin_slug;
}
}
}
- return ($GLOBALS[GLOBAL_NS.'_conflicting_plugin'] = ''); // i.e. No conflicting plugins.
+
+ return $GLOBALS[GLOBAL_NS.'_conflicting_plugin'] = ''; // i.e. No conflicting plugins.
}
/**
diff --git a/src/includes/classes/DirStats.php b/src/includes/classes/DirStats.php
index 9a58047d..de4183be 100644
--- a/src/includes/classes/DirStats.php
+++ b/src/includes/classes/DirStats.php
@@ -1,4 +1,5 @@
cache_key = GLOBAL_NS.'_dir_stats';
$this->history_cache_key = GLOBAL_NS.'_h_dir_stats';
- $this->allowed_history_cache_keys = array(md5('forCache0'), md5('forHtmlCCache0'));
- $this->allowed_host_history_cache_keys = array(md5('forHostCache0'), md5('forHtmlCHostCache0'));
+ $this->allowed_history_cache_keys = [md5('forCache0'), md5('forHtmlCCache0')];
+ $this->allowed_host_history_cache_keys = [md5('forHostCache0'), md5('forHtmlCHostCache0')];
}
/**
@@ -71,8 +72,9 @@ public function __construct()
protected function getCache()
{
if (!is_array($cache = get_site_option($this->cache_key))) {
- update_site_option($this->cache_key, ($cache = array()));
+ update_site_option($this->cache_key, ($cache = []));
}
+
return $cache;
}
@@ -88,8 +90,9 @@ protected function getHostCache()
$host_cache_key = $this->cacheKeyForBlog();
if (!is_array($host_cache = get_site_option($host_cache_key))) {
- update_site_option($host_cache_key, ($host_cache = array()));
+ update_site_option($host_cache_key, ($host_cache = []));
}
+
return $host_cache;
}
@@ -103,8 +106,9 @@ protected function getHostCache()
protected function getHistoryCache()
{
if (!is_array($cache = get_site_option($this->history_cache_key))) {
- update_site_option($this->history_cache_key, ($cache = array()));
+ update_site_option($this->history_cache_key, ($cache = []));
}
+
return $cache;
}
@@ -120,8 +124,9 @@ protected function getHostHistoryCache()
$host_history_cache_key = $this->historyCacheKeyForBlog();
if (!is_array($host_history_cache = get_site_option($host_history_cache_key))) {
- update_site_option($host_history_cache_key, ($host_history_cache = array()));
+ update_site_option($host_history_cache_key, ($host_history_cache = []));
}
+
return $host_history_cache;
}
@@ -136,7 +141,7 @@ protected function getHostHistoryCache()
protected function updateCache($key, \stdClass $stats)
{
$cache = $this->getCache();
- $cache = array_merge($cache, array((string) $key => $stats));
+ $cache = array_merge($cache, [(string) $key => $stats]);
update_site_option($this->cache_key, $cache);
$this->updateHistoryCache($key, $stats);
}
@@ -153,7 +158,7 @@ protected function updateHostCache($key, \stdClass $stats)
{
$host_cache = $this->getHostCache();
$host_cache_key = $this->cacheKeyForBlog();
- $host_cache = array_merge($host_cache, array((string) $key => $stats));
+ $host_cache = array_merge($host_cache, [(string) $key => $stats]);
update_site_option($host_cache_key, $host_cache);
$this->updateHostHistoryCache($key, $stats);
}
@@ -303,13 +308,13 @@ public function wipeCache($include_child_blogs = true)
}
} // ↓ Even if clearing child blogs.
// This makes sure the option cache is updated also.
- update_site_option($this->cache_key, array()); // Always.
+ update_site_option($this->cache_key, []); // Always.
// Clear network and current blog.
// If different; or in case `$include_child_blogs=false`.
$host_cache_key = $this->cacheKeyForBlog(); // If not the same.
if ($this->cache_key !== $host_cache_key) { // Clear host?
- update_site_option($host_cache_key, array());
+ update_site_option($host_cache_key, []);
}
}
@@ -326,7 +331,7 @@ public function clearHostCache($consider_network_cap = true)
$this->wipeCache(false); // Wipe network and current blog.
} else {
$host_cache_key = $this->cacheKeyForBlog();
- update_site_option($host_cache_key, array());
+ update_site_option($host_cache_key, []);
}
}
@@ -354,13 +359,13 @@ public function wipeHistoryCache($include_child_blogs = true)
}
} // ↓ Even if clearing child blogs.
// This makes sure the option cache is updated also.
- update_site_option($this->history_cache_key, array()); // Always.
+ update_site_option($this->history_cache_key, []); // Always.
// Clear network and current blog.
// If different; or in case `$include_child_blogs=false`.
$host_history_cache_key = $this->historyCacheKeyForBlog(); // If not the same.
if ($this->history_cache_key !== $host_history_cache_key) { // Clear host?
- update_site_option($host_history_cache_key, array());
+ update_site_option($host_history_cache_key, []);
}
}
@@ -377,7 +382,7 @@ public function clearHostHistoryCache($consider_network_cap = true)
$this->wipeHistoryCache(false); // Wipe network and current blog.
} else {
$host_history_cache_key = $this->historyCacheKeyForBlog();
- update_site_option($host_history_cache_key, array());
+ update_site_option($host_history_cache_key, []);
}
}
@@ -399,8 +404,10 @@ protected function cacheKeyForBlog($blog_id = 0)
if (!$blog_id) {
$blog_id = (integer) get_current_blog_id();
}
+
return $this->cache_key.'_'.$blog_id;
}
+
return $this->cache_key;
}
@@ -422,8 +429,10 @@ protected function historyCacheKeyForBlog($blog_id = 0)
if (!$blog_id) {
$blog_id = (integer) get_current_blog_id();
}
+
return $this->history_cache_key.'_'.$blog_id;
}
+
return $this->history_cache_key;
}
@@ -454,7 +463,7 @@ public function forCache($no_cache = false, $include_paths = false)
} // Otherwise, we need to pull a fresh set of stats.
$stats = (object) $this->plugin->getDirRegexStats($this->plugin->cacheDir(), '', $include_paths, true, true);
- $stats = (object) array('stats' => $stats, 'time' => time());
+ $stats = (object) ['stats' => $stats, 'time' => time()];
$this->updateCache($cache_key, $stats);
@@ -489,7 +498,7 @@ public function forHtmlCCache($no_cache = false, $include_paths = false)
$stats = new \stdClass(); // Initialize stats object instance.
- $htmlc_cache_dirs = array(); // Initialize directories.
+ $htmlc_cache_dirs = []; // Initialize directories.
$htmlc_cache_dirs[] = $this->plugin->wpContentBaseDirTo($this->plugin->htmlc_cache_sub_dir_public);
$htmlc_cache_dirs[] = $this->plugin->wpContentBaseDirTo($this->plugin->htmlc_cache_sub_dir_private);
@@ -509,7 +518,7 @@ public function forHtmlCCache($no_cache = false, $include_paths = false)
}
unset($_htmlc_cache_dir, $_check_disk_stats); // Housekeeping.
- $stats = (object) array('stats' => $stats, 'time' => time());
+ $stats = (object) ['stats' => $stats, 'time' => time()];
$this->updateCache($cache_key, $stats);
@@ -560,7 +569,7 @@ public function forHostCache(
}
$stats = new \stdClass(); // Initialize stats object instance.
- foreach (array('http', 'https') as $_host_scheme) {
+ foreach (['http', 'https'] as $_host_scheme) {
$_host_url = $_host_scheme.'://'.$host_token.$host_base_dir_tokens;
$_host_cache_path_flags = $this::CACHE_PATH_NO_PATH_INDEX | $this::CACHE_PATH_NO_QUV | $this::CACHE_PATH_NO_EXT;
$_host_cache_path = $this->plugin->buildCachePath($_host_url, '', '', $_host_cache_path_flags);
@@ -581,18 +590,18 @@ public function forHostCache(
unset($_host_scheme, $_host_url, $_host_cache_path_flags, $_host_cache_path, $_host_cache_dir, $_check_disk_stats);
if (!$___considering_domain_mapping && is_multisite() && $this->plugin->canConsiderDomainMapping()) {
- $domain_mapping_variations = array(); // Initialize array of domain variations.
+ $domain_mapping_variations = []; // Initialize array of domain variations.
if (($_host_token_for_blog = $this->plugin->hostTokenForBlog())) {
$_host_base_dir_tokens_for_blog = $this->plugin->hostBaseDirTokensForBlog();
- $domain_mapping_variations[] = array('host_token' => $_host_token_for_blog, 'host_base_dir_tokens' => $_host_base_dir_tokens_for_blog);
+ $domain_mapping_variations[] = ['host_token' => $_host_token_for_blog, 'host_base_dir_tokens' => $_host_base_dir_tokens_for_blog];
} // The original blog host; i.e., without domain mapping.
unset($_host_token_for_blog, $_host_base_dir_tokens_for_blog); // Housekeeping.
foreach ($this->plugin->domainMappingBlogDomains() as $_domain_mapping_blog_domain) {
if (($_domain_host_token_for_blog = $this->plugin->hostTokenForBlog(false, true, $_domain_mapping_blog_domain))) {
$_domain_host_base_dir_tokens_for_blog = $this->plugin->hostBaseDirTokensForBlog(false, true); // This is only a formality.
- $domain_mapping_variations[] = array('host_token' => $_domain_host_token_for_blog, 'host_base_dir_tokens' => $_domain_host_base_dir_tokens_for_blog);
+ $domain_mapping_variations[] = ['host_token' => $_domain_host_token_for_blog, 'host_base_dir_tokens' => $_domain_host_base_dir_tokens_for_blog];
}
} // This includes all of the domain mappings configured for the current blog ID.
unset($_domain_mapping_blog_domain, $_domain_host_token_for_blog, $_domain_host_base_dir_tokens_for_blog); // Housekeeping.
@@ -614,11 +623,12 @@ public function forHostCache(
}
unset($_domain_mapping_variation); // Housekeeping.
}
- $stats = (object) array('stats' => $stats, 'time' => time());
+ $stats = (object) ['stats' => $stats, 'time' => time()];
if (!$___considering_domain_mapping) {
$this->updateHostCache($cache_key, $stats);
}
+
return $stats;
}
@@ -649,7 +659,7 @@ public function forHtmlCHostCache($no_cache = false, $include_paths = false)
$host_token = $this->plugin->hostToken(true); // Dashify.
$host_base_dir_tokens = $this->plugin->hostBaseDirTokens(true); // Dashify.
- $htmlc_cache_dirs = array(); // Initialize array of all HTML Compressor directories to clear.
+ $htmlc_cache_dirs = []; // Initialize array of all HTML Compressor directories to clear.
$htmlc_cache_dirs[] = $this->plugin->wpContentBaseDirTo($this->plugin->htmlc_cache_sub_dir_public.rtrim($host_base_dir_tokens, '/').'/'.$host_token);
$htmlc_cache_dirs[] = $this->plugin->wpContentBaseDirTo($this->plugin->htmlc_cache_sub_dir_private.rtrim($host_base_dir_tokens, '/').'/'.$host_token);
@@ -686,7 +696,7 @@ public function forHtmlCHostCache($no_cache = false, $include_paths = false)
}
unset($_htmlc_cache_dir, $_check_disk_stats); // Just a little housekeeping.
- $stats = (object) array('stats' => $stats, 'time' => time());
+ $stats = (object) ['stats' => $stats, 'time' => time()];
$this->updateHostCache($cache_key, $stats);
@@ -708,7 +718,7 @@ public function largestCacheSize($last_x_days = null)
$last_x_days = max(1, $this->plugin->options['dir_stats_history_days']);
}
$largest_size = 0; // Initialize.
- $largest_sizes = array(); // Initialize.
+ $largest_sizes = []; // Initialize.
$history_cache = $this->getHistoryCache();
$history_max_age = strtotime('-'.$last_x_days.' days');
@@ -731,7 +741,7 @@ public function largestCacheSize($last_x_days = null)
}
unset($_key, $_time, $_stats); // Housekeeping.
- return (object) array('days' => $last_x_days, 'size' => $largest_size);
+ return (object) ['days' => $last_x_days, 'size' => $largest_size];
}
/**
@@ -749,7 +759,7 @@ public function largestHostCacheSize($last_x_days = null)
$last_x_days = max(1, $this->plugin->options['dir_stats_history_days']);
}
$largest_size = 0; // Initialize.
- $largest_sizes = array(); // Initialize.
+ $largest_sizes = []; // Initialize.
$host_history_cache = $this->getHostHistoryCache();
$host_history_max_age = strtotime('-'.$last_x_days.' days');
@@ -772,7 +782,7 @@ public function largestHostCacheSize($last_x_days = null)
}
unset($_key, $_time, $_stats); // Housekeeping.
- return (object) array('days' => $last_x_days, 'size' => $largest_size);
+ return (object) ['days' => $last_x_days, 'size' => $largest_size];
}
/**
@@ -790,7 +800,7 @@ public function largestCacheCount($last_x_days = null)
$last_x_days = max(1, $this->plugin->options['dir_stats_history_days']);
}
$largest_count = 0; // Initialize.
- $largest_counts = array(); // Initialize.
+ $largest_counts = []; // Initialize.
$history_cache = $this->getHistoryCache();
$history_max_age = strtotime('-'.$last_x_days.' days');
@@ -813,7 +823,7 @@ public function largestCacheCount($last_x_days = null)
}
unset($_key, $_time, $_stats); // Housekeeping.
- return (object) array('days' => $last_x_days, 'count' => $largest_count);
+ return (object) ['days' => $last_x_days, 'count' => $largest_count];
}
/**
@@ -831,7 +841,7 @@ public function largestHostCacheCount($last_x_days = null)
$last_x_days = max(1, $this->plugin->options['dir_stats_history_days']);
}
$largest_count = 0; // Initialize.
- $largest_counts = array(); // Initialize.
+ $largest_counts = []; // Initialize.
$host_history_cache = $this->getHostHistoryCache();
$host_history_max_age = strtotime('-'.$last_x_days.' days');
@@ -854,7 +864,7 @@ public function largestHostCacheCount($last_x_days = null)
}
unset($_key, $_time, $_stats); // Housekeeping.
- return (object) array('days' => $last_x_days, 'count' => $largest_count);
+ return (object) ['days' => $last_x_days, 'count' => $largest_count];
}
}
/*[/pro]*/
diff --git a/src/includes/classes/FeedUtils.php b/src/includes/classes/FeedUtils.php
index bec02a79..120c12f3 100644
--- a/src/includes/classes/FeedUtils.php
+++ b/src/includes/classes/FeedUtils.php
@@ -48,7 +48,7 @@ public function __construct()
$this->home_url = rtrim(home_url(), '/');
$this->default_feed = get_default_feed(); // Default feed type.
$this->seo_friendly_permalinks = (boolean) get_option('permalink_structure');
- $this->feed_types = array_unique(array($this->default_feed, 'rdf', 'rss', 'rss2', 'atom'));
+ $this->feed_types = array_unique([$this->default_feed, 'rdf', 'rss', 'rss2', 'atom']);
}
/**
@@ -62,7 +62,7 @@ public function __construct()
*/
public function feedLinkVariations($type_prefix = '')
{
- $variations = array(); // Initialize.
+ $variations = []; // Initialize.
foreach ($this->feed_types as $_feed_type) {
$variations[] = get_feed_link((string) $type_prefix.$_feed_type);
@@ -83,7 +83,7 @@ public function feedLinkVariations($type_prefix = '')
*/
public function postCommentsFeedLinkVariations(\WP_Post $post)
{
- $variations = array(); // Initialize.
+ $variations = []; // Initialize.
foreach ($this->feed_types as $_feed_type) {
$variations[] = get_post_comments_feed_link($post->ID, $_feed_type);
@@ -104,15 +104,15 @@ public function postCommentsFeedLinkVariations(\WP_Post $post)
*/
public function postAuthorFeedLinkVariations(\WP_Post $post)
{
- $variations = array(); // Initialize.
+ $variations = []; // Initialize.
foreach ($this->feed_types as $_feed_type) {
$variations[] = get_author_feed_link($post->post_author, $_feed_type);
}
if ($this->seo_friendly_permalinks && ($post_author = get_userdata($post->post_author))) {
foreach ($this->feed_types as $_feed_type) {
- $variations[] = add_query_arg(urlencode_deep(array('author' => $post->post_author)), $this->home_url.'/feed/'.urlencode($_feed_type).'/');
- $variations[] = add_query_arg(urlencode_deep(array('author' => $post_author->user_nicename)), $this->home_url.'/feed/'.urlencode($_feed_type).'/');
+ $variations[] = add_query_arg(urlencode_deep(['author' => $post->post_author]), $this->home_url.'/feed/'.urlencode($_feed_type).'/');
+ $variations[] = add_query_arg(urlencode_deep(['author' => $post_author->user_nicename]), $this->home_url.'/feed/'.urlencode($_feed_type).'/');
}
}
unset($_feed_type); // Housekeeping.
@@ -131,7 +131,7 @@ public function postAuthorFeedLinkVariations(\WP_Post $post)
*/
public function postTypeArchiveFeedLinkVariations(\WP_Post $post)
{
- $variations = array(); // Initialize.
+ $variations = []; // Initialize.
foreach ($this->feed_types as $_feed_type) {
$variations[] = get_post_type_archive_feed_link($post->post_type, $_feed_type);
@@ -158,7 +158,7 @@ public function postTypeArchiveFeedLinkVariations(\WP_Post $post)
*/
public function postTermFeedLinkVariations(\WP_Post $post, $include_regex_wildcard_keys = false)
{
- $variations = $post_terms = array(); // Initialize.
+ $variations = $post_terms = []; // Initialize.
if (!is_array($post_taxonomies = get_object_taxonomies($post, 'objects')) || !$post_taxonomies) {
return $variations; // Nothing to do here; post has no terms.
@@ -202,10 +202,10 @@ public function postTermFeedLinkVariations(\WP_Post $post, $include_regex_wildca
$_taxonomy_query_var = $_taxonomy->query_var;
}
foreach ($this->feed_types as $_feed_type) {
- $variations[] = add_query_arg(urlencode_deep(array($_taxonomy_query_var => $_post_term->term_id)), $this->home_url.'/feed/'.urlencode($_feed_type).'/');
+ $variations[] = add_query_arg(urlencode_deep([$_taxonomy_query_var => $_post_term->term_id]), $this->home_url.'/feed/'.urlencode($_feed_type).'/');
}
foreach ($this->feed_types as $_feed_type) {
- $variations[] = add_query_arg(urlencode_deep(array($_taxonomy_query_var => $_post_term->slug)), $this->home_url.'/feed/'.urlencode($_feed_type).'/');
+ $variations[] = add_query_arg(urlencode_deep([$_taxonomy_query_var => $_post_term->slug]), $this->home_url.'/feed/'.urlencode($_feed_type).'/');
}
}
unset($_taxonomy, $_taxonomy_query_var, $_feed_type); // Housekeeping.
@@ -226,7 +226,7 @@ public function postTermFeedLinkVariations(\WP_Post $post, $include_regex_wildca
*/
public function convertVariationsToHostCachePathRegexFrags(array $variations)
{
- $regex_frags = array();
+ $regex_frags = [];
$is_multisite = is_multisite();
$can_consider_domain_mapping = $is_multisite && $this->plugin->canConsiderDomainMapping();
$flags = $this::CACHE_PATH_NO_SCHEME | $this::CACHE_PATH_NO_HOST // Default flags.
diff --git a/src/includes/classes/MenuPageOptions.php b/src/includes/classes/MenuPageOptions.php
index c3dfb1cd..3e8ca884 100644
--- a/src/includes/classes/MenuPageOptions.php
+++ b/src/includes/classes/MenuPageOptions.php
@@ -20,7 +20,7 @@ public function __construct()
global $is_nginx; // WP global for web server checks below.
echo '