first commit

This commit is contained in:
User A0264400
2026-04-01 23:20:16 +03:00
commit a766acdc90
23071 changed files with 4933189 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
<?php
/**
* Activator for the cyrlitera
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 09.03.2018, Webcraftic
* @see Wbcr_Factory480_Activator
* @version 1.0
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
class WCACHE_Activation extends Wbcr_Factory480_Activator {
/**
* Runs activation actions.
*
* @since 1.0.0
*/
public function activate()
{
require_once WCACHE_PLUGIN_DIR . '/includes/cache.php';
try {
WCL_Cache::activate();
} catch( Exception $e ) {
//nothing
}
}
public function deactivate()
{
require_once WCACHE_PLUGIN_DIR . '/includes/cache.php';
try {
WCL_Cache::deactivate();
} catch( Exception $e ) {
//nothing
}
}
}

View File

@@ -0,0 +1,238 @@
<?php
/**
* Clearfy quick start options
*
* @author Alex Kovalev <alex.kovalevv@gmail.com>
* @copyright (c) 03.06.2020, Webcraftic
* @version 1.0
*/
add_filter('wbcr/clearfy/adminbar_menu_items', function ($menu_items) {
$nonce = wp_create_nonce('wclearfy_cache_delete');
$menu_items['clearfy-clear-all-cache'] = [
'id' => 'clearfy-clear-all-cache',
'title' => '<span class="dashicons dashicons-update"></span> ' . __('Clear all cache', 'clearfy'),
'href' => esc_url(add_query_arg([
'wclearfy_cache_delete' => '1',
'_wpnonce' => $nonce
]))
];
return $menu_items;
});
add_filter("wbcr_clearfy_group_options", function ($options) {
$options[] = [
'name' => 'enable_cache',
'title' => __('Enable cache', 'clearfy'),
'tags' => ['optimize_performance']
];
$options[] = [
'name' => 'dont_cache_for_logged_in_users',
'title' => __('Don\'t cache for logged-in users', 'clearfy'),
'tags' => ['optimize_performance']
];
$options[] = [
'name' => 'cache_reject_uri',
'title' => __('Never Cache URL(s)', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'preload_cache',
'title' => __('Preload cache', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'clear_cache_for_newpost',
'title' => __('Clear cache for new post', 'clearfy'),
'tags' => ['optimize_performance']
];
$options[] = [
'name' => 'exclude_files',
'title' => __('Filenames that can be cached', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'exclude_pages',
'title' => __('Rejected User Agents', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'gzip',
'title' => __('Gzip', 'clearfy'),
'tags' => ['optimize_performance']
];
$options[] = [
'name' => 'browser_caching',
'title' => __('Browser Caching', 'clearfy'),
'tags' => ['optimize_performance']
];
$options[] = [
'name' => 'cache_mobile',
'title' => __('Mobile', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'cache_mobile_theme',
'title' => __('Create cache for mobile theme', 'clearfy'),
'tags' => []
];
$options[] = [
'name' => 'widget_cache',
'title' => __('Widget Cache', 'clearfy'),
'tags' => ['optimize_performance']
];
return $options;
});
add_action('wclearfy/setup_wizard/speed_optimize_step/continue_step', function () {
require_once WCACHE_PLUGIN_DIR . '/includes/helpers.php';
try {
\WCL_Cache_Helpers::modifyHtaccess();
} catch( \Exception $e ) {
}
});
add_filter('wclearfy/setup_wizard/speed_optimize_step/form_options', function ($options) {
array_unshift($options, [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'enable_cache',
'title' => __('Enable cache', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('This option enable cache to generates static html files from your dynamic WordPress blog. After a html file is generated your webserver will serve that file instead of processing the comparatively heavier and more expensive WordPress PHP scripts.', 'clearfy'),
'default' => true
], [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'gzip',
'title' => __('Gzip', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('Reduce the size of page decrease the page load time a lot. You can reduce the size of page with GZIP compression feature.
If the size of requested files are big, loading takes time so in this case there is needed to reduce the size of files. Gzip Compression feature compresses the pages and resources before sending so the transfer time is reduced.', 'clearfy'),
'default' => false
], [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'browser_caching',
'title' => __('Browser Caching', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('Reduce the load times of pages by storing commonly used files from your website on your visitors browser.
A browser loads the css, js, images resources to display the web page to the visitors. This process is always performed.
If the commonly used files are cached by browser, the visitors browsers do not have to load them evert time so the load times of pages are reduced.', 'clearfy'),
'default' => false
]);
return $options;
});
add_action('wclearfy/cache/settings_page/after_form_save', function () {
if( WCL_Cache_Helpers::is_nginx() && WCL_Plugin::app()->getPopulateOption('enable_cache') ) {
wp_redirect(WCL_Plugin::app()->getPluginPageUrl('clearfy_cache_nginx_rules'));
exit;
}
}, 10);
add_action('wbcr/factory/pages/impressive/print_all_notices', function ($plugin, $page) {
if( "clearfy_cache" === $page->id ) {
if( WCL_Cache_Helpers::is_nginx() && WCL_Plugin::app()->getPopulateOption('enable_cache') ) {
$button = '<br><a class="btn btn-default" href="' . WCL_Plugin::app()->getPluginPageUrl('clearfy_cache_nginx_rules') . '">NGINX configuration</a>';
$page->printWarningNotice("<p>" . __("Clearfy will work out of the box on NGINX servers. But if you want to get the best performance results, place the NGINX rules we generated in your server config. It enables NGINX to directly serve previously cached files without calling WordPress or any PHP. It also adds headers to cached CSS, JS, and images via browser cache.", 'wbcr_factory_pages_480') . "</p>" . $button);
}
}
}, 10, 2);
add_filter('wclearfy/cache/htaccess_rules', function ($htaccess) {
$gzip = WCL_Plugin::app()->getPopulateOption('gzip');
if( $gzip ) {
$data = "# BEGIN GzipWClearfyCache" . "\n" . "<IfModule mod_deflate.c>" . "\n" . "AddType x-font/woff .woff" . "\n" . "AddType x-font/ttf .ttf" . "\n" . "AddOutputFilterByType DEFLATE image/svg+xml" . "\n" . "AddOutputFilterByType DEFLATE text/plain" . "\n" . "AddOutputFilterByType DEFLATE text/html" . "\n" . "AddOutputFilterByType DEFLATE text/xml" . "\n" . "AddOutputFilterByType DEFLATE text/css" . "\n" . "AddOutputFilterByType DEFLATE text/javascript" . "\n" . "AddOutputFilterByType DEFLATE application/xml" . "\n" . "AddOutputFilterByType DEFLATE application/xhtml+xml" . "\n" . "AddOutputFilterByType DEFLATE application/rss+xml" . "\n" . "AddOutputFilterByType DEFLATE application/javascript" . "\n" . "AddOutputFilterByType DEFLATE application/x-javascript" . "\n" . "AddOutputFilterByType DEFLATE application/x-font-ttf" . "\n" . "AddOutputFilterByType DEFLATE x-font/ttf" . "\n" . "AddOutputFilterByType DEFLATE application/vnd.ms-fontobject" . "\n" . "AddOutputFilterByType DEFLATE font/opentype font/ttf font/eot font/otf" . "\n" . "</IfModule>" . "\n";
if( defined("WCLEARFY_GZIP_FOR_COMBINED_FILES") && WCLEARFY_GZIP_FOR_COMBINED_FILES ) {
$data = $data . "\n" . '<FilesMatch "\d+index\.(css|js)(\.gz)?$">' . "\n" . "# to zip the combined css and js files" . "\n\n" . "RewriteEngine On" . "\n" . "RewriteCond %{HTTP:Accept-encoding} gzip" . "\n" . "RewriteCond %{REQUEST_FILENAME}\.gz -s" . "\n" . "RewriteRule ^(.*)\.(css|js) $1\.$2\.gz [QSA]" . "\n\n" . "# to revent double gzip and give the correct mime-type" . "\n\n" . "RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1,E=FORCE_GZIP]" . "\n" . "RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1,E=FORCE_GZIP]" . "\n" . "Header set Content-Encoding gzip env=FORCE_GZIP" . "\n" . "</FilesMatch>" . "\n";
}
$data = $data . "# END GzipWClearfyCache" . "\n";
$htaccess = preg_replace("/\s*\#\s?BEGIN\s?GzipWClearfyCache.*?#\s?END\s?GzipWClearfyCache\s*/s", "", $htaccess);
return $data . $htaccess;
} else {
//delete gzip rules
$htaccess = preg_replace("/\s*\#\s?BEGIN\s?GzipWClearfyCache.*?#\s?END\s?GzipWClearfyCache\s*/s", "", $htaccess);
return $htaccess;
}
});
add_filter('wclearfy/cache/htaccess_rules', function ($htaccess) {
$browser_caching = WCL_Plugin::app()->getPopulateOption('browser_caching');
if( $browser_caching ) {
$data = "
# BEGIN LBCWClearfyCache
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault 'access plus 1 month'
ExpiresByType text/cache-manifest 'access plus 0 seconds'
ExpiresByType text/html 'access plus 0 seconds'
ExpiresByType text/xml 'access plus 0 seconds'
ExpiresByType application/xml 'access plus 0 seconds'
ExpiresByType application/json 'access plus 0 seconds'
ExpiresByType application/rss+xml 'access plus 1 hour'
ExpiresByType application/atom+xml 'access plus 1 hour'
ExpiresByType image/x-icon 'access plus 1 week'
ExpiresByType image/gif 'access plus 4 months'
ExpiresByType image/png 'access plus 4 months'
ExpiresByType image/jpeg 'access plus 4 months'
ExpiresByType image/webp 'access plus 4 months'
ExpiresByType video/ogg 'access plus 4 months'
ExpiresByType audio/ogg 'access plus 4 months'
ExpiresByType video/mp4 'access plus 4 months'
ExpiresByType video/webm 'access plus 4 months'
ExpiresByType text/x-component 'access plus 1 month'
ExpiresByType font/ttf 'access plus 4 months'
ExpiresByType font/otf 'access plus 4 months'
ExpiresByType font/woff 'access plus 4 months'
ExpiresByType font/woff2 'access plus 4 months'
ExpiresByType image/svg+xml 'access plus 1 month'
ExpiresByType application/vnd.ms-fontobject 'access plus 1 month'
ExpiresByType text/css 'access plus 1 year'
ExpiresByType application/javascript 'access plus 1 year'
</IfModule>
# END LBCWClearfyCache";
if( !preg_match("/BEGIN\s*LBCWClearfyCache/", $htaccess) ) {
return $data . $htaccess;
} else {
return $htaccess;
}
} else {
//delete levere browser caching
$htaccess = preg_replace("/#\s?BEGIN\s?LBCWClearfyCache.*?#\s?END\s?LBCWClearfyCache/s", "", $htaccess);
return $htaccess;
}
});
//add_action('wfactory/activated_' . WCL_Plugin::app()->getPluginName() . '_component', function ($component_name) {
//todo: Проверить совместимость с плагинами, включить или отключить компонент в зависимсти от результатов
//});

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,221 @@
<?php
/**
* The page Settings.
*
* @since 1.0.0
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! class_exists( 'WBCR\Factory_Templates_134\Pages\PageBase' ) ) {
return;
}
class WCL_CacheProNginxRulesPage extends WBCR\Factory_Templates_134\Pages\PageBase {
/**
* The id of the page in the admin menu.
*
* Mainly used to navigate between pages.
*
* @see FactoryPages480_AdminPage
*
* @since 1.0.0
* @var string
*/
public $id = "clearfy_cache_nginx_rules";
/**
* @var string
*/
public $page_parent_page = "none";
/**
* @var string
*/
public $page_menu_dashicon = 'dashicons-clock';
/**
* @var bool
*/
//public $internal = false;
/**
* @var string
*/
public $type = 'page';
public $available_for_multisite = true;
/**
* Show on the page a search form for search options of plugin?
*
* @since 2.2.0 - Added
* @var bool - true show, false hide
*/
public $show_search_options_form = false;
/**
* @param WCL_Plugin $plugin
*/
public function __construct(WCL_Plugin $plugin)
{
$this->menu_title = __('Nginx Rules', 'clearfy');
parent::__construct($plugin);
$this->plugin = $plugin;
}
public function getPageTitle()
{
return __('Nginx Rules', 'clearfy');
}
public function showPageContent()
{
?>
<div class="form-group">
<h2><?php
_e('Nginx Configuration Rules', 'clearfy') ?></h2>
<p>
<?php
_e('It enables NGINX to directly serve previously cached files without calling WordPress or any PHP. It also adds headers to cached CSS, JS, and images via browser cache.', 'clearfy') ?>
</p>
<p>
<?php
_e('Unfortunately, our plugin does not have the ability to automatically configure the nginx server. You have to copy the rules below and paste into your server config file.', 'clearfy') ?>
</p>
<p>
<?php
_e('Copy and paste the following code snippet in the server { } block of “default” file (or whatever the file is being used) located in /etc/nginx/sites-enabled/. Make sure to remove the existing location / { } block before using the one in the following code snippet.', 'clearfy') ?>
</p>
<div class="control-group">
<textarea row="50" cols="100" style="height: 500px;">
<?php
echo $this->generate_base_nginx_rules();
echo $this->generate_browser_cache_rules();
echo $this->generate_gzip_rules();
?>
</textarea>
</div>
</div>
<?php
}
protected function generate_base_nginx_rules()
{
$rules = "
#####
#CLEARFY CACHE RULES
#
set \$clearfy_bypass 1; # Should NGINX bypass WordPress and call cache file directly ?
set \$condition '';
# Do not bypass if it's a POST request
if (\$request_method = POST) {
set \$clearfy_bypass 0;
set \$clearfy_reason \"POST request\";
set \$condition \"null\";
}
# Do not bypass if arguments are found (e.g. ?page=2)
if (\$is_args) {
set \$clearfy_bypass 0;
set \$clerfy_reason \"Arguments found\";
set \$condition \"null\";
}
# Do not bypass if the site is in maintenance mode
if (-f \"\$document_root/.maintenance\") {
set \$clearfy_bypass 0;
set \$clearfy_reason \"Maintenance mode\";
set \$condition \"null\";
}
# Do not bypass if one of those cookie if found
# wordpress_logged_in_[hash] : When a user is logged in, this cookie is created (we'd rather let WP-Rocket handle that)
# wp-postpass_[hash] : When a protected post requires a password, this cookie is created.
if (\$http_cookie ~* \"(wordpress_logged_in_|wp\-postpass_|woocommerce_items_in_cart|woocommerce_cart_hash|wptouch_switch_toogle|comment_author_|comment_author_email_)\") {
set \$clearfy_bypass 0;
set \$clearfy_reason \"Cookie\";
set \$condition \"null\";
}
set \$fullurl '/wp-content/cache/all\${condition}';
#CACHE ENDING
location / {
set \$serve_url \$fullurl\${uri}index.html;
add_header X-Clearfy-Cache-Location \$serve_URL;
try_files \$serve_url \$uri \$uri/ /index.php\$is_args\$args;
}
# Debug header (when file is not cached)
add_header X-Clearfy-Nginx-Serving-Static \$clearfy_is_bypassed;
add_header X-Clearfy-Nginx-Reason \$clearfy_reason;
add_header X-Clearfy-Nginx-File \$clearfy_file;
";
return $rules;
}
private function generate_gzip_rules()
{
$rules = '
#####
# BROWSER CSS CACHE
#
location ~ /wp-content/cache/all/.*html$ {
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types image/svg+xml text/plain text/html text/xml text/css text/javascript application/xml application/xhtml+xml application/rss+xml application/javascript application/x-javascript application/x-font-ttf application/vnd.ms-fontobject font/opentype font/ttf font/eot font/otf;
}
';
return $rules;
}
private function generate_browser_cache_rules()
{
$rules = '
#####
# BROWSER CSS CACHE
#
location ~* \.css$ {
etag on;
gzip_vary on;
expires 30d;
}';
$rules .= '
####
# BROWSER JS CACHE
#
location ~* \.js$ {
etag on;
gzip_vary on;
expires 30d;
}';
$rules .= '
####
# BROWSER MEDIA CACHE
#
location ~* \.(ico|gif|jpe?g|png|svg|eot|otf|woff|woff2|ttf|ogg)$ {
etag on;
expires 30d;
}';
return $rules;
}
}

View File

@@ -0,0 +1,328 @@
<?php
/**
* The page Settings.
*
* @since 1.0.0
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
class WCACHE_CachePage extends WBCR\Factory_Templates_134\Pages\PageBase {
/**
* @see {@inheritDoc}
*
* @var string
*/
public $id = "clearfy_cache";
/**
* @var string
*/
public $page_parent_page = 'performance';
/**
* @see {@inheritDoc}
*
* @var string
*/
public $page_menu_dashicon = 'dashicons-performance';
/**
* @see {@inheritDoc}
*
* @var int
*/
public $page_menu_position = 20;
/**
* @see {@inheritDoc}
*
* @var bool
*/
//public $available_for_multisite = true;
protected $errors = [
98 => "<label>.htaccess was not found</label> <a target='_blank' href='http://www.wpfastestcache.com/warnings/htaccess-was-not-found/'>Read More</a>",
99 => "define('WP_CACHE', true); is needed to be added into wp-config.php",
100 => "You have to set <strong><u><a href=" . "'/wp-admin/options-permalink.php'>permalinks</a></u></strong>",
101 => "Fast Velocity Minify needs to be deactivated",
102 => 'Far Future Expiration Plugin needs to be deactivated',
103 => "SG Optimizer needs to be deactived",
104 => "AdRotate needs to be deactived",
105 => "MobilePress needs to be deactived",
106 => "Speed Booster Pack needs to be deactived",
107 => "WP Performance Score Booster needs to be deactivated<br>This plugin has aldready Gzip, Leverage Browser Caching features",
109 => "Check and Enable GZIP compression needs to be deactivated<br>This plugin has aldready Gzip feature",
110 => "GZippy needs to be deactivated<br>This plugin has aldready Gzip feature",
111 => "GZip Ninja Speed Compression needs to be deactivated<br>This plugin has aldready Gzip feature",
112 => "WordPress Gzip Compression needs to be deactivated<br>This plugin has aldready Gzip feature",
113 => "GZIP Output needs to be deactivated<br>This plugin has aldready Gzip feature",
114 => "Head Cleaner needs to be deactivated",
115 => "Far Future Expiration Plugin needs to be deactivated",
];
/**
* @param WCL_Plugin $plugin
*/
public function __construct(WCL_Plugin $plugin)
{
$this->menu_title = __('Cache', 'clearfy');
$this->page_menu_short_description = __('Cache pages', 'clearfy');
if( $plugin->premium->is_activate() && $plugin->premium->is_install_package() ) {
$this->available_for_multisite = true;
}
parent::__construct($plugin);
$this->plugin = $plugin;
}
/**
* We register notifications for some actions
*
* @param $notices
* @param \Wbcr_Factory480_Plugin $plugin
*
* @return array
* @see libs\factory\pages\themplates\FactoryPages480_ImpressiveThemplate
*/
public function getActionNotices($notices)
{
$notices[] = [
'conditions' => [
'wclearfy-cache-cleared' => 1
],
'type' => 'success',
'message' => 'Cache has been cleared!'
];
foreach($this->errors as $key => $error_message) {
$notices[] = [
'conditions' => [
'wclearfy-cache-error' => $key
],
'type' => 'danger',
'message' => $error_message
];
}
return $notices;
}
/**
* Permalinks options.
*
* @return mixed[]
* @since 1.0.0
*/
public function getPageOptions()
{
$options = [];
$options[] = [
'type' => 'html',
'html' => '<div class="wbcr-factory-page-group-header">' . __('<strong>Cache settings</strong>', 'clearfy') . '<p>' . __('A very fast caching engine for WordPress that produces static html files. You can configure caching in this section.', 'clearfy') . '</p></div>'
];
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'enable_cache',
'title' => __('Enable cache', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('This option enable cache to generates static html files from your dynamic WordPress blog. After a html file is generated your webserver will serve that file instead of processing the comparatively heavier and more expensive WordPress PHP scripts.', 'clearfy'),
'default' => false
];
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'dont_cache_for_logged_in_users',
'title' => __('Don\'t cache for logged-in users', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('Don\'t show the cached version for logged-in users', 'clearfy'),
'default' => false
];
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'gzip',
'title' => __('Gzip', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('Reduce the size of page decrease the page load time a lot. You can reduce the size of page with GZIP compression feature.
If the size of requested files are big, loading takes time so in this case there is needed to reduce the size of files. Gzip Compression feature compresses the pages and resources before sending so the transfer time is reduced.', 'clearfy'),
'default' => false
];
$options[] = [
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'browser_caching',
'title' => __('Browser Caching', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'green'],
'hint' => __('Reduce the load times of pages by storing commonly used files from your website on your visitors browser.
A browser loads the css, js, images resources to display the web page to the visitors. This process is always performed.
If the commonly used files are cached by browser, the visitors browsers do not have to load them evert time so the load times of pages are reduced.', 'clearfy'),
'default' => false
];
$options[] = [
'type' => 'textarea',
'name' => 'cache_reject_uri',
'title' => __('Never Cache URL(s)', 'clearfy'),
//'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Specify URLs of pages or posts that should never be cached (one per line). The domain part of the URL will be stripped automatically.
Use (.*) wildcards to address multiple URLs under a given path.', 'clearfy'),
];
$options[] = [
'type' => 'textarea',
'name' => 'cache_reject_user_agents',
'title' => __('Rejected User Agents', 'clearfy'),
'default' => "facebookexternalhit\nTwitterbot\nLinkedInBot\nWhatsApp\nMediatoolkitbot",
//'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Strings in the HTTP User Agent header that prevent WP-Cache from caching bot, spiders, and crawlers requests. Note that super cached files are still sent to these agents if they already exists.', 'clearfy'),
];
$options[] = [
'type' => 'textarea',
'name' => 'cache_reject_cookies',
'title' => __('Rejected Cookies', 'clearfy'),
//'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Do not cache pages when these cookies are set. Add the cookie names here, one per line. Matches on fragments, so "test" will match "WordPress_test_cookie". (Simple caching only)', 'clearfy'),
];
$options[] = [
'type' => 'more-link',
'name' => 'cache-group',
'title' => __('Advanced options', 'clearfy'),
'count' => 8,
'items' => [
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'cache_mobile',
'title' => __('Mobile', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __("Don't show the cached version for desktop to mobile devices", 'clearfy'),
'default' => false
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'cache_mobile_theme',
'title' => __('Create cache for mobile theme', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('If you use a mobile theme, you should enable both “Mobile” and “Create cache for mobile theme” options. If you use a responsive theme, no need to use the mobile cache feature. You should disable “Mobile” and “Create cache for mobile theme” options.', 'clearfy'),
'default' => false,
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'widget_cache',
'title' => __('Widget Cache', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('You can reduce the number of sql queries with this feature.
When “Cache System” is enabled, the page is saved as a static html file, thus PHP and MySQL does not work for the page which has been cached. MySQL and PHP work to generate the html of the other pages which have not been cached yet.
Every time before the cache is created, the same widgets are generated again and again. This feature avoids generating the widgets again and again to reduce the sql queries.', 'clearfy'),
'default' => true,
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'preload_cache',
'title' => __('Preload cache', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('The preload feature stars to work after delete cache.
When the Preload feature calls the urls, the cache of urls are created automatically. When all the pages are cached, the preload stops working. When the cache is clear, it starts working again.
The Preload runs every 5 minutes. If you want set a specific interval. Note: The preload feature works with the WP_CRON system.', 'clearfy'),
'default' => false
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'clear_cache_for_newpost',
'title' => __('Clear cache for new post', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Clear cache files when a post or page is published', 'clearfy'),
'default' => true
],
[
'type' => 'checkbox',
'way' => 'buttons',
'name' => 'clear_cache_for_updated_post',
'title' => __('Clear cache for updated Post', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Clear cache files when a post or page is updated', 'clearfy'),
'default' => true
],
[
'type' => 'textarea',
'name' => 'exclude_files',
'title' => __('Filenames that can be cached', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Add here those filenames that can be cached, even if they match one of the rejected substring specified above.', 'clearfy'),
'default' => 'wp-comments-popup.php
wp-links-opml.php
wp-locations.php
'
],
[
'type' => 'textarea',
'name' => 'exclude_pages',
'title' => __('Rejected User Agents', 'clearfy'),
'layout' => ['hint-type' => 'icon', 'hint-icon-color' => 'grey'],
'hint' => __('Strings in the HTTP User Agent header that prevent WP-Cache from caching bot, spiders, and crawlers requests. Note that super cached files are still sent to these agents if they already exists.', 'clearfy'),
'default' => 'bot
ia_archive
slurp
crawl
spider
Yandex
'
]
]
];
$form_options = [];
$form_options[] = [
'type' => 'form-group',
'items' => $options,
//'cssClass' => 'postbox'
];
return apply_filters('wclearfy_cache_form_options', $form_options, $this);
}
public function afterFormSave()
{
try {
do_action("wclearfy/cache/settings_page/after_form_save");
WCL_Cache_Helpers::modifyHtaccess();
} catch( Exception $e ) {
if( !empty($e->getCode()) && isset($this->errors[$e->getCode()]) ) {
$this->redirectToAction('index', ['wclearfy-cache-error' => $e->getCode()]);
}
}
}
}

View File

@@ -0,0 +1,40 @@
<?php
/**
* Plugin Name: Webcraftic Clearfy Cache
* Plugin URI: https://webcraftic.com
* Description: Webcraftic Clearfy Cache
* Author: Webcraftic <wordpress.webraftic@gmail.com>
* Version: 1.0.3
* Text Domain: clearfy_cache
* Domain Path: /languages/
* Author URI: https://webcraftic.com
* Framework Version: FACTORY_480_VERSION
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* Developers who contributions in the development plugin:
*
* Alexander Kovalev
* ---------------------------------------------------------------------------------
* Full plugin development.
*
* Email: alex.kovalevv@gmail.com
* Personal card: https://alexkovalevv.github.io
* Personal repo: https://github.com/alexkovalevv
* ---------------------------------------------------------------------------------
*/
/**
* -----------------------------------------------------------------------------
* CHECK REQUIREMENTS
* Check compatibility with php and wp version of the user's site. As well as checking
* compatibility with other plugins from Webcraftic.
* -----------------------------------------------------------------------------
*/
//todo: Fill the file if need release alone plugin

View File

@@ -0,0 +1,52 @@
<?php
/**
* Этот файл инициализирует этот плагин, как аддон для плагина Clearfy.
*
* Файл будет подключен только в плагине Clearfy, используя особый вариант загрузки. Это более простое решение
* пришло на смену встроенной системы подключения аддонов в фреймворке.
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2018 Webraftic Ltd
*/
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
if( !defined('WCACHE_PLUGIN_ACTIVE') ) {
define('WCACHE_PLUGIN_VERSION', '1.0.3');
define('WCACHE_TEXT_DOMAIN', 'clearfy_cache');
define('WCACHE_PLUGIN_ACTIVE', true);
// Этот плагин загружен, как аддон для плагина Clearfy
define('LOADING_CLEARFY_CACHE_AS_ADDON', true);
if( !defined('WCACHE_PLUGIN_DIR') ) {
define('WCACHE_PLUGIN_DIR', dirname(__FILE__));
}
if( !defined('WCACHE_PLUGIN_BASE') ) {
define('WCACHE_PLUGIN_BASE', plugin_basename(__FILE__));
}
if( !defined('WCACHE_PLUGIN_URL') ) {
define('WCACHE_PLUGIN_URL', plugins_url('', __FILE__));
}
try {
// Global scripts
require_once(WCACHE_PLUGIN_DIR . '/includes/3rd-party/class-clearfy-plugin.php');
new WCACHE_Plugin();
} catch( Exception $e ) {
$wcache_plugin_error_func = function () use ($e) {
$error = sprintf("The %s plugin has stopped. <b>Error:</b> %s Code: %s", 'Webcraftic Clearfy Cache', $e->getMessage(), $e->getCode());
echo '<div class="notice notice-error"><p>' . $error . '</p></div>';
};
add_action('admin_notices', $wcache_plugin_error_func);
add_action('network_admin_notices', $wcache_plugin_error_func);
}
}

View File

@@ -0,0 +1,135 @@
<?php
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* Clearfy cache
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 2018 Webraftic Ltd
* @version 1.0
*/
class WCACHE_Plugin {
/**
* @see self::app()
* @var WCL_Plugin
*/
private static $app;
/**
* Конструктор
*
* Применяет конструктор родительского класса и записывает экземпляр текущего класса в свойство $app.
* Подробнее о свойстве $app см. self::app()
*
* @param string $plugin_path
* @param array $data
*
* @throws Exception
*/
public function __construct()
{
if( !class_exists('WCL_Plugin') ) {
throw new Exception('Plugin Clearfy is not installed!');
}
self::$app = WCL_Plugin::app();
$this->global_scripts();
if( is_admin() ) {
$this->admin_scripts();
}
// Wordpress 6.7 fix
add_action( 'init', function () {
if ( is_admin() ) {
$this->register_pages();
}
} );
}
/**
* Статический метод для быстрого доступа к интерфейсу плагина.
*
* Позволяет разработчику глобально получить доступ к экземпляру класса плагина в любом месте
* плагина, но при этом разработчик не может вносить изменения в основной класс плагина.
*
* Используется для получения настроек плагина, информации о плагине, для доступа к вспомогательным
* классам.
*
* @return WCL_Plugin
*/
public static function app()
{
return self::$app;
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.0
*/
protected function init_activation()
{
include_once(WCACHE_PLUGIN_DIR . '/admin/activation.php');
self::app()->registerActivation('WCACHE_Activation');
}
/**
* @throws \Exception
* @since 1.0.0
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function register_pages()
{
self::app()->registerPage('WCACHE_CachePage', WCACHE_PLUGIN_DIR . '/admin/pages/class-pages-performance-cache.php');
self::app()->registerPage('WCL_CacheProNginxRulesPage', WCACHE_PLUGIN_DIR . '/admin/pages/class-pages-nginx-rules.php');
}
/**
* @throws \Exception
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function admin_scripts()
{
require(WCACHE_PLUGIN_DIR . '/admin/boot.php');
$this->init_activation();
}
private function global_scripts()
{
require_once WCACHE_PLUGIN_DIR . '/includes/helpers.php';
require_once WCACHE_PLUGIN_DIR . '/includes/cache.php';
if( self::app()->getPopulateOption('enable_cache') ) {
if( self::app()->getPopulateOption('widget_cache') ) {
require_once WCACHE_PLUGIN_DIR . "/includes/widget-cache.php";
WCL_WidgetCache::action();
}
}
if( self::app()->getPopulateOption('cache_mobile_theme') ) {
require_once WCACHE_PLUGIN_DIR . '/includes/mobile-cache.php';
}
add_filter('wbcr/clearfy/adminbar_menu_items', function ($menu_items) {
$nonce = wp_create_nonce('wclearfy_cache_delete');
$menu_items['clearfy-clear-all-cache'] = [
'id' => 'clearfy-clear-all-cache',
'title' => '<span class="dashicons dashicons-update"></span> ' . __('Clear all cache', 'clearfy'),
'href' => esc_url(add_query_arg([
'wclearfy_cache_delete' => '1',
'_wpnonce' => $nonce
]))
];
return $menu_items;
});
}
}

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,100 @@
<?php
require_once WCACHE_PLUGIN_DIR . '/includes/helpers.php';
require_once WCACHE_PLUGIN_DIR . '/includes/create-cache.php';
class WCL_Cache {
public function __construct()
{
add_action('transition_post_status', array($this, 'on_all_status_transitions'), 10, 3);
add_action('init', function () {
if (current_user_can('manage_options') && isset($_GET['wclearfy_cache_delete'])) {
check_admin_referer('wclearfy_cache_delete_action');
WCL_Cache_Helpers::deleteCache();
wp_redirect(esc_url_raw(remove_query_arg(['wclearfy_cache_delete', '_wpnonce'])));
die();
}
});
if( !is_admin() ) {
if( isset($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] ) {
$cache = new WCL_Create_Cache();
$cache->createCache();
}
}
}
public function on_all_status_transitions($new_status, $old_status, $post)
{
if( !WCL_Plugin::app()->getPopulateOption('enable_cache') ) {
return false;
}
if( !wp_is_post_revision($post->ID) ) {
if( isset($post->post_type) ) {
if( $post->post_type == "nf_sub" ) {
return false;
}
}
if( WCL_Plugin::app()->getPopulateOption('clear_cache_for_newpost') ) {
if( $new_status == "publish" && $old_status != "publish" ) {
WCL_Cache_Helpers::deleteHomePageCache();
//to clear category cache and tag cache
WCL_Cache_Helpers::singleDeleteCache(false, $post->ID);
//to clear widget cache
WCL_Cache_Helpers::deleteWidgetCache();
}
}
if( WCL_Plugin::app()->getPopulateOption('clear_cache_for_updated_post') ) {
if( $new_status == "publish" && $old_status == "publish" ) {
WCL_Cache_Helpers::singleDeleteCache(false, $post->ID);
//to clear widget cache
WCL_Cache_Helpers::deleteWidgetCache();
}
}
if( $new_status == "trash" && $old_status == "publish" ) {
WCL_Cache_Helpers::singleDeleteCache(false, $post->ID);
} else if( ($new_status == "draft" || $new_status == "pending" || $new_status == "private") && $old_status == "publish" ) {
WCL_Cache_Helpers::deleteCache();
}
}
}
public static function activate()
{
if( WCL_Plugin::app()->getPopulateOption('enable_cache') ) {
WCL_Cache_Helpers::modifyHtaccess();
}
}
public static function deactivate()
{
$path = ABSPATH;
if( WCL_Cache_Helpers::is_subdirectory_install() ) {
$path = WCL_Cache_Helpers::getABSPATH();
}
if( is_file($path . ".htaccess") && is_writable($path . ".htaccess") ) {
$htaccess = file_get_contents($path . ".htaccess");
$htaccess = preg_replace("/#\s?BEGIN\s?WClearfyCache.*?#\s?END\s?WClearfyCache/s", "", $htaccess);
$htaccess = preg_replace("/#\s?BEGIN\s?GzipWClearfyCache.*?#\s?END\s?GzipWClearfyCache/s", "", $htaccess);
$htaccess = preg_replace("/#\s?BEGIN\s?LBCWClearfyCache.*?#\s?END\s?LBCWClearfyCache/s", "", $htaccess);
$htaccess = preg_replace("/#\s?BEGIN\s?WEBPWClearfyCache.*?#\s?END\s?WEBPWClearfyCache/s", "", $htaccess);
@file_put_contents($path . ".htaccess", $htaccess);
}
//$wclearfy->deleteCache();
}
}
new WCL_Cache();

View File

@@ -0,0 +1,132 @@
<?php
// Exit if accessed directly
if( !defined('ABSPATH') ) {
exit;
}
/**
* Transliteration core class
*
* @author Alexander Kovalev <alex.kovalevv@gmail.com>, Github: https://github.com/alexkovalevv
* @copyright (c) 19.02.2018, Webcraftic
*/
class WCACHE_Plugin extends Wbcr_Factory480_Plugin {
/**
* @see self::app()
* @var Wbcr_Factory480_Plugin
*/
private static $app;
/**
* @since 1.1.0
* @var array
*/
private $plugin_data;
/**
* Конструктор
*
* Применяет конструктор родительского класса и записывает экземпляр текущего класса в свойство $app.
* Подробнее о свойстве $app см. self::app()
*
* @param string $plugin_path
* @param array $data
*
* @throws Exception
*/
public function __construct($plugin_path, $data)
{
parent::__construct($plugin_path, $data);
self::$app = $this;
$this->plugin_data = $data;
$this->global_scripts();
if( is_admin() ) {
$this->admin_scripts();
}
// Wordpress 6.7 fix
add_action( 'init', function () {
if ( is_admin() ) {
$this->register_pages();
}
} );
}
/**
* Статический метод для быстрого доступа к интерфейсу плагина.
*
* Позволяет разработчику глобально получить доступ к экземпляру класса плагина в любом месте
* плагина, но при этом разработчик не может вносить изменения в основной класс плагина.
*
* Используется для получения настроек плагина, информации о плагине, для доступа к вспомогательным
* классам.
*
* @return \Wbcr_Factory480_Plugin|\WCTR_Plugin
*/
public static function app()
{
return self::$app;
}
/**
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
* @since 1.0.0
*/
protected function init_activation()
{
include_once(WCACHE_PLUGIN_DIR . '/admin/activation.php');
self::app()->registerActivation('WCACHE_Activation');
}
/**
* @throws \Exception
* @since 1.0.0
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function register_pages()
{
$this->registerPage('WCACHE_CachePage', WCACHE_PLUGIN_DIR . '/admin/pages/class-pages-performance-cache.php');
}
/**
* @throws \Exception
* @author Alexander Kovalev <alex.kovalevv@gmail.com>
*/
private function admin_scripts()
{
$this->init_activation();
}
private function global_scripts()
{
require_once WCACHE_PLUGIN_DIR . '/helpers.php';
require_once WCACHE_PLUGIN_DIR . '/includes/cache.php';
if( is_admin() ) {
require(WCACHE_PLUGIN_DIR . '/admin/boot.php');
if( class_exists('WCL_CachePage') ) {
WCL_Plugin::app()->registerPage('WCL_CacheProPage', WCACHE_PLUGIN_DIR . '/admin/pages/class-pages-cache.php');
}
}
add_filter('wbcr/clearfy/adminbar_menu_items', function ($menu_items) {
$nonce = wp_create_nonce('wclearfy_cache_delete');
$menu_items['clearfy-clear-all-cache'] = [
'id' => 'clearfy-clear-all-cache',
'title' => '<span class="dashicons dashicons-update"></span> ' . __('Clear all cache', 'clearfy'),
'href' => esc_url(add_query_arg([
'wclearfy_cache_delete' => '1',
'_wpnonce' => $nonce
]))
];
return $menu_items;
});
}
}

View File

@@ -0,0 +1,921 @@
<?php
class WCL_Create_Cache {
public $options = [];
public $cdn;
private $startTime;
private $blockCache = false;
private $err = "";
public $cacheFilePath = "";
public $exclude_rules = false;
public $preload_user_agent = false;
public $current_page_type = false;
public $current_page_content_type = false;
public $exclude_current_page_text = false;
public function __construct()
{
//to fix: PHP Notice: Undefined index: HTTP_USER_AGENT
$_SERVER['HTTP_USER_AGENT'] = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] ? strip_tags($_SERVER['HTTP_USER_AGENT']) : "Empty User Agent";
if( preg_match("/(WP\sFastest\sCache\sPreload(\siPhone\sMobile)?\s*Bot)/", $_SERVER['HTTP_USER_AGENT']) ) {
$this->preload_user_agent = true;
} else {
$this->preload_user_agent = false;
}
//$this->set_cdn();
$this->set_cache_file_path();
}
public function detect_current_page_type()
{
if( preg_match("/\?/", $_SERVER["REQUEST_URI"]) ) {
return true;
}
if( preg_match("/^\/wp-json/", $_SERVER["REQUEST_URI"]) ) {
return true;
}
if( is_front_page() ) {
echo "<!--WCLEARFY_PAGE_TYPE_homepage-->";
} else if( is_category() ) {
echo "<!--WCLEARFY_PAGE_TYPE_category-->";
} else if( is_tag() ) {
echo "<!--WCLEARFY_PAGE_TYPE_tag-->";
} else if( is_singular('post') ) {
echo "<!--WCLEARFY_PAGE_TYPE_post-->";
} else if( is_page() ) {
echo "<!--WCLEARFY_PAGE_TYPE_page-->";
} else if( is_attachment() ) {
echo "<!--WCLEARFY_PAGE_TYPE_attachment-->";
} else if( is_archive() ) {
echo "<!--WCLEARFY_PAGE_TYPE_archive-->";
}
}
public function set_exclude_rules()
{
if( $json_data = get_option("WClearfyCacheExclude") ) {
$this->exclude_rules = json_decode($json_data);
}
}
public function set_cache_file_path()
{
$type = "all";
if( WCL_Cache_Helpers::isMobile() && WCL_Plugin::app()->getPopulateOption('cache_mobile') ) {
if( class_exists("WCL_MobileCache") && WCL_Plugin::app()->getPopulateOption('cache_mobile_theme') ) {
$type = "wclearfy-mobile-cache";
}
}
if( WCL_Cache_Helpers::isPluginActive('gtranslate/gtranslate.php') ) {
if( isset($_SERVER["HTTP_X_GT_LANG"]) ) {
$this->cacheFilePath = WCL_Cache_Helpers::getWpContentDir("/cache/" . $type . "/") . $_SERVER["HTTP_X_GT_LANG"] . $_SERVER["REQUEST_URI"];
} else if( isset($_SERVER["REDIRECT_URL"]) && $_SERVER["REDIRECT_URL"] != "/index.php" ) {
$this->cacheFilePath = WCL_Cache_Helpers::getWpContentDir("/cache/" . $type . "/") . $_SERVER["REDIRECT_URL"];
} else if( isset($_SERVER["REQUEST_URI"]) ) {
$this->cacheFilePath = WCL_Cache_Helpers::getWpContentDir("/cache/" . $type . "/") . $_SERVER["REQUEST_URI"];
}
} else {
$this->cacheFilePath = WCL_Cache_Helpers::getWpContentDir("/cache/" . $type . "/") . $_SERVER["REQUEST_URI"];
// for /?s=
$this->cacheFilePath = preg_replace("/(\/\?s\=)/", "$1/", $this->cacheFilePath);
}
$this->cacheFilePath = $this->cacheFilePath ? rtrim($this->cacheFilePath, "/") . "/" : "";
$this->cacheFilePath = preg_replace("/\/cache\/(all|wclearfy-mobile-cache)\/\//", "/cache/$1/", $this->cacheFilePath);
if( strlen($_SERVER["REQUEST_URI"]) > 1 ) { // for the sub-pages
if( !preg_match("/\.html/i", $_SERVER["REQUEST_URI"]) ) {
if( WCL_Cache_Helpers::is_trailing_slash() ) {
if( !preg_match("/\/$/", $_SERVER["REQUEST_URI"]) ) {
if( defined('WCACHE_QUERYSTRING') && WCACHE_QUERYSTRING ) {
} else if( preg_match("/gclid\=/i", $this->cacheFilePath) ) {
} else if( preg_match("/fbclid\=/i", $this->cacheFilePath) ) {
} else if( preg_match("/utm_(source|medium|campaign|content|term)/i", $this->cacheFilePath) ) {
} else {
$this->cacheFilePath = false;
}
}
} else {
//toDo
}
}
}
$this->remove_url_paramters();
// to decode path if it is not utf-8
if( $this->cacheFilePath ) {
$this->cacheFilePath = urldecode($this->cacheFilePath);
}
// for security
if( preg_match("/\.{2,}/", $this->cacheFilePath) ) {
$this->cacheFilePath = false;
}
if( WCL_Cache_Helpers::isMobile() ) {
if( WCL_Plugin::app()->getPopulateOption('cache_mobile') ) {
if( !class_exists("WCL_MobileCache") ) {
$this->cacheFilePath = false;
} else {
if( !WCL_Plugin::app()->getPopulateOption('cache_mobile_theme') ) {
$this->cacheFilePath = false;
}
}
}
}
}
public function remove_url_paramters()
{
$action = false;
//to remove query strings for cache if Google Click Identifier are set
if( preg_match("/gclid\=/i", $this->cacheFilePath) ) {
$action = true;
}
//to remove query strings for cache if facebook parameters are set
if( preg_match("/fbclid\=/i", $this->cacheFilePath) ) {
$action = true;
}
//to remove query strings for cache if google analytics parameters are set
if( preg_match("/utm_(source|medium|campaign|content|term)/i", $this->cacheFilePath) ) {
$action = true;
}
if( $action ) {
if( strlen($_SERVER["REQUEST_URI"]) > 1 ) { // for the sub-pages
$this->cacheFilePath = preg_replace("/\/*\?.+/", "", $this->cacheFilePath);
$this->cacheFilePath = $this->cacheFilePath . "/";
define('WCACHE_QUERYSTRING', true);
}
}
}
public function set_cdn()
{
$cdn_values = get_option("WClearfyCacheCDN");
if( $cdn_values ) {
$std_obj = json_decode($cdn_values);
$arr = [];
if( is_array($std_obj) ) {
$arr = $std_obj;
} else {
array_push($arr, $std_obj);
}
foreach($arr as $key => &$std) {
$std->originurl = trim($std->originurl);
$std->originurl = trim($std->originurl, "/");
$std->originurl = preg_replace("/http(s?)\:\/\/(www\.)?/i", "", $std->originurl);
$std->cdnurl = trim($std->cdnurl);
$std->cdnurl = trim($std->cdnurl, "/");
if( !preg_match("/https\:\/\//", $std->cdnurl) ) {
$std->cdnurl = "//" . preg_replace("/http(s?)\:\/\/(www\.)?/i", "", $std->cdnurl);
}
}
$this->cdn = $arr;
}
}
public function checkShortCode($content)
{
if( preg_match("/\[wclearfyNOT\]/", $content) ) {
if( !is_home() || !is_archive() ) {
$this->blockCache = true;
}
$content = str_replace("[wclearfyNOT]", "", $content);
}
return $content;
}
public function createCache()
{
if( !WCL_Plugin::app()->getPopulateOption('enable_cache') ) {
return 0;
}
// to exclude static pdf files
if( preg_match("/\.pdf$/i", $_SERVER["REQUEST_URI"]) ) {
return 0;
}
// to check logged-in user
if( WCL_Plugin::app()->getPopulateOption('dont_cache_for_logged_in_users') ) {
foreach((array)$_COOKIE as $cookie_key => $cookie_value) {
if( preg_match("/wordpress_logged_in/i", $cookie_key) ) {
ob_start([$this, "cdn_rewrite"]);
return 0;
}
}
}
// to exclude admin users
foreach((array)$_COOKIE as $cookie_key => $cookie_value) {
if( preg_match("/wordpress_logged_in/i", $cookie_key) ) {
$users_groups = get_users(["role" => "administrator", "fields" => ["user_login"]]);
foreach($users_groups as $user_key => $user_value) {
if( preg_match("/^" . preg_quote($user_value->user_login, "/") . "/", $cookie_value) ) {
ob_start([$this, "cdn_rewrite"]);
return 0;
}
}
}
}
// to check comment author
foreach((array)$_COOKIE as $cookie_key => $cookie_value) {
if( preg_match("/comment_author_/i", $cookie_key) ) {
ob_start([$this, "cdn_rewrite"]);
return 0;
}
}
if( isset($_COOKIE) && isset($_COOKIE['safirmobilswitcher']) ) {
ob_start([$this, "cdn_rewrite"]);
return 0;
}
if( isset($_COOKIE) && isset($_COOKIE["wptouch-pro-view"]) ) {
if( WCL_Cache_Helpers::is_wptouch_smartphone() ) {
if( $_COOKIE["wptouch-pro-view"] == "desktop" ) {
ob_start([$this, "cdn_rewrite"]);
return 0;
}
}
}
if( preg_match("/\?/", $_SERVER["REQUEST_URI"]) && !preg_match("/\/\?fdx\_switcher\=true/", $_SERVER["REQUEST_URI"]) ) { // for WP Mobile Edition
if( preg_match("/\?amp(\=1)?/i", $_SERVER["REQUEST_URI"]) ) {
//
} else if( defined('WCACHE_QUERYSTRING') && WCACHE_QUERYSTRING ) {
//
} else {
ob_start([$this, "cdn_rewrite"]);
return 0;
}
}
if( preg_match("/(" . WCL_Cache_Helpers::get_excluded_useragent() . ")/", $_SERVER['HTTP_USER_AGENT']) ) {
return 0;
}
if( isset($_SERVER['REQUEST_URI']) && preg_match("/(\/){2}$/", $_SERVER['REQUEST_URI']) ) {
return 0;
}
// to check permalink if it does not end with slash
if( isset($_SERVER['REQUEST_URI']) && preg_match("/[^\/]+\/$/", $_SERVER['REQUEST_URI']) ) {
if( !preg_match("/\/$/", get_option('permalink_structure')) ) {
return 0;
}
}
if( isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "POST" ) {
return 0;
}
if( preg_match("/^https/i", get_option("home")) && !is_ssl() ) {
//Must be secure connection
return 0;
}
if( !preg_match("/^https/i", get_option("home")) && is_ssl() ) {
//must be normal connection
if( !WCL_Cache_Helpers::isPluginActive('really-simple-ssl/rlrsssl-really-simple-ssl.php') ) {
if( !WCL_Cache_Helpers::isPluginActive('really-simple-ssl-pro/really-simple-ssl-pro.php') ) {
if( !WCL_Cache_Helpers::isPluginActive('really-simple-ssl-on-specific-pages/really-simple-ssl-on-specific-pages.php') ) {
if( !WCL_Cache_Helpers::isPluginActive('ssl-insecure-content-fixer/ssl-insecure-content-fixer.php') ) {
if( !WCL_Cache_Helpers::isPluginActive('https-redirection/https-redirection.php') ) {
if( !WCL_Cache_Helpers::isPluginActive('better-wp-security/better-wp-security.php') ) {
return 0;
}
}
}
}
}
}
}
if( preg_match("/www\./i", get_option("home")) && !preg_match("/www\./i", $_SERVER['HTTP_HOST']) ) {
return 0;
}
if( !preg_match("/www\./i", get_option("home")) && preg_match("/www\./i", $_SERVER['HTTP_HOST']) ) {
return 0;
}
if( $this->exclude_page() ) {
echo "<!-- Clearfy Cache: Exclude Page -->"."\n";
return 0;
}
// http://mobiledetect.net/ does not contain the following user-agents
if( preg_match("/Nokia309|Casper_VIA/i", $_SERVER['HTTP_USER_AGENT']) ) {
return 0;
}
if( preg_match("/Empty\sUser\sAgent/i", $_SERVER['HTTP_USER_AGENT']) ) { // not to show the cache for command line
return 0;
}
//to show cache version via php if htaccess rewrite rule does not work
if( !$this->preload_user_agent && $this->cacheFilePath && (@file_exists($this->cacheFilePath . "index.html") || @file_exists($this->cacheFilePath . "index.json") || @file_exists($this->cacheFilePath . "index.xml")) ) {
$via_php = "";
if( @file_exists($this->cacheFilePath . "index.json") ) {
$file_extension = "json";
header('Content-type: application/json');
} else if( @file_exists($this->cacheFilePath . "index.xml") ) {
$file_extension = "xml";
header('Content-type: text/xml');
} else {
$file_extension = "html";
$via_php = "<!-- via php -->";
}
if( $content = @file_get_contents($this->cacheFilePath . "index." . $file_extension) ) {
if( defined('WCLEARFY_REMOVE_VIA_FOOTER_COMMENT') && WCLEARFY_REMOVE_VIA_FOOTER_COMMENT ) {
$via_php = "";
}
$content = $content . $via_php;
die($content);
}
} else {
if( WCL_Cache_Helpers::isMobile() ) {
if( class_exists("WCL_MobileCache") && WCL_Plugin::app()->getPopulateOption('cache_mobile_theme') ) {
if( WCL_Plugin::app()->getPopulateOption('cache_mobile_theme_name') ) {
$create_cache = true;
} else if( WCL_Cache_Helpers::isPluginActive('wptouch/wptouch.php') || WCL_Cache_Helpers::isPluginActive('wptouch-pro/wptouch-pro.php') ) {
//to check that user-agent exists in wp-touch's list or not
if( WCL_Cache_Helpers::is_wptouch_smartphone() ) {
$create_cache = true;
} else {
$create_cache = false;
}
} else if( WCL_Cache_Helpers::isPluginActive('any-mobile-theme-switcher/any-mobile-theme-switcher.php') ) {
if( WCL_Cache_Helpers::is_anymobilethemeswitcher_mobile() ) {
$create_cache = true;
} else {
$create_cache = false;
}
} else {
if( (preg_match('/iPhone/', $_SERVER['HTTP_USER_AGENT']) && preg_match('/Mobile/', $_SERVER['HTTP_USER_AGENT'])) || (preg_match('/Android/', $_SERVER['HTTP_USER_AGENT']) && preg_match('/Mobile/', $_SERVER['HTTP_USER_AGENT'])) ) {
$create_cache = true;
} else {
$create_cache = false;
}
}
} else if( !WCL_Plugin::app()->getPopulateOption('cache_mobile') && !WCL_Plugin::app()->getPopulateOption('cache_mobile_theme') ) {
$create_cache = true;
} else {
$create_cache = false;
}
} else {
$create_cache = true;
}
if( $create_cache ) {
$this->startTime = microtime(true);
add_action('wp', [$this, "detect_current_page_type"]);
add_action('get_footer', [$this, "detect_current_page_type"]);
add_action('get_footer', [$this, "wp_print_scripts_action"]);
// to exclude current page hook
add_action("wclearfy_exclude_current_page", [$this, 'exclude_current_page'], 10, 0);
ob_start([$this, "callback"]);
}
}
}
public function exclude_current_page($some = true)
{
$via = debug_backtrace();
if( isset($via) && is_array($via) ) {
foreach($via as $key => $value) {
if( $value["function"] == "wclearfy_exclude_current_page" ) {
if( defined('WCLEARFY_DEBUG') && (WCLEARFY_DEBUG === true) ) {
if( preg_match("/wp-content\/themes/", $value["file"]) ) {
$this->exclude_current_page_text = "<!-- This page has been excluded by " . basename($value["file"]) . " of the Theme -->";
} else if( preg_match("/wp-content\/plugins/", $value["file"]) ) {
$this->exclude_current_page_text = "<!-- This page has been excluded by " . basename($value["file"]) . " of " . preg_replace("/([^\/]+)\/.+/", "$1", plugin_basename($value["file"])) . " -->";
}
} else {
$this->exclude_current_page_text = "<!-- This page has been excluded -->";
}
break;
}
}
}
}
public function wp_print_scripts_action()
{
echo "<!--WCLEARFY_FOOTER_START-->";
}
public function ignored($buffer)
{
$list = [
"\/wp\-comments\-post\.php",
"\/wp\-login\.php",
"\/robots\.txt",
"\/wp\-cron\.php",
"\/wp\-content",
"\/wp\-admin",
"\/wp\-includes",
"\/index\.php",
"\/xmlrpc\.php",
"\/wp\-api\/",
"leaflet\-geojson\.php",
"\/clientarea\.php"
];
if( WCL_Cache_Helpers::isPluginActive('woocommerce/woocommerce.php') ) {
if( $this->current_page_type != "homepage" ) {
global $post;
if( isset($post->ID) && $post->ID ) {
if( function_exists("wc_get_page_id") ) {
$woocommerce_ids = [];
array_push($woocommerce_ids, wc_get_page_id('cart'), wc_get_page_id('checkout'), wc_get_page_id('receipt'), wc_get_page_id('confirmation'), wc_get_page_id('myaccount'));
if( in_array($post->ID, $woocommerce_ids) ) {
return true;
}
}
}
array_push($list, "\/cart\/?$", "\/checkout", "\/receipt", "\/confirmation", "\/wc-api\/");
}
}
if( WCL_Cache_Helpers::isPluginActive('wp-easycart/wpeasycart.php') ) {
array_push($list, "\/cart");
}
if( WCL_Cache_Helpers::isPluginActive('easy-digital-downloads/easy-digital-downloads.php') ) {
array_push($list, "\/cart", "\/checkout");
}
if( preg_match("/" . implode("|", $list) . "/i", $_SERVER["REQUEST_URI"]) ) {
return true;
}
return false;
}
public function exclude_page()
{
$preg_match_rule = "";
$request_url = urldecode(trim($_SERVER["REQUEST_URI"], "/"));
$excluded_uris = WCL_Plugin::app()->getPopulateOption('cache_reject_uri');
if( !empty($excluded_uris) ) {
$excluded_uris = array_map(function ($value) {
$site_url = site_url();
$value = trim(rtrim($value));
// http://clearfy.pro/members/ -> /members/
$value = str_replace($site_url, "", $value);
// /members/(.*) -> members/(.*)
$value = preg_replace("/^\//", "", $value);
// members/ -> members
$value = untrailingslashit($value);
return $value;
}, preg_split('/\r\n|\n|\r/', $excluded_uris));
} else {
$excluded_uris = [];
}
foreach($excluded_uris as $uri) {
if( $uri === $request_url ) {
return true;
}
if( !empty($uri) && @preg_match('/' . $uri . '/i', $request_url) ) {
return true;
}
}
return false;
}
public function is_json()
{
return $this->current_page_content_type == "json" ? true : false;
}
public function is_xml()
{
return $this->current_page_content_type == "xml" ? true : false;
}
public function is_html()
{
return $this->current_page_content_type == "html" ? true : false;
}
public function set_current_page_type($buffer)
{
preg_match('/<\!--WCLEARFY_PAGE_TYPE_([a-z]+)-->/i', $buffer, $out);
$this->current_page_type = isset($out[1]) ? $out[1] : false;
}
public function set_current_page_content_type($buffer)
{
$content_type = false;
if( function_exists("headers_list") ) {
$headers = headers_list();
foreach($headers as $header) {
if( preg_match("/Content-Type\:/i", $header) ) {
$content_type = preg_replace("/Content-Type\:\s(.+)/i", "$1", $header);
}
}
}
if( preg_match("/xml/i", $content_type) ) {
$this->current_page_content_type = "xml";
} else if( preg_match("/json/i", $content_type) ) {
$this->current_page_content_type = "json";
} else {
$this->current_page_content_type = "html";
}
}
public function last_error($buffer = false)
{
if( function_exists("http_response_code") && (http_response_code() === 404) ) {
return true;
}
if( is_404() ) {
return true;
}
if( preg_match("/<body id\=\"error-page\">\s*<p>[^\>]+<\/p>\s*<\/body>/i", $buffer) ) {
return true;
}
}
public function callback($buffer)
{
$this->set_current_page_type($buffer);
$this->set_current_page_content_type($buffer);
$buffer = $this->checkShortCode($buffer);
// for Wordfence: not to cache 503 pages
if( defined('DONOTCACHEPAGE') && WCL_Cache_Helpers::isPluginActive('wordfence/wordfence.php') ) {
if( function_exists("http_response_code") && http_response_code() == 503 ) {
return $buffer . "<!-- DONOTCACHEPAGE is defined as TRUE -->";
}
}
// for iThemes Security: not to cache 403 pages
if( defined('DONOTCACHEPAGE') && WCL_Cache_Helpers::isPluginActive('better-wp-security/better-wp-security.php') ) {
if( function_exists("http_response_code") && http_response_code() == 403 ) {
return $buffer . "<!-- DONOTCACHEPAGE is defined as TRUE -->";
}
}
if( $this->exclude_page($buffer) ) {
$buffer = preg_replace('/<\!--WCLEARFY_PAGE_TYPE_[a-z]+-->/i', '', $buffer);
return $buffer;
}
$buffer = preg_replace('/<\!--WCLEARFY_PAGE_TYPE_[a-z]+-->/i', '', $buffer);
if( $this->exclude_current_page_text ) {
return $buffer . $this->exclude_current_page_text;
} else if( $this->is_json() && (!defined('WCACHE_JSON') || (defined('WCACHE_JSON') && WCACHE_JSON !== true)) ) {
return $buffer;
} else if( preg_match("/Mediapartners-Google|Google\sWireless\sTranscoder/i", $_SERVER['HTTP_USER_AGENT']) ) {
return $buffer;
} else if( is_user_logged_in() || $this->isCommenter() ) {
return $buffer;
} else if( $this->isPasswordProtected($buffer) ) {
return $buffer . "<!-- Password protected content has been detected -->";
} else if( WCL_Cache_Helpers::isWpLogin($buffer) ) {
return $buffer . "<!-- wp-login.php -->";
} else if( WCL_Cache_Helpers::hasContactForm7WithCaptcha($buffer) ) {
return $buffer . "<!-- This page was not cached because ContactForm7's captcha -->";
} else if( $this->last_error($buffer) ) {
return $buffer;
} else if( $this->ignored($buffer) ) {
return $buffer;
} else if( $this->blockCache === true ) {
return $buffer . "<!-- wclearfyNOT has been detected -->";
} else if( isset($_GET["preview"]) ) {
return $buffer . "<!-- not cached -->";
} else if( $this->checkHtml($buffer) ) {
return $buffer . "<!-- html is corrupted -->";
} else if( (function_exists("http_response_code")) && (http_response_code() == 301 || http_response_code() == 302) ) {
return $buffer;
} else if( !$this->cacheFilePath ) {
return $buffer . "<!-- permalink_structure ends with slash (/) but REQUEST_URI does not end with slash (/) -->";
} else {
$content = $buffer;
if( $this->err ) {
return $buffer . "<!-- " . $this->err . " -->";
} else {
$content = $this->cacheDate($content);
$content = str_replace("<!--WCLEARFY_FOOTER_START-->", "", $content);
$content = $this->cdn_rewrite($content);
$content = $this->fix_pre_tag($content, $buffer);
if( $this->cacheFilePath ) {
if( $this->is_html() ) {
$this->createFolder($this->cacheFilePath, $content);
do_action('wclearfy_is_cacheable_action');
} else if( $this->is_xml() ) {
if( preg_match("/<link><\/link>/", $buffer) ) {
if( preg_match("/\/feed$/", $_SERVER["REQUEST_URI"]) ) {
return $buffer . time();
}
}
$this->createFolder($this->cacheFilePath, $buffer, "xml");
do_action('wclearfy_is_cacheable_action');
return $buffer;
} else if( $this->is_json() ) {
$this->createFolder($this->cacheFilePath, $buffer, "json");
do_action('wclearfy_is_cacheable_action');
return $buffer;
}
}
return $content . "<!-- need to refresh to see cached version -->";
}
}
}
public function fix_pre_tag($content, $buffer)
{
if( preg_match("/<pre[^\>]*>/i", $buffer) ) {
preg_match_all("/<pre[^\>]*>((?!<\/pre>).)+<\/pre>/is", $buffer, $pre_buffer);
preg_match_all("/<pre[^\>]*>((?!<\/pre>).)+<\/pre>/is", $content, $pre_content);
if( isset($pre_content[0]) && isset($pre_content[0][0]) ) {
foreach($pre_content[0] as $key => $value) {
/*
location ~ / {
set $path /path/$1/index.html;
}
*/
if( isset($pre_buffer[0][$key]) ) {
$pre_buffer[0][$key] = preg_replace('/\$(\d)/', '\\\$$1', $pre_buffer[0][$key]);
$content = preg_replace("/" . preg_quote($value, "/") . "/", $pre_buffer[0][$key], $content);
}
}
}
}
return $content;
}
public function cdn_rewrite($content)
{
if( $this->cdn ) {
$content = preg_replace_callback("/(srcset|src|href|data-vc-parallax-image|data-bg|data-fullurl|data-mobileurl|data-img-url|data-cvpsrc|data-cvpset|data-thumb|data-bg-url|data-large_image|data-lazyload|data-lazy|data-source-url|data-srcsmall|data-srclarge|data-srcfull|data-slide-img|data-lazy-original)\s{0,2}\=\s{0,2}[\'\"]([^\'\"]+)[\'\"]/i", [
$this,
'cdn_replace_urls'
], $content);
//url()
$content = preg_replace_callback("/(url)\(([^\)\>]+)\)/i", [$this, 'cdn_replace_urls'], $content);
//{"concatemoji":"http:\/\/your_url.com\/wp-includes\/js\/wp-emoji-release.min.js?ver=4.7"}
$content = preg_replace_callback("/\{\"concatemoji\"\:\"[^\"]+\"\}/i", [
$this,
'cdn_replace_urls'
], $content);
//<script>var loaderRandomImages=["https:\/\/www.site.com\/wp-content\/uploads\/2016\/12\/image.jpg"];</script>
$content = preg_replace_callback("/[\"\']([^\'\"]+)[\"\']\s*\:\s*[\"\']https?\:\\\\\/\\\\\/[^\"\']+[\"\']/i", [
$this,
'cdn_replace_urls'
], $content);
// <script>
// jsFileLocation:"//domain.com/wp-content/plugins/revslider/public/assets/js/"
// </script>
$content = preg_replace_callback("/(jsFileLocation)\s*\:[\"\']([^\"\']+)[\"\']/i", [
$this,
'cdn_replace_urls'
], $content);
// <form data-product_variations="[{&quot;src&quot;:&quot;//domain.com\/img.jpg&quot;}]">
// <div data-siteorigin-parallax="{&quot;backgroundUrl&quot;:&quot;https:\/\/domain.com\/wp-content\/TOR.jpg&quot;,&quot;backgroundSize&quot;:[830,467],&quot;}" data-stretch-type="full">
$content = preg_replace_callback("/(data-product_variations|data-siteorigin-parallax)\=[\"\'][^\"\']+[\"\']/i", [
$this,
'cdn_replace_urls'
], $content);
// <object data="https://site.com/source.swf" type="application/x-shockwave-flash"></object>
$content = preg_replace_callback("/<object[^\>]+(data)\s{0,2}\=[\'\"]([^\'\"]+)[\'\"][^\>]+>/i", [
$this,
'cdn_replace_urls'
], $content);
}
return $content;
}
public function get_header($content)
{
$head_first_index = strpos($content, "<head");
$head_last_index = strpos($content, "</head>");
return substr($content, $head_first_index, ($head_last_index - $head_first_index + 1));
}
public function checkHtml($buffer)
{
if( !$this->is_html() ) {
return false;
}
if( preg_match('/<html[^\>]*>/si', $buffer) && preg_match('/<body[^\>]*>/si', $buffer) ) {
return false;
}
// if(strlen($buffer) > 10){
// return false;
// }
return true;
}
public function cacheDate($buffer)
{
if( WCL_Cache_Helpers::isMobile() && class_exists("WCL_MobileCache") && WCL_Plugin::app()->getPopulateOption('cache_mobile') && WCL_Plugin::app()->getPopulateOption('cache_mobile_theme') ) {
$comment = "<!-- Mobile: Clearfy Cache file was created in " . $this->creationTime() . " seconds, on " . date("d-m-y G:i:s", current_time('timestamp')) . " -->";
} else {
$comment = "<!-- Clearfy Cache file was created in " . $this->creationTime() . " seconds, on " . date("d-m-y G:i:s", current_time('timestamp')) . " -->";
}
if( defined('WCLEARFY_REMOVE_FOOTER_COMMENT') && WCLEARFY_REMOVE_FOOTER_COMMENT ) {
return $buffer;
} else {
return $buffer . $comment;
}
}
public function creationTime()
{
return microtime(true) - $this->startTime;
}
public function isCommenter()
{
$commenter = wp_get_current_commenter();
return isset($commenter["comment_author_email"]) && $commenter["comment_author_email"] ? true : false;
}
public function isPasswordProtected($buffer)
{
if( preg_match("/action\=[\'\"].+postpass.*[\'\"]/", $buffer) ) {
return true;
}
foreach($_COOKIE as $key => $value) {
if( preg_match("/wp\-postpass\_/", $key) ) {
return true;
}
}
return false;
}
public function create_name($list)
{
$arr = is_array($list) ? $list : [["href" => $list]];
$name = "";
foreach($arr as $tag_key => $tag_value) {
$tmp = preg_replace("/(\.css|\.js)\?.*/", "$1", $tag_value["href"]); //to remove version number
$name = $name . $tmp;
}
return base_convert(crc32($name), 20, 36);
}
public function createFolder($cachFilePath, $buffer, $extension = "html", $prefix = false)
{
$create = false;
$file_name = "index.";
$update_db_statistic = true;
if( $buffer && strlen($buffer) > 100 && preg_match("/html|xml|json/i", $extension) ) {
if( !preg_match("/^\<\!\-\-\sMobile\:\sWP\sFastest\sCache/i", $buffer) ) {
if( !preg_match("/^\<\!\-\-\sWP\sFastest\sCache/i", $buffer) ) {
$create = true;
}
}
if( $this->preload_user_agent ) {
if( file_exists($cachFilePath . "/" . "index." . $extension) ) {
$update_db_statistic = false;
@unlink($cachFilePath . "/" . "index." . $extension);
}
}
}
if( ($extension == "svg" || $extension == "woff" || $extension == "css" || $extension == "js") && $buffer && strlen($buffer) > 5 ) {
$create = true;
$file_name = base_convert(substr(time(), -6), 20, 36) . ".";
$buffer = trim($buffer);
if( $extension == "js" ) {
if( substr($buffer, -1) != ";" ) {
$buffer .= ";";
}
}
}
if( $create ) {
if( !is_user_logged_in() && !$this->isCommenter() ) {
if( !is_dir($cachFilePath) ) {
if( is_writable(WCL_Cache_Helpers::getWpContentDir()) || ((is_dir(WCL_Cache_Helpers::getWpContentDir() . "/cache")) && (is_writable(WCL_Cache_Helpers::getWpContentDir() . "/cache"))) ) {
if( @mkdir($cachFilePath, 0755, true) ) {
$buffer = (string)apply_filters('wclearfy_buffer_callback_filter', $buffer, $extension);
file_put_contents($cachFilePath . "/" . $file_name . $extension, $buffer);
if( $extension == "html" ) {
if( !file_exists(WP_CONTENT_DIR . "/cache/index.html") ) {
@file_put_contents(WP_CONTENT_DIR . "/cache/index.html", "");
}
} else {
if( !file_exists(WP_CONTENT_DIR . "/cache/wclearfy-minified/index.html") ) {
@file_put_contents(WP_CONTENT_DIR . "/cache/wclearfy-minified/index.html", "");
}
}
} else {
}
} else {
}
} else {
if( file_exists($cachFilePath . "/" . $file_name . $extension) ) {
} else {
$buffer = (string)apply_filters('wclearfy_buffer_callback_filter', $buffer, $extension);
file_put_contents($cachFilePath . "/" . $file_name . $extension, $buffer);
}
}
}
} else if( $extension == "html" ) {
$this->err = "Buffer is empty so the cache cannot be created";
}
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
<?php
// Silence is golden.

View File

@@ -0,0 +1,45 @@
<?php
class WCL_MobileCache {
private $folder_name = "wclearfy-mobile-cache";
private $wptouch = false;
public function __construct()
{
}
public function set_wptouch($status)
{
$this->wptouch = $status;
}
public function update_htaccess($data)
{
preg_match("/RewriteEngine\sOn(.+)/is", $data, $out);
$htaccess = "\n##### mobile #####\n";
$htaccess .= $out[0];
if( $this->wptouch ) {
$wptouch_rule = "RewriteCond %{HTTP:Cookie} !wptouch-pro-view=desktop";
$htaccess = str_replace("RewriteCond %{HTTP:Profile}", $wptouch_rule . "\n" . "RewriteCond %{HTTP:Profile}", $htaccess);
}
$htaccess = str_replace("RewriteCond %{HTTP:Cookie} !safirmobilswitcher=mobil", "RewriteCond %{HTTP:Cookie} !safirmobilswitcher=masaustu", $htaccess);
$htaccess = str_replace("RewriteCond %{HTTP_USER_AGENT} !^.*", "RewriteCond %{HTTP_USER_AGENT} ^.*", $htaccess);
$htaccess = preg_replace("/\/cache\/all\//", "/cache/" . $this->get_folder_name() . "/", $htaccess);
//$htaccess = preg_replace("/(\/cache\/)[^\/]+(\/.{1}1\/index\.html)/","$1".$this->get_folder_name()."$2", $htaccess);
$htaccess .= "\n##### mobile #####\n";
return $htaccess;
}
public function get_folder_name()
{
return $this->folder_name;
}
}
?>

View File

@@ -0,0 +1,504 @@
<?php
class WCL_Preload_Cache {
private static $exclude_rules = false;
public static function set_preload($slug)
{
$preload_arr = array();
if( !empty($_POST) && isset($_POST["wpFastestCachePreload"]) ) {
foreach($_POST as $key => $value) {
$key = esc_attr($key);
$value = esc_attr($value);
preg_match("/wpFastestCachePreload_(.+)/", $key, $type);
if( !empty($type) ) {
if( $type[1] == "restart" ) {
//to need to remove "restart" value
} else if( $type[1] == "number" ) {
$preload_arr[$type[1]] = $value;
} else {
$preload_arr[$type[1]] = 0;
}
}
}
}
if( $data = get_option("WClearfyCachePreLoad") ) {
$preload_std = json_decode($data);
if( !empty($preload_arr) ) {
foreach($preload_arr as $key => &$value) {
if( !empty($preload_std->$key) ) {
if( $key != "number" ) {
$value = $preload_std->$key;
}
}
}
$preload_std = $preload_arr;
} else {
foreach($preload_std as $key => &$value) {
if( $key != "number" ) {
$value = 0;
}
}
}
update_option("WClearfyCachePreLoad", json_encode($preload_std));
if( !wp_next_scheduled($slug . "_Preload") ) {
wp_schedule_event(time() + 5, 'everyfiveminute', $slug . "_Preload");
}
} else {
if( !empty($preload_arr) ) {
add_option("WClearfyCachePreLoad", json_encode($preload_arr), null, "yes");
if( !wp_next_scheduled($slug . "_Preload") ) {
wp_schedule_event(time() + 5, 'everyfiveminute', $slug . "_Preload");
}
} else {
//toDO
}
}
}
public static function statistic($pre_load = false)
{
$total = new stdClass();
if( isset($pre_load->homepage) ) {
$total->homepage = 1;
}
if( isset($pre_load->customposttypes) ) {
global $wpdb;
$post_types = get_post_types(array('public' => true), "names", "and");
$where_query = "";
foreach($post_types as $post_type_key => $post_type_value) {
if( !in_array($post_type_key, array("post", "page", "attachment")) ) {
$where_query = $where_query . $wpdb->prefix . "posts.post_type = '" . $post_type_value . "' OR ";
}
}
if( $where_query ) {
$where_query = preg_replace("/(\s*OR\s*)$/", "", $where_query);
$recent_custom_posts = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS COUNT(" . $wpdb->prefix . "posts.ID) as total FROM " . $wpdb->prefix . "posts WHERE 1=1 AND (" . $where_query . ") AND ((" . $wpdb->prefix . "posts.post_status = 'publish')) ORDER BY " . $wpdb->prefix . "posts.ID", ARRAY_A);
$total->customposttypes = $recent_custom_posts[0]["total"];
}
}
if( isset($pre_load->post) ) {
$count_posts = wp_count_posts("post", array('post_status' => 'publish', 'suppress_filters' => true));
$total->post = $count_posts->publish;
}
if( isset($pre_load->attachment) ) {
$total_attachments = wp_count_attachments();
$total->attachment = array_sum((array)$total_attachments) - $total_attachments->trash;
}
if( isset($pre_load->page) ) {
$count_pages = wp_count_posts("page", array('post_status' => 'publish', 'suppress_filters' => true));
$total->page = $count_pages->publish;
}
if( isset($pre_load->category) ) {
$total->category = wp_count_terms("category", array('hide_empty' => false));
}
if( isset($pre_load->tag) ) {
$total->tag = wp_count_terms("post_tag", array('hide_empty' => false));
}
if( isset($pre_load->customTaxonomies) ) {
$taxo = get_taxonomies(array('public' => true, '_builtin' => false), "names", "and");
if( count($taxo) > 0 ) {
$total->customTaxonomies = wp_count_terms($taxo, array('hide_empty' => false));
}
}
foreach($total as $key => $value) {
$pre_load->$key = $pre_load->$key == -1 ? $value : $pre_load->$key;
echo $key . ": " . $pre_load->$key . "/" . $value . "<br>";
}
}
public static function create_preload_cache($options)
{
if( $data = get_option("WClearfyCachePreLoad") ) {
if( !isset($options->wpFastestCacheStatus) ) {
die("Cache System must be enabled");
}
$pre_load = json_decode($data);
if( defined("WCLEARFY_PRELOAD_NUMBER") && WCLEARFY_PRELOAD_NUMBER ) {
$number = WCLEARFY_PRELOAD_NUMBER;
} else {
$number = $pre_load->number;
}
$urls_limit = isset($options->wpFastestCachePreload_number) ? $options->wpFastestCachePreload_number : 4; // must be even
$urls = array();
if( isset($options->wpFastestCacheMobileTheme) && $options->wpFastestCacheMobileTheme ) {
$mobile_theme = true;
$number = round($number / 2);
} else {
$mobile_theme = false;
}
// HOME
if( isset($pre_load->homepage) && $pre_load->homepage > -1 ) {
if( $mobile_theme ) {
array_push($urls, array("url" => get_option("home"), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => get_option("home"), "user-agent" => "desktop"));
$number--;
$pre_load->homepage = -1;
}
// CUSTOM POSTS
if( $number > 0 && isset($pre_load->customposttypes) && $pre_load->customposttypes > -1 ) {
global $wpdb;
$post_types = get_post_types(array('public' => true), "names", "and");
$where_query = "";
foreach($post_types as $post_type_key => $post_type_value) {
if( !in_array($post_type_key, array("post", "page", "attachment")) ) {
$where_query = $where_query . $wpdb->prefix . "posts.post_type = '" . $post_type_value . "' OR ";
}
}
if( $where_query ) {
$where_query = preg_replace("/(\s*OR\s*)$/", "", $where_query);
$recent_custom_posts = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS " . $wpdb->prefix . "posts.ID FROM " . $wpdb->prefix . "posts WHERE 1=1 AND (" . $where_query . ") AND ((" . $wpdb->prefix . "posts.post_status = 'publish')) ORDER BY " . $wpdb->prefix . "posts.ID DESC LIMIT " . $pre_load->customposttypes . ", " . $number, ARRAY_A);
if( count($recent_custom_posts) > 0 ) {
foreach($recent_custom_posts as $key => $post) {
if( $mobile_theme ) {
array_push($urls, array("url" => get_permalink($post["ID"]), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => get_permalink($post["ID"]), "user-agent" => "desktop"));
$number--;
$pre_load->customposttypes = $pre_load->customposttypes + 1;
}
} else {
$pre_load->customposttypes = -1;
}
}
}
// POST
if( $number > 0 && isset($pre_load->post) && $pre_load->post > -1 ) {
// $recent_posts = wp_get_recent_posts(array(
// 'numberposts' => $number,
// 'offset' => $pre_load->post,
// 'orderby' => 'ID',
// 'order' => 'DESC',
// 'post_type' => 'post',
// 'post_status' => 'publish',
// 'suppress_filters' => true
// ), ARRAY_A);
global $wpdb;
$recent_posts = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS " . $wpdb->prefix . "posts.ID FROM " . $wpdb->prefix . "posts WHERE 1=1 AND (" . $wpdb->prefix . "posts.post_type = 'post') AND ((" . $wpdb->prefix . "posts.post_status = 'publish')) ORDER BY " . $wpdb->prefix . "posts.ID DESC LIMIT " . $pre_load->post . ", " . $number, ARRAY_A);
if( count($recent_posts) > 0 ) {
foreach($recent_posts as $key => $post) {
if( $mobile_theme ) {
array_push($urls, array("url" => get_permalink($post["ID"]), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => get_permalink($post["ID"]), "user-agent" => "desktop"));
$number--;
$pre_load->post = $pre_load->post + 1;
}
} else {
$pre_load->post = -1;
}
}
// ATTACHMENT
if( $number > 0 && isset($pre_load->attachment) && $pre_load->attachment > -1 ) {
global $wpdb;
$recent_attachments = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS " . $wpdb->prefix . "posts.ID FROM " . $wpdb->prefix . "posts WHERE 1=1 AND (" . $wpdb->prefix . "posts.post_type = 'attachment') ORDER BY " . $wpdb->prefix . "posts.ID DESC LIMIT " . $pre_load->attachment . ", " . $number, ARRAY_A);
if( count($recent_attachments) > 0 ) {
foreach($recent_attachments as $key => $attachment) {
if( $mobile_theme ) {
array_push($urls, array(
"url" => get_permalink($attachment["ID"]),
"user-agent" => "mobile"
));
$number--;
}
array_push($urls, array("url" => get_permalink($attachment["ID"]), "user-agent" => "desktop"));
$number--;
$pre_load->attachment = $pre_load->attachment + 1;
}
} else {
$pre_load->attachment = -1;
}
}
// PAGE
if( $number > 0 && isset($pre_load->page) && $pre_load->page > -1 ) {
global $wpdb;
$pages = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS " . $wpdb->prefix . "posts.ID FROM " . $wpdb->prefix . "posts WHERE 1=1 AND (" . $wpdb->prefix . "posts.post_type = 'page') AND ((" . $wpdb->prefix . "posts.post_status = 'publish')) ORDER BY " . $wpdb->prefix . "posts.ID DESC LIMIT " . $pre_load->page . ", " . $number, ARRAY_A);
if( count($pages) > 0 ) {
foreach($pages as $key => $page) {
if( $mobile_theme ) {
array_push($urls, array("url" => get_page_link($page["ID"]), "user-agent" => "mobile"));
$number--;
}
array_push($urls, array("url" => get_page_link($page["ID"]), "user-agent" => "desktop"));
$number--;
$pre_load->page = $pre_load->page + 1;
}
} else {
$pre_load->page = -1;
}
}
// CATEGORY
if( $number > 0 && isset($pre_load->category) && $pre_load->category > -1 ) {
$categories = get_terms(array(
'taxonomy' => array('category'),
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => false,
'number' => $number,
'fields' => 'all',
'pad_counts' => false,
'offset' => $pre_load->category
));
if( count($categories) > 0 ) {
foreach($categories as $key => $category) {
if( $mobile_theme ) {
array_push($urls, array(
"url" => get_term_link($category->slug, $category->taxonomy),
"user-agent" => "mobile"
));
$number--;
}
array_push($urls, array(
"url" => get_term_link($category->slug, $category->taxonomy),
"user-agent" => "desktop"
));
$number--;
$pre_load->category = $pre_load->category + 1;
}
} else {
$pre_load->category = -1;
}
}
// TAG
if( $number > 0 && isset($pre_load->tag) && $pre_load->tag > -1 ) {
$tags = get_terms(array(
'taxonomy' => array('post_tag'),
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => false,
'number' => $number,
'fields' => 'all',
'pad_counts' => false,
'offset' => $pre_load->tag
));
if( count($tags) > 0 ) {
foreach($tags as $key => $tag) {
if( $mobile_theme ) {
array_push($urls, array(
"url" => get_term_link($tag->slug, $tag->taxonomy),
"user-agent" => "mobile"
));
$number--;
}
array_push($urls, array(
"url" => get_term_link($tag->slug, $tag->taxonomy),
"user-agent" => "desktop"
));
$number--;
$pre_load->tag = $pre_load->tag + 1;
}
} else {
$pre_load->tag = -1;
}
}
// Custom Taxonomies
if( $number > 0 && isset($pre_load->customTaxonomies) && $pre_load->customTaxonomies > -1 ) {
$taxo = get_taxonomies(array('public' => true, '_builtin' => false), "names", "and");
if( count($taxo) > 0 ) {
$custom_taxos = get_terms(array(
'taxonomy' => array_values($taxo),
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => false,
'number' => $number,
'fields' => 'all',
'pad_counts' => false,
'offset' => $pre_load->customTaxonomies
));
if( count($custom_taxos) > 0 ) {
foreach($custom_taxos as $key => $custom_tax) {
if( $mobile_theme ) {
array_push($urls, array(
"url" => get_term_link($custom_tax->slug, $custom_tax->taxonomy),
"user-agent" => "mobile"
));
$number--;
}
array_push($urls, array(
"url" => get_term_link($custom_tax->slug, $custom_tax->taxonomy),
"user-agent" => "desktop"
));
$number--;
$pre_load->customTaxonomies = $pre_load->customTaxonomies + 1;
}
} else {
$pre_load->customTaxonomies = -1;
}
} else {
$pre_load->customTaxonomies = -1;
}
}
if( count($urls) > 0 ) {
foreach($urls as $key => $arr) {
$user_agent = "";
if( $arr["user-agent"] == "desktop" ) {
$user_agent = "Clearfy Cache Preload Bot";
} else if( $arr["user-agent"] == "mobile" ) {
$user_agent = "Clearfy Cache Preload iPhone Mobile Bot";
}
if( self::is_excluded($arr["url"]) ) {
$status = "<strong style=\"color:blue;\">Excluded</strong>";
} else {
if( $GLOBALS["wp_fastest_cache"]->wclearfy_remote_get($arr["url"], $user_agent) ) {
$status = "<strong style=\"color:lightgreen;\">OK</strong>";
} else {
$status = "<strong style=\"color:red;\">ERROR</strong>";
}
}
echo $status . " " . $arr["url"] . " (" . $arr["user-agent"] . ")<br>";
}
echo "<br>";
echo count($urls) . " page have been cached";
update_option("WClearfyCachePreLoad", json_encode($pre_load));
echo "<br><br>";
self::statistic($pre_load);
} else {
if( isset($options->wpFastestCachePreload_restart) ) {
foreach($pre_load as $pre_load_key => &$pre_load_value) {
if( $pre_load_key != "number" ) {
$pre_load_value = 0;
}
}
update_option("WClearfyCachePreLoad", json_encode($pre_load));
echo "Preload Restarted";
include_once('cdn.php');
CdnWCLEARFY::cloudflare_clear_cache();
} else {
echo "Completed";
wp_clear_scheduled_hook("wp_fastest_cache_Preload");
}
}
}
if( isset($_GET) && isset($_GET["type"]) && $_GET["type"] == "preload" ) {
die();
}
}
public static function is_excluded($url)
{
if( !is_string($url) ) {
return false;
}
$request_url = parse_url($url, PHP_URL_PATH);
$request_url = urldecode(trim($request_url, "/"));
if( !$request_url ) {
return false;
}
if( self::$exclude_rules === false ) {
if( $json_data = get_option("WClearfyCacheExclude") ) {
self::$exclude_rules = json_decode($json_data);
} else {
self::$exclude_rules = array();
}
}
foreach((array)self::$exclude_rules as $key => $value) {
if( $value->prefix == "exact" ) {
if( strtolower($value->content) == strtolower($request_url) ) {
return true;
}
} else {
if( $value->prefix == "startwith" ) {
$preg_match_rule = "^" . preg_quote($value->content, "/");
} else if( $value->prefix == "contain" ) {
$preg_match_rule = preg_quote($value->content, "/");
}
if( isset($preg_match_rule) ) {
if( preg_match("/" . $preg_match_rule . "/i", $request_url) ) {
return true;
}
}
}
}
return false;
}
}
?>

View File

@@ -0,0 +1,208 @@
<?php
class WCL_SinglePreload_Cache {
public static $id = 0;
public static $urls = array();
public static function init()
{
SinglePreloadWCLEARFY::set_id();
SinglePreloadWCLEARFY::set_urls();
SinglePreloadWCLEARFY::set_urls_with_terms();
}
public static function set_id()
{
if( isset($_GET["post"]) && $_GET["post"] ) {
static::$id = esc_sql($_GET["post"]);
if( get_post_status(static::$id) != "publish" ) {
static::$id = 0;
}
}
}
public static function create_cache()
{
$res = $GLOBALS["wp_fastest_cache"]->wclearfy_remote_get($_GET["url"], $_GET["user_agent"]);
if( $res ) {
die("true");
}
}
public static function is_mobile_active()
{
if( isset($GLOBALS["wp_fastest_cache_options"]->wpFastestCacheMobile) && isset($GLOBALS["wp_fastest_cache_options"]->wpFastestCacheMobileTheme) ) {
return true;
} else {
return false;
}
}
public static function set_term_urls($term_taxonomy_id)
{
$term = get_term_by("term_taxonomy_id", $term_taxonomy_id);
if( $term && !is_wp_error($term) ) {
$url = get_term_link($term->term_id, $term->taxonomy);
array_push(static::$urls, array("url" => $url, "user-agent" => "Clearfy Cache Preload Bot"));
if( self::is_mobile_active() ) {
array_push(static::$urls, array(
"url" => $url,
"user-agent" => "Clearfy Cache Preload iPhone Mobile Bot"
));
}
if( $term->parent > 0 ) {
$parent = get_term_by("id", $term->parent, $term->taxonomy);
static::set_term_urls($parent->term_taxonomy_id);
}
}
}
public static function set_urls_with_terms()
{
global $wpdb;
$terms = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "term_relationships` WHERE `object_id`=" . static::$id, ARRAY_A);
foreach($terms as $term_key => $term_val) {
static::set_term_urls($term_val["term_taxonomy_id"]);
}
}
public static function set_urls()
{
if( static::$id ) {
$permalink = get_permalink(static::$id);
array_push(static::$urls, array("url" => $permalink, "user-agent" => "Clearfy Cache Preload Bot"));
if( self::is_mobile_active() ) {
array_push(static::$urls, array(
"url" => $permalink,
"user-agent" => "Clearfy Cache Preload iPhone Mobile Bot"
));
}
}
}
public static function put_inline_js()
{
$screen = get_current_screen();
if( $screen->parent_base == "edit" && $screen->base == "post" ) {
?>
<div id="wclearfy-single-preload" class="notice notice-info is-dismissible" style="display: none;">
<p id="wclearfy-single-preload-info"><?php _e('Cache is generated for this content', 'wp-fastest-cache'); ?>
<label style="display: none;" id="wclearfy-single-preload-error">0</label><label id="wclearfy-single-preload-process" style="padding-left: 5px;"><span>0</span>/<span><?php echo count(static::$urls); ?></span></label>
</p>
<script type="text/javascript">
var WclearfySinglePreload = {
error_message: "",
init: function() {
},
change_status: function() {
var type = "";
var cached_number = parseInt(jQuery("#wclearfy-single-preload-process span").first().text());
var total = parseInt(jQuery("#wclearfy-single-preload-process span").last().text());
var error_number = parseInt(jQuery("#wclearfy-single-preload-error").text());
if( cached_number == total ) {
type = "success";
}
if( (error_number + cached_number) == total ) {
if( error_number > cached_number ) {
type = "error";
} else {
type = "success";
}
}
if( type ) {
var class_name = jQuery("#wclearfy-single-preload").attr("class");
class_name = class_name.replace("notice-info", "notice-" + type);
jQuery("#wclearfy-single-preload").attr("class", class_name);
if( type == "success" ) {
jQuery("#wclearfy-single-preload p").text("<?php _e('Cache has been generated for this content successfully', 'wp-fastest-cache');?>");
} else {
if( this.error_message ) {
this.error_message = "<?php _e('Cache has NOT been generated for this content successfully', 'wp-fastest-cache');?>" + "<br>" + "<?php _e('Reason:', 'wp-fastest-cache');?>" + " " + this.error_message;
jQuery("#wclearfy-single-preload p").html(this.error_message);
}
}
}
},
increase_error: function() {
var error_number = jQuery("#wclearfy-single-preload-error").text();
error_number = parseInt(error_number) + 1;
jQuery("#wclearfy-single-preload-error").text(error_number);
this.change_status();
},
create_cache: function(url, user_agent) {
var self = this;
jQuery("#wclearfy-single-preload").show();
jQuery.ajax({
type: 'GET',
url: ajaxurl,
data: {
"action": "wclearfy_preload_single",
"url": url,
"user_agent": user_agent
},
dataType: "html",
timeout: 10000,
cache: false,
success: function(data) {
if( data == "true" ) {
var number = jQuery("#wclearfy-single-preload-process span").first().text();
number = parseInt(number) + 1;
jQuery("#wclearfy-single-preload-process span").first().text(number);
} else {
self.error_message = data;
WclearfySinglePreload.increase_error();
}
self.change_status();
},
error: function(error) {
self.error_message = error.statusText;
WclearfySinglePreload.increase_error();
}
});
}
};
jQuery(document).ready(function() {
if( jQuery("#message").find("a").attr("href") ) {
WclearfySinglePreload.init();
<?php
foreach (self::$urls as $key => $value) {
?>
setTimeout(function() {
WclearfySinglePreload.create_cache("<?php echo $value["url"]; ?>", "<?php echo $value["user-agent"]; ?>");
}, <?php echo $key * 500;?>);
<?php
}
?>
}
});
</script>
</div>
<?php
}
}
}
?>

View File

@@ -0,0 +1,462 @@
<?php
class CdnWCLEARFY{
public static function cloudflare_clear_cache($email = false, $key = false, $zoneid = false){
if(!$email && !$key && !$zoneid){
if($cdn_values = get_option("WClearfyCacheCDN")){
$std_obj = json_decode($cdn_values);
foreach ($std_obj as $key => $value) {
if($value->id == "cloudflare"){
$email = $value->cdnurl;
$key = $value->originurl;
break;
}
}
if($email && $key){
$zone = self::cloudflare_get_zone_id($email, $key, false);
if($zone["success"]){
$zoneid = $zone["zoneid"];
}
}
}
}
if($email && $key && $zoneid){
$header = array("method" => "DELETE",
'headers' => array(
"X-Auth-Email" => $email,
"X-Auth-Key" => $key,
"Content-Type" => "application/json"
),
"body" => '{"purge_everything":true}'
);
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/'.$zoneid.'/purge_cache', $header);
}
}
public static function cloudflare_disable_rocket_loader($email = false, $key = false, $zoneid = false){
if($email && $key && $zoneid){
$header = array("method" => "PATCH",
'timeout' => 10,
'headers' => array(
"X-Auth-Email" => $email,
"X-Auth-Key" => $key,
"Content-Type" => "application/json"
),
'body' => '{"value":"off"}'
);
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/'.$zoneid.'/settings/rocket_loader', $header);
if(!$response || is_wp_error($response)){
return array("success" => false, "error_message" => "Unable to disable rocket loader option");
}else{
$body = json_decode(wp_remote_retrieve_body($response));
if($body->success){
return array("success" => true);
}else if(isset($body->errors) && isset($body->errors[0])){
return array("success" => false, "error_message" => $body->errors[0]->message);
}else{
return array("success" => false, "error_message" => "Unknown error: 101");
}
}
return array("success" => false, "error_message" => "Unknown error");
}
}
public static function cloudflare_set_browser_caching($email = false, $key = false, $zoneid = false){
if($email && $key && $zoneid){
$header = array("method" => "PATCH",
'timeout' => 10,
'headers' => array(
"X-Auth-Email" => $email,
"X-Auth-Key" => $key,
"Content-Type" => "application/json"
),
'body' => '{"value":16070400}'
);
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/'.$zoneid.'/settings/browser_cache_ttl', $header);
if(!$response || is_wp_error($response)){
return array("success" => false, "error_message" => "Unable to set the browser caching option");
}else{
$body = json_decode(wp_remote_retrieve_body($response));
if($body->success){
return array("success" => true);
}else if(isset($body->errors) && isset($body->errors[0])){
return array("success" => false, "error_message" => $body->errors[0]->message);
}else{
return array("success" => false, "error_message" => "Unknown error: 101");
}
}
return array("success" => false, "error_message" => "Unknown error");
}
}
public static function cloudflare_disable_minify($email = false, $key = false, $zoneid = false){
if($email && $key && $zoneid){
$header = array("method" => "PATCH",
'timeout' => 10,
'headers' => array(
"X-Auth-Email" => $email,
"X-Auth-Key" => $key,
"Content-Type" => "application/json"
),
'body' => '{"value":{"css":"off","html":"off","js":"off"}}'
);
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/'.$zoneid.'/settings/minify', $header);
if(!$response || is_wp_error($response)){
return array("success" => false, "error_message" => "Unable to disable minify options");
}else{
$body = json_decode(wp_remote_retrieve_body($response));
if($body->success){
return array("success" => true);
}else if(isset($body->errors) && isset($body->errors[0])){
return array("success" => false, "error_message" => $body->errors[0]->message);
}else{
return array("success" => false, "error_message" => "Unknown error: 101");
}
}
return array("success" => false, "error_message" => "Unknown error");
}else{
wp_die("bad request");
}
}
public static function cloudflare_get_zone_id($email = false, $key = false){
$hostname = preg_replace("/^(https?\:\/\/)?(www\d*\.)?/", "", $_SERVER["HTTP_HOST"]);
if(function_exists("idn_to_utf8")){
$hostname = idn_to_utf8($hostname);
}
$header = array("method" => "GET",
'headers' => array(
"X-Auth-Email" => $email,
"X-Auth-Key" => $key,
"Content-Type" => "application/json"
),
);
/*
status=active has been removed because status may be "pending"
*/
$response = wp_remote_request('https://api.cloudflare.com/client/v4/zones/?page=1&per_page=1000', $header);
if(!$response || is_wp_error($response)){
$res = array("success" => false, "error_message" => $response->get_error_message());
}else{
$zone = json_decode(wp_remote_retrieve_body($response));
if(isset($zone->errors) && isset($zone->errors[0])){
$res = array("success" => false, "error_message" => $zone->errors[0]->message);
}else{
if(isset($zone->result) && isset($zone->result[0])){
foreach ($zone->result as $zone_key => $zone_value) {
if(preg_match("/".$zone_value->name."/", $hostname)){
$res = array("success" => true,
"zoneid" => $zone_value->id,
"plan" => $zone_value->plan->legacy_id);
}
}
if(!$res["success"]){
$res = array("success" => false, "error_message" => "No zone name ".$hostname);
}
}else{
$res = array("success" => false, "error_message" => "There is no zone");
}
}
}
return $res;
}
public static function cloudflare_remove_webp(){
$path = ABSPATH.".htaccess";
if(file_exists($path)){
if(is_writable($path)){
$htaccess = file_get_contents($path);
$htaccess = preg_replace("/#\s?BEGIN\s?WEBPWClearfyCache.*?#\s?END\s?WEBPWClearfyCache/s", "", $htaccess);
file_put_contents($path, $htaccess);
}
}
}
public static function cloudflare_change_settings(){
//admin OR author OR editor
if(current_user_can('manage_options') || current_user_can('delete_published_posts') || current_user_can('edit_published_posts')){
if(isset($_GET["url"]) && isset($_GET["origin_url"])){
$email = $_GET["url"];
$key = $_GET["origin_url"];
}
$zone = CdnWCLEARFY::cloudflare_get_zone_id($email, $key);
if($zone["success"]){
$minify = CdnWCLEARFY::cloudflare_disable_minify($email, $key, $zone["zoneid"]);
$rocket_loader = CdnWCLEARFY::cloudflare_disable_rocket_loader($email, $key, $zone["zoneid"]);
$purge_cache = CdnWCLEARFY::cloudflare_clear_cache($email, $key, $zone["zoneid"]);
$browser_caching = CdnWCLEARFY::cloudflare_set_browser_caching($email, $key, $zone["zoneid"]);
if($zone["plan"] == "free"){
CdnWCLEARFY::cloudflare_remove_webp();;
}
if($minify["success"]){
if($rocket_loader["success"]){
if($browser_caching["success"]){
$res = array("success" => true);
}else{
$res = array("success" => false, "error_message" => $browser_caching["error_message"]);
}
}else{
$res = array("success" => false, "error_message" => $rocket_loader["error_message"]);
}
}else{
$res = array("success" => false, "error_message" => $minify["error_message"]);
}
}else{
$res = $zone;
}
wp_send_json($res);
}else{
wp_die("Must be admin");
}
}
public static function check_url(){
if(current_user_can('manage_options')){
if(isset($_GET["type"]) && $_GET["type"] == "cloudflare"){
CdnWCLEARFY::cloudflare_change_settings();
}
if(preg_match("/wp\.com/", $_GET["url"]) || $_GET["url"] == "random"){
wp_send_json(array("success" => true));
}
$host = str_replace("www.", "", $_SERVER["HTTP_HOST"]);
$_GET["url"] = esc_url_raw($_GET["url"]);
if(!preg_match("/^http/", $_GET["url"])){
$_GET["url"] = "http://".$_GET["url"];
}
if(preg_match("/^https/i", site_url()) && preg_match("/^https/i", home_url())){
$_GET["url"] = preg_replace("/http\:\/\//i", "https://", $_GET["url"]);
}
$response = wp_remote_get($_GET["url"], array('timeout' => 20, 'user-agent' => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:64.0) Gecko/20100101 Firefox/64.0"));
$header = wp_remote_retrieve_headers($response);
if ( !$response || is_wp_error( $response ) ) {
$res = array("success" => false, "error_message" => $response->get_error_message());
if($response->get_error_code() == "http_request_failed"){
if($response->get_error_message() == "Failure when receiving data from the peer"){
$res = array("success" => true);
}else if(preg_match("/cURL\serror\s60/i", $response->get_error_message())){
//cURL error 60: SSL: no alternative certificate subject name matches target host name
$res = array("success" => false, "error_message" => "<a href='https://www.wpfastestcache.com/warnings/how-to-use-cdn-on-ssl-sites/' target='_blank'>Please Read: https://www.wpfastestcache.com/warnings/how-to-use-cdn-on-ssl-sites/</a>");
}else if(preg_match("/cURL\serror\s6/i", $response->get_error_message())){
//cURL error 6: Couldn't resolve host
if(preg_match("/".preg_quote($host, "/")."/i", $_GET["url"])){
$res = array("success" => true);
}
}
}
}else{
$response_code = wp_remote_retrieve_response_code( $response );
if($response_code == 200){
$res = array("success" => true);
}else{
if(method_exists($response, "get_error_message")){
$res = array("success" => false, "error_message" => $response->get_error_message());
}else{
$res = array("success" => false, "error_message" => wp_remote_retrieve_response_message($response));
}
if(isset($header["server"]) && preg_match("/squid/i", $header["server"])){
$res = array("success" => true);
}
if(($response_code == 401) && (preg_match("/res\.cloudinary\.com/i", $_GET["url"]))){
$res = array("success" => true);
}
if(($response_code == 403) && (preg_match("/stackpathdns\.com/i", $_GET["url"]))){
$res = array("success" => true);
}
if(($response_code == 403) && (preg_match("/cloudfront\.net/i", $_GET["url"]))){
$res = array("success" => false, "error_message" => "<a href='https://www.wpfastestcache.com/warnings/amazon-s3-cloudfront-access-denied-403-forbidden/' target='_blank'>Please Read: https://www.wpfastestcache.com/warnings/amazon-s3-cloudfront-access-denied-403-forbidden</a>");
}
}
}
wp_send_json($res);
}else{
wp_die("Must be admin");
}
}
public static function cdn_options(){
if(current_user_can('manage_options')){
$cdn_values = get_option("WClearfyCacheCDN");
if($cdn_values){
echo $cdn_values;
}else{
echo json_encode(array("success" => false));
}
exit;
}else{
wp_die("Must be admin");
}
}
public static function remove_cdn_integration(){
if(current_user_can('manage_options')){
$cdn_values = get_option("WClearfyCacheCDN");
if($cdn_values){
$std_obj = json_decode($cdn_values);
$cdn_values_arr = array();
if(is_array($std_obj)){
$cdn_values_arr = $std_obj;
}else{
array_push($cdn_values_arr, $std_obj);
}
foreach ($cdn_values_arr as $cdn_key => $cdn_value) {
if($cdn_value->id == "amazonaws" || $cdn_value->id == "keycdn" || $cdn_value->id == "cdn77"){
$cdn_value->id = "other";
}
if($cdn_value->id == $_POST["id"]){
unset($cdn_values_arr[$cdn_key]);
}
}
$cdn_values_arr = array_values($cdn_values_arr);
}
if(count($cdn_values_arr) > 0){
update_option("WClearfyCacheCDN", json_encode($cdn_values_arr));
}else{
delete_option("WClearfyCacheCDN");
}
echo json_encode(array("success" => true));
exit;
}else{
wp_die("Must be admin");
}
}
public static function cdn_template(){
if(current_user_can('manage_options')){
if($_POST["id"] == "maxcdn"){
$path = WCLEARFY_MAIN_PATH."templates/cdn/maxcdn.php";
}else if($_POST["id"] == "other"){
$path = WCLEARFY_MAIN_PATH."templates/cdn/other.php";
}else if($_POST["id"] == "photon"){
$path = WCLEARFY_MAIN_PATH."templates/cdn/photon.php";
}else if($_POST["id"] == "cloudflare"){
$path = WCLEARFY_MAIN_PATH."templates/cdn/cloudflare.php";
}else{
die("Wrong cdn");
}
ob_start();
include_once($path);
$content = ob_get_contents();
ob_end_clean();
$res = array("success" => false, "content" => "");
if($data = @file_get_contents($path)){
$res["success"] = true;
$res["content"] = $content;
}
echo json_encode($res);
exit;
}else{
wp_die("Must be admin");
}
}
public static function save_cdn_integration(){
if(current_user_can('manage_options')){
if(isset($_POST) && isset($_POST["values"])){
foreach ($_POST["values"] as $val_key => &$val_value) {
$val_value = sanitize_text_field($val_value);
}
}
if($data = get_option("WClearfyCacheCDN")){
$cdn_exist = false;
$arr = json_decode($data);
if(is_array($arr)){
foreach ($arr as $cdn_key => &$cdn_value) {
if($cdn_value->id == $_POST["values"]["id"]){
$cdn_value = $_POST["values"];
$cdn_exist = true;
}
}
if(!$cdn_exist){
array_push($arr, $_POST["values"]);
}
update_option("WClearfyCacheCDN", json_encode($arr));
}else{
$tmp_arr = array();
if($arr->id == $_POST["values"]["id"]){
array_push($tmp_arr, $_POST["values"]);
}else{
array_push($tmp_arr, $arr);
array_push($tmp_arr, $_POST["values"]);
}
update_option("WClearfyCacheCDN", json_encode($tmp_arr));
}
}else{
$arr = array();
array_push($arr, $_POST["values"]);
add_option("WClearfyCacheCDN", json_encode($arr), null, "yes");
}
echo json_encode(array("success" => true));
exit;
}else{
wp_die("Must be admin");
}
}
}
?>

View File

@@ -0,0 +1,160 @@
<?php
class WCL_WidgetCache {
public static function action()
{
add_filter('widget_display_callback', array("WCL_WidgetCache", "create_cache"), 10, 3);
}
public static function add_filter_admin()
{
add_filter('widget_update_callback', array("WCL_WidgetCache", "widget_update"), 5, 3);
add_action('in_widget_form', array("WCL_WidgetCache", 'in_widget_form'), 5, 3);
}
public static function in_widget_form($widget, $return, $instance)
{
$wclearfynot = isset($instance['wclearfynot']) ? $instance['wclearfynot'] : '';
?>
<p>
<input class="checkbox" type="checkbox" id="<?php echo $widget->get_field_id('wclearfynot'); ?>" name="<?php echo $widget->get_field_name('wclearfynot'); ?>" <?php checked(true, $wclearfynot); ?> />
<label for="<?php echo $widget->get_field_id('wclearfynot'); ?>">
<?php _e('Don\'t cache this widget'); ?>
</label>
</p>
<?php
}
public static function widget_update($instance, $new_instance)
{
WCL_Cache_Helpers::rm_folder_recursively(WCL_Cache_Helpers::getWpContentDir("/cache/wclearfy-widget-cache/"));
if( isset($new_instance['wclearfynot']) ) {
$instance['wclearfynot'] = 1;
} else {
if( isset($instance['wclearfynot']) ) {
unset($instance['wclearfynot']);
}
}
return $instance;
}
public static function create_cache($instance, $widget, $args)
{
if( !isset($args["widget_id"]) || !$args["widget_id"] ) {
return $instance;
}
if( $instance === false ) {
return $instance;
}
// to return instance if not to cache widget
if( isset($instance["wclearfynot"]) ) {
return $instance;
}
// to exclude WooCommerce Product Categories automatically if show_children_only has been set
if( isset($instance["show_children_only"]) ) {
return $instance;
}
// to exclude fixed widget Q2W3 Fixed Widget
if( isset($instance["q2w3_fixed_widget"]) ) {
return $instance;
}
// to exclude Ninja Forms
if( preg_match("/^ninja_forms_widget/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude WPML Multilingual Language Switcher
if( preg_match("/^icl_lang_sel_widget/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude Yuzo Related Posts
if( preg_match("/^yuzo_widget/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude Amazon Affiliate for WordPress
if( preg_match("/^aawp_widget_/i", $args["widget_id"]) ) {
return $instance;
}
// Flagman theme
if( preg_match("/^ct_slider_widget_/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude woocommerce product filter
if( preg_match("/^woof_widget/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude woocommerce product filter
if( preg_match("/^woocommerce_price_filter/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude Bridge Woocommerce Dropdown Cart
if( preg_match("/^woocommerce-dropdown-cart/i", $args["widget_id"]) ) {
return $instance;
}
// to exclude woocommerce product filter
// https://mihajlovicnenad.com/product-filter/
if( preg_match("/^prdctfltr/i", $args["widget_id"]) ) {
return $instance;
}
$create_cache = false;
$path = WCL_Cache_Helpers::getWpContentDir("/cache/wclearfy-widget-cache/" . $args["widget_id"] . ".html");
//to get cache
if( file_exists($path) ) {
if( $data = @file_get_contents($path) ) {
echo $data;
return false;
}
}
//to get the content of Widget
ob_start();
$widget->widget($args, $instance);
$cached_widget = ob_get_clean();
//to create cache
if( $cached_widget ) {
if( !is_dir(WCL_Cache_Helpers::getWpContentDir("/cache/wclearfy-widget-cache")) ) {
if( @mkdir(WCL_Cache_Helpers::getWpContentDir("/cache/wclearfy-widget-cache"), 0755, true) ) {
$create_cache = true;
}
} else {
$create_cache = true;
}
//to exclude the widgets which contains nonce value
//<input type="hidden" id="poll_1_nonce" name="wp-polls-nonce" value="fdd28cece7" />
if( preg_match("/<input[^\>]+hidden[^\>]+nonce[^\>]+>/", $cached_widget) || preg_match("/<input[^\>]+nonce[^\>]+hidden[^\>]+>/", $cached_widget) ) {
$create_cache = false;
}
if( $create_cache ) {
@file_put_contents($path, $cached_widget);
}
}
echo $cached_widget;
return false;
}
}
?>