Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 2637
0.00% covered (danger)
0.00%
0 / 124
CRAP
n/a
0 / 0
wpsc_init
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
72
wp_super_cache_init_action
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
wp_cache_set_home
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
wpsc_enqueue_styles
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
get_wpcachehome
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
wpsc_remove_advanced_cache
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
wpsupercache_uninstall
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
wpsupercache_deactivate
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
6
wpsupercache_activate
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
42
wpsupercache_site_admin
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
wp_cache_add_pages
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
wp_cache_network_pages
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
wp_super_cache_admin_enqueue_scripts
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
6
wpsc_is_boost_installed
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
wpsc_is_boost_active
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
wpsc_hide_boost_banner
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
wpsc_ajax_activate_boost
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
wpsc_jetpack_boost_install_banner
0.00% covered (danger)
0.00%
0 / 31
0.00% covered (danger)
0.00%
0 / 1
56
wp_cache_manager_error_checks
0.00% covered (danger)
0.00%
0 / 160
0.00% covered (danger)
0.00%
0 / 1
8010
wp_cache_manager_updates
0.00% covered (danger)
0.00%
0 / 145
0.00% covered (danger)
0.00%
0 / 1
3192
wp_cache_manager
0.00% covered (danger)
0.00%
0 / 296
0.00% covered (danger)
0.00%
0 / 1
2352
wpsc_plugins_tab
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
30
wpsc_admin_tabs
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
30
wpsc_restore_settings
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
comment_form_lockdown_message
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
wp_update_lock_down
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
72
wpsc_update_direct_pages
0.00% covered (danger)
0.00%
0 / 52
0.00% covered (danger)
0.00%
0 / 1
930
wpsc_lockdown
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
RecursiveFolderDelete
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
56
wp_cache_time_update
0.00% covered (danger)
0.00%
0 / 54
0.00% covered (danger)
0.00%
0 / 1
552
wp_cache_sanitize_value
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
wp_cache_update_rejected_ua
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
wpsc_edit_rejected_ua
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
wp_cache_update_rejected_pages
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
wpsc_update_tracking_parameters
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
wpsc_edit_tracking_parameters
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
wp_cache_update_rejected_cookies
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
wp_cache_update_rejected_strings
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
wp_cache_update_accepted_strings
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
wpsc_update_debug_settings
0.00% covered (danger)
0.00%
0 / 62
0.00% covered (danger)
0.00%
0 / 1
462
wp_cache_enable
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
wp_cache_disable
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
wp_super_cache_enable
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
30
wp_super_cache_disable
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
56
wp_cache_is_enabled
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
wp_cache_remove_index
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
90
wp_cache_index_notice
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
56
wpsc_config_file_notices
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
90
wpsc_dismiss_indexhtml_warning
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
wp_cache_logout_all
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
wp_cache_add_index_protection
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
182
wp_cache_add_site_cache_index
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
110
wp_cache_verify_cache_dir
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
90
wp_cache_verify_config_file
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
182
wp_cache_create_advanced_cache
0.00% covered (danger)
0.00%
0 / 39
0.00% covered (danger)
0.00%
0 / 1
306
wpsc_identify_advanced_cache
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
wpsc_check_advanced_cache
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 1
90
wp_cache_check_global_config
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
110
wpsc_generate_sizes_array
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
wp_cache_format_fsize
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
wp_cache_regenerate_cache_file_stats
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
182
wp_cache_files
0.00% covered (danger)
0.00%
0 / 128
0.00% covered (danger)
0.00%
0 / 1
3306
wp_cache_delete_buttons
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
12
delete_cache_dashboard
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
30
wpsc_dirsize
0.00% covered (danger)
0.00%
0 / 37
0.00% covered (danger)
0.00%
0 / 1
552
wp_cache_clean_cache
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
72
wpsc_delete_post_cache
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
wp_cache_clean_legacy_files
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
132
wp_cache_clean_expired
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
156
wpsc_remove_marker
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
90
wp_cache_catch_404
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
wp_cache_favorite_action
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
wp_cache_plugin_notice
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
20
wp_cache_plugin_actions
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
wp_cache_admin_notice
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
110
wp_cache_check_site
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
210
update_cached_mobile_ua_list
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
wpsc_update_htaccess
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
wpsc_update_htaccess_form
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
30
wpsc_get_logged_in_cookie
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
wpsc_get_htaccess_info
0.00% covered (danger)
0.00%
0 / 125
0.00% covered (danger)
0.00%
0 / 1
600
clear_post_supercache
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
wpsc_ajax_get_preload_status
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
wpsc_get_preload_status_file_path
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
wpsc_get_next_preload_time
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
wpsc_get_preload_status
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
wpsc_update_active_preload
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
6
wpsc_update_idle_preload
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
wp_cron_preload_cache
0.00% covered (danger)
0.00%
0 / 165
0.00% covered (danger)
0.00%
0 / 1
2970
wpsc_schedule_next_preload
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
option_preload_cache_counter
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
check_up_on_preloading
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
30
wp_cache_disable_plugin
0.00% covered (danger)
0.00%
0 / 38
0.00% covered (danger)
0.00%
0 / 1
420
uninstall_supercache
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
56
supercache_admin_bar_render
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
wpsc_is_preload_active
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
72
wpsc_reset_preload_counter
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
wpsc_reset_preload_settings
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
6
wpsc_cancel_preload
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
30
wpsc_create_stop_preload_flag
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
wpsc_enable_preload
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
wpsc_get_post_types
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
wpsc_post_count
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
wpsc_get_minimum_preload_interval
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
wpsc_preload_settings
0.00% covered (danger)
0.00%
0 / 50
0.00% covered (danger)
0.00%
0 / 1
462
wpsc_is_preloading
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
wpsc_set_default_gc
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
56
add_mod_rewrite_rules
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
remove_mod_rewrite_rules
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
update_mod_rewrite_rules
0.00% covered (danger)
0.00%
0 / 74
0.00% covered (danger)
0.00%
0 / 1
506
wpsc_feed_update
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
wpsc_get_plugin_list
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
wpsc_update_plugin_list
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
wpsc_add_plugin
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
wpsc_delete_plugin
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
wpsc_get_plugins
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
wpsc_add_cookie
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
wpsc_delete_cookie
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
wpsc_get_cookies
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
wpsc_get_extra_cookies
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
wpsc_update_check
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
wpsc_render_partial
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
30
wpsc_render_header
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
wpsc_render_footer
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/*
3 * Plugin Name: WP Super Cache
4 * Plugin URI: https://wordpress.org/plugins/wp-super-cache/
5 * Description: Very fast caching plugin for WordPress.
6 * Version: 3.0.3
7 * Author: Automattic
8 * Author URI: https://automattic.com/
9 * License: GPL2+
10 * License URI: https://www.gnu.org/licenses/gpl-2.0.txt
11 * Text Domain: wp-super-cache
12 */
13
14/*
15Copyright Automattic and many other contributors.
16
17This program is free software; you can redistribute it and/or modify
18it under the terms of the GNU General Public License as published by
19the Free Software Foundation; either version 2 of the License, or
20(at your option) any later version.
21
22This program is distributed in the hope that it will be useful,
23but WITHOUT ANY WARRANTY; without even the implied warranty of
24MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25GNU General Public License for more details.
26
27You should have received a copy of the GNU General Public License
28along with this program; if not, see <https://www.gnu.org/licenses/>.
29*/
30
31define( 'WPSC_VERSION_ID', '1.12.1' );
32
33require_once( __DIR__. '/inc/delete-cache-button.php');
34require_once( __DIR__. '/inc/preload-notification.php');
35require_once __DIR__ . '/inc/boost.php';
36
37if ( ! function_exists( 'wp_cache_phase2' ) ) {
38    require_once( __DIR__. '/wp-cache-phase2.php');
39}
40
41if ( ! defined( 'PHP_VERSION_ID' ) ) {
42    // For versions of PHP below 5.2.7, this constant doesn't exist.
43    $wpsc_php_version = explode( '.', PHP_VERSION );
44    define( 'PHP_VERSION_ID', intval( $wpsc_php_version[0] * 10000 + $wpsc_php_version[1] * 100 + $wpsc_php_version[2] ) );
45    unset( $wpsc_php_version );
46}
47
48/**
49 * Defines how many posts to preload per loop.
50 */
51if ( ! defined( 'WPSC_PRELOAD_POST_COUNT' ) ) {
52    define( 'WPSC_PRELOAD_POST_COUNT', 10 );
53}
54
55/**
56 * Defines the interval in seconds between preloading pages.
57 */
58if ( ! defined( 'WPSC_PRELOAD_POST_INTERVAL' ) ) {
59    define( 'WPSC_PRELOAD_POST_INTERVAL', 1 );
60}
61
62/**
63 * Defines the interval in seconds between preloading loops.
64 */
65if ( ! defined( 'WPSC_PRELOAD_LOOP_INTERVAL' ) ) {
66    define( 'WPSC_PRELOAD_LOOP_INTERVAL', 0 );
67}
68
69function wpsc_init() {
70    global $wp_cache_config_file, $wp_cache_config_file_sample, $wpsc_advanced_cache_dist_filename, $wp_cache_check_wp_config, $wpsc_advanced_cache_filename, $wpsc_promo_links;
71
72    if ( ! defined( 'WPCACHECONFIGPATH' ) ) {
73        define( 'WPCACHECONFIGPATH', WP_CONTENT_DIR );
74    }
75
76    $wp_cache_config_file = WPCACHECONFIGPATH . '/wp-cache-config.php';
77
78    // Centralise the promotional links to other products
79    $wpsc_promo_links = array(
80        'boost'       => 'https://jetpack.com/boost/?utm_source=wporg&utm_medium=plugin&utm_campaign=wp-super-cache&utm_id=wp-super-cache',
81        'photon'      => 'https://jetpack.com/features/design/content-delivery-network/?utm_source=wporg&utm_medium=plugin&utm_campaign=wp-super-cache&utm_id=wp-super-cache',
82        'videopress'  => 'https://jetpack.com/videopress/?utm_source=wporg&utm_medium=plugin&utm_campaign=wp-super-cache&utm_id=wp-super-cache',
83        'crowdsignal' => 'https://crowdsignal.com/?utm_source=wporg&utm_medium=plugin&utm_campaign=wp-super-cache&utm_id=wp-super-cache',
84        'jetpack'     => 'https://jetpack.com/?utm_source=wporg&utm_medium=plugin&utm_campaign=wp-super-cache&utm_id=wp-super-cache',
85    );
86
87    if ( !defined( 'WPCACHEHOME' ) ) {
88        define( 'WPCACHEHOME', __DIR__ . '/' );
89        $wp_cache_config_file_sample = WPCACHEHOME . 'wp-cache-config-sample.php';
90        $wpsc_advanced_cache_dist_filename = WPCACHEHOME . 'advanced-cache.php';
91    } elseif ( realpath( WPCACHEHOME ) != realpath( __DIR__ ) ) {
92        $wp_cache_config_file_sample = __DIR__. '/wp-cache-config-sample.php';
93        $wpsc_advanced_cache_dist_filename = __DIR__. '/advanced-cache.php';
94        if ( ! defined( 'ADVANCEDCACHEPROBLEM' ) ) {
95            define( 'ADVANCEDCACHEPROBLEM', 1 ); // force an update of WPCACHEHOME
96        }
97    } else {
98        $wp_cache_config_file_sample = WPCACHEHOME . 'wp-cache-config-sample.php';
99        $wpsc_advanced_cache_dist_filename = WPCACHEHOME . 'advanced-cache.php';
100    }
101    $wpsc_advanced_cache_filename = WP_CONTENT_DIR . '/advanced-cache.php';
102
103    if ( !defined( 'WP_CACHE' ) || ( defined( 'WP_CACHE' ) && constant( 'WP_CACHE' ) == false ) ) {
104        $wp_cache_check_wp_config = true;
105    }
106}
107
108wpsc_init();
109
110/**
111 * WP-CLI requires explicit declaration of global variables.
112 * It's minimal list of global variables.
113 */
114global $super_cache_enabled, $cache_enabled, $wp_cache_mod_rewrite, $wp_cache_home_path, $cache_path, $file_prefix;
115global $wp_cache_mutex_disabled, $mutex_filename, $sem_id, $wp_super_cache_late_init;
116global $cache_compression, $cache_max_time, $wp_cache_shutdown_gc, $cache_rebuild_files;
117global $wp_super_cache_debug, $wp_super_cache_advanced_debug, $wp_cache_debug_level, $wp_cache_debug_to_file;
118global $wp_cache_debug_log, $wp_cache_debug_ip, $wp_cache_debug_username, $wp_cache_debug_email;
119global $cache_time_interval, $cache_scheduled_time, $cache_schedule_interval, $cache_schedule_type, $cache_gc_email_me;
120global $wp_cache_preload_on, $wp_cache_preload_interval, $wp_cache_preload_posts, $wp_cache_preload_taxonomies;
121
122// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- these are used by various functions but the linter complains.
123global $wp_cache_preload_email_me, $wp_cache_preload_email_volume;
124global $wp_cache_mobile, $wp_cache_mobile_enabled, $wp_cache_mobile_browsers, $wp_cache_mobile_prefixes;
125global $wp_cache_config_file, $wp_cache_config_file_sample;
126
127// phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
128global $wpsc_advanced_cache_filename, $wpsc_advanced_cache_dist_filename;
129global $wp_cache_phase1_loaded, $blog_cache_dir, $wp_supercache_304, $wp_cache_mfunc_enabled;
130global $wp_cache_front_page_checks, $wpsc_save_headers, $is_nginx, $wpsc_promo_links;
131global $wp_cache_disable_utf8, $wp_cache_not_logged_in, $wp_cache_make_known_anon;
132global $wpsc_tracking_parameters, $wpsc_rejected_cookies, $cache_rejected_uri;
133global $cache_acceptable_files, $wp_super_cache_comments;
134global $wp_super_cache_front_page_check, $wp_super_cache_front_page_clear;
135global $wp_super_cache_front_page_text, $wp_super_cache_front_page_notification;
136global $wpsc_plugins, $wpsc_cookies, $wpsc_version, $wp_cache_clear_on_post_edit;
137// phpcs:enable VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
138// Check is cache config already loaded.
139if ( ! isset( $cache_enabled, $super_cache_enabled, $wp_cache_mod_rewrite, $cache_path ) &&
140    empty( $wp_cache_phase1_loaded ) &&
141    // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
142    ! @include( $wp_cache_config_file )
143) {
144    @include $wp_cache_config_file_sample; // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
145}
146
147include(WPCACHEHOME . 'wp-cache-base.php');
148if ( class_exists( 'WP_REST_Controller' ) ) {
149    include( __DIR__. '/rest/load.php' );
150}
151
152function wp_super_cache_init_action() {
153
154    load_plugin_textdomain( 'wp-super-cache', false, basename( __DIR__ ) . '/languages' );
155
156    wpsc_register_post_hooks();
157}
158add_action( 'init', 'wp_super_cache_init_action' );
159
160function wp_cache_set_home() {
161    global $wp_cache_is_home;
162    $wp_cache_is_home = ( is_front_page() || is_home() );
163    if ( $wp_cache_is_home && is_paged() )
164        $wp_cache_is_home = false;
165}
166add_action( 'template_redirect', 'wp_cache_set_home' );
167
168function wpsc_enqueue_styles() {
169    wp_enqueue_style(
170        'wpsc_styles',
171        plugins_url( 'styling/dashboard.css', __FILE__ ),
172        array(),
173        filemtime( plugin_dir_path( __FILE__ ) . 'styling/dashboard.css' )
174    );
175}
176
177// Check for the page parameter to see if we're on a WPSC page.
178// phpcs:ignore WordPress.Security.NonceVerification.Recommended
179if ( isset( $_GET['page'] ) && $_GET['page'] === 'wpsupercache' ) {
180    add_action( 'admin_enqueue_scripts', 'wpsc_enqueue_styles' );
181}
182
183// OSSDL CDN plugin (https://wordpress.org/plugins/ossdl-cdn-off-linker/)
184include_once( WPCACHEHOME . 'ossdl-cdn.php' );
185
186function get_wpcachehome() {
187    if ( function_exists( '_deprecated_function' ) ) {
188        _deprecated_function( __FUNCTION__, 'WP Super Cache 1.6.5' );
189    }
190
191    if ( ! defined( 'WPCACHEHOME' ) ) {
192        if ( is_file( __DIR__ . '/wp-cache-config-sample.php' ) ) {
193            define( 'WPCACHEHOME', trailingslashit( __DIR__ ) );
194        } elseif ( is_file( __DIR__ . '/wp-super-cache/wp-cache-config-sample.php' ) ) {
195            define( 'WPCACHEHOME', __DIR__ . '/wp-super-cache/' );
196        } else {
197            die( sprintf( esc_html__( 'Please create %s/wp-cache-config.php from wp-super-cache/wp-cache-config-sample.php', 'wp-super-cache' ), esc_attr( WPCACHECONFIGPATH ) ) );
198        }
199    }
200}
201
202function wpsc_remove_advanced_cache() {
203    global $wpsc_advanced_cache_filename;
204    if ( file_exists( $wpsc_advanced_cache_filename ) ) {
205        $file = file_get_contents( $wpsc_advanced_cache_filename );
206        if (
207            strpos( $file, "WP SUPER CACHE 0.8.9.1" ) ||
208            strpos( $file, "WP SUPER CACHE 1.2" )
209        ) {
210            unlink( $wpsc_advanced_cache_filename );
211        }
212    }
213}
214
215function wpsupercache_uninstall() {
216    global $wp_cache_config_file, $cache_path;
217
218    wpsc_remove_advanced_cache();
219
220    if ( file_exists( $wp_cache_config_file ) ) {
221        unlink( $wp_cache_config_file );
222    }
223
224    wp_cache_remove_index();
225
226    if ( ! empty( $cache_path ) ) {
227        @unlink( $cache_path . '.htaccess' );
228        @unlink( $cache_path . 'meta' );
229        @unlink( $cache_path . 'supercache' );
230    }
231
232    wp_clear_scheduled_hook( 'wp_cache_check_site_hook' );
233    wp_clear_scheduled_hook( 'wp_cache_gc' );
234    wp_clear_scheduled_hook( 'wp_cache_gc_watcher' );
235    wp_cache_disable_plugin();
236    delete_site_option( 'wp_super_cache_index_detected' );
237}
238if ( is_admin() ) {
239    register_uninstall_hook( __FILE__, 'wpsupercache_uninstall' );
240}
241
242function wpsupercache_deactivate() {
243    global $wp_cache_config_file, $wpsc_advanced_cache_filename, $cache_path;
244
245    wpsc_remove_advanced_cache();
246
247    if ( ! empty( $cache_path ) ) {
248        prune_super_cache( $cache_path, true );
249        wp_cache_remove_index();
250        @unlink( $cache_path . '.htaccess' );
251        @unlink( $cache_path . 'meta' );
252        @unlink( $cache_path . 'supercache' );
253    }
254
255    wp_clear_scheduled_hook( 'wp_cache_check_site_hook' );
256    wp_clear_scheduled_hook( 'wp_cache_gc' );
257    wp_clear_scheduled_hook( 'wp_cache_gc_watcher' );
258    wp_cache_replace_line('^ *\$cache_enabled', '$cache_enabled = false;', $wp_cache_config_file);
259    wp_cache_disable_plugin( false ); // don't delete configuration file
260    delete_user_option( get_current_user_id(), 'wpsc_dismissed_boost_banner' );
261}
262register_deactivation_hook( __FILE__, 'wpsupercache_deactivate' );
263
264function wpsupercache_activate() {
265    global $cache_path;
266    if ( ! isset( $cache_path ) || $cache_path == '' )
267        $cache_path = WP_CONTENT_DIR . '/cache/'; // from sample config file
268
269    ob_start();
270    wpsc_init();
271
272    if (
273        ! wp_cache_verify_cache_dir() ||
274        ! wpsc_check_advanced_cache() ||
275        ! wp_cache_verify_config_file()
276    ) {
277        $text = ob_get_contents();
278        ob_end_clean();
279        return false;
280    }
281    $text = ob_get_contents();
282    wp_cache_check_global_config();
283    ob_end_clean();
284    wp_schedule_single_event( time() + 10, 'wp_cache_add_site_cache_index' );
285}
286register_activation_hook( __FILE__, 'wpsupercache_activate' );
287
288function wpsupercache_site_admin() {
289    return current_user_can( 'setup_network' );
290}
291
292function wp_cache_add_pages() {
293    if ( wpsupercache_site_admin() ) {
294        // In single or MS mode add this menu item too, but only for superadmins in MS mode.
295        add_options_page( 'WP Super Cache', 'WP Super Cache', 'manage_options', 'wpsupercache', 'wp_cache_manager' );
296    }
297}
298add_action( 'admin_menu', 'wp_cache_add_pages' );
299
300
301function wp_cache_network_pages() {
302    add_submenu_page( 'settings.php', 'WP Super Cache', 'WP Super Cache', 'manage_options', 'wpsupercache', 'wp_cache_manager' );
303}
304add_action( 'network_admin_menu', 'wp_cache_network_pages' );
305
306/**
307 * Load JavaScript on admin pages.
308 */
309function wp_super_cache_admin_enqueue_scripts( $hook ) {
310    if ( 'settings_page_wpsupercache' !== $hook ) {
311        return;
312    }
313
314    wp_enqueue_script(
315        'wp-super-cache-admin',
316        trailingslashit( plugin_dir_url( __FILE__ ) ) . 'js/admin.js',
317        array( 'jquery' ),
318        WPSC_VERSION_ID,
319        false
320    );
321
322    wp_localize_script(
323        'wp-super-cache-admin',
324        'wpscAdmin',
325        array(
326            'boostNoticeDismissNonce' => wp_create_nonce( 'wpsc_dismiss_boost_notice' ),
327            'boostDismissNonce'       => wp_create_nonce( 'wpsc_dismiss_boost_banner' ),
328            'boostInstallNonce'       => wp_create_nonce( 'updates' ),
329            'boostActivateNonce'      => wp_create_nonce( 'activate-boost' ),
330        )
331    );
332}
333add_action( 'admin_enqueue_scripts', 'wp_super_cache_admin_enqueue_scripts' );
334
335/**
336 * Use the standard WordPress plugin installation ajax handler.
337 */
338add_action( 'wp_ajax_wpsc_install_plugin', 'wp_ajax_install_plugin' );
339
340/**
341 * Check if Jetpack Boost has been installed.
342 */
343function wpsc_is_boost_installed() {
344    $plugins = array_keys( get_plugins() );
345
346    foreach ( $plugins as $plugin ) {
347        if ( str_contains( $plugin, 'jetpack-boost/jetpack-boost.php' ) ) {
348            return true;
349        }
350    }
351
352    return false;
353}
354
355/**
356 * Check if Jetpack Boost is active.
357 */
358function wpsc_is_boost_active() {
359    return class_exists( '\Automattic\Jetpack_Boost\Jetpack_Boost' );
360}
361
362/**
363 * Admin ajax action: hide the Boost Banner.
364 */
365function wpsc_hide_boost_banner() {
366    check_ajax_referer( 'wpsc_dismiss_boost_banner', 'nonce' );
367    update_user_option( get_current_user_id(), 'wpsc_dismissed_boost_banner', '1' );
368
369    wp_die();
370}
371add_action( 'wp_ajax_wpsc-hide-boost-banner', 'wpsc_hide_boost_banner' );
372
373/**
374 * Admin ajax action: activate Jetpack Boost.
375 */
376function wpsc_ajax_activate_boost() {
377    check_ajax_referer( 'activate-boost' );
378
379    if ( ! isset( $_POST['source'] ) ) {
380        wp_send_json_error( 'no source specified', null, JSON_UNESCAPED_SLASHES );
381    }
382
383    $source = sanitize_text_field( wp_unslash( $_POST['source'] ) );
384    $result = activate_plugin( 'jetpack-boost/jetpack-boost.php' );
385    if ( is_wp_error( $result ) ) {
386        wp_send_json_error( $result->get_error_message(), null, JSON_UNESCAPED_SLASHES );
387    }
388
389    wpsc_notify_migration_to_boost( $source );
390
391    wp_send_json_success( null, null, JSON_UNESCAPED_SLASHES );
392}
393add_action( 'wp_ajax_wpsc_activate_boost', 'wpsc_ajax_activate_boost' );
394
395/**
396 * Show a Jetpack Boost installation banner (unless dismissed or installed)
397 */
398function wpsc_jetpack_boost_install_banner() {
399    if ( ! wpsc_is_boost_current() ) {
400        return;
401    }
402    // Don't show the banner if Boost is installed, or the banner has been dismissed.
403    $is_dismissed = '1' === get_user_option( 'wpsc_dismissed_boost_banner' );
404    if ( wpsc_is_boost_active() || $is_dismissed ) {
405        return;
406    }
407
408    $config       = wpsc_get_boost_migration_config();
409    $button_url   = $config['is_installed'] ? $config['activate_url'] : $config['install_url'];
410    $button_label = $config['is_installed'] ? __( 'Set up Jetpack Boost', 'wp-super-cache' ) : __( 'Install Jetpack Boost', 'wp-super-cache' );
411    $button_class = $config['is_installed'] ? 'wpsc-activate-boost-button' : 'wpsc-install-boost-button';
412    $plugin_url   = plugin_dir_url( __FILE__ );
413
414    ?>
415        <div class="wpsc-boost-banner">
416            <div class="wpsc-boost-banner-inner">
417                <div class="wpsc-boost-banner-content">
418                    <img style="width:282px" src="<?php echo esc_url( $plugin_url . '/assets/jetpack-logo.svg' ); ?>" height="36" />
419
420                    <h3>
421                        <?php esc_html_e( 'Speed up your site with our top&#8209;rated performance tool', 'wp-super-cache' ); ?>
422                    </h3>
423
424                    <p id="wpsc-install-invitation">
425                        <?php
426                            esc_html_e(
427                                'Caching is a great start, but there is more to maximize your site speed. Find out how much your cache speeds up your site and make it blazing fast with Jetpack Boost, the easiest WordPress speed optimization plugin developed by WP Super Cache engineers.',
428                                'wp-super-cache'
429                            );
430                        ?>
431                    </p>
432
433                    <div class="wpsc-boost-migration-error" style="display:none; color:red; margin-bottom: 20px;"></div>
434
435                    <div style="display: flex; gap: 24px;">
436                        <a style="font-weight: 500; line-height: 1; padding: 10px 20px 15px;" data-source='banner' href="<?php echo esc_url( $button_url ); ?>" class="wpsc-boost-migration-button button button-primary <?php echo esc_attr( $button_class ); ?>">
437                            <div class='spinner' style='display:none; margin-top: 8px'></div>
438                            <label><?php echo esc_html( $button_label ); ?></label>
439                        </a>
440                        <a style="display: flex; align-items: center; font-weight: 500; color: #000; " href="https://jetpack.com/blog/discover-how-to-improve-your-site-performance-with-jetpack-boost/">
441                            Learn More
442                        </a>
443                    </div>
444                </div>
445
446                <div class="wpsc-boost-banner-image-container">
447                    <img
448                        width="350"
449                        height="452"
450                        src="<?php echo esc_url( $plugin_url . 'assets/boost-install-card-main.png' ); ?>"
451                        title="<?php esc_attr_e( 'Check how your web site performance scores for desktop and mobile.', 'wp-super-cache' ); ?>"
452                        alt="<?php esc_attr_e( 'An image showing the Jetpack Boost dashboard.', 'wp-super-cache' ); ?>"
453                        srcset="<?php echo esc_url( $plugin_url . 'assets/boost-install-card-main.png' ); ?> 400w, <?php echo esc_url( $plugin_url . 'assets/boost-install-card-main-2x.png' ); ?> 800w"
454                        sizes="(max-width: 782px) 350px, 700px"
455                    >
456                </div>
457            </div>
458
459            <span class="wpsc-boost-dismiss dashicons dashicons-dismiss"></span>
460        </div>
461    <?php
462}
463
464function wp_cache_manager_error_checks() {
465    global $wp_cache_debug, $wp_cache_cron_check, $cache_enabled, $super_cache_enabled, $wp_cache_config_file, $wp_cache_mobile_browsers, $wp_cache_mobile_prefixes, $wp_cache_mobile_browsers, $wp_cache_mobile_enabled, $wp_cache_mod_rewrite;
466    global $dismiss_htaccess_warning, $dismiss_readable_warning, $dismiss_gc_warning, $wp_cache_shutdown_gc, $is_nginx;
467    global $htaccess_path;
468
469    if ( ! wpsupercache_site_admin() ) {
470        return false;
471    }
472
473    // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.safe_modeDeprecatedRemoved -- Version is checked before access.
474    if ( PHP_VERSION_ID < 50300 && ( ini_get( 'safe_mode' ) === '1' || strtolower( ini_get( 'safe_mode' ) ) === 'on' ) ) { // @codingStandardsIgnoreLine
475        echo '<div class="notice notice-error"><h4>' . esc_html__( 'Warning! PHP Safe Mode Enabled!', 'wp-super-cache' ) . '</h4>';
476        echo '<p>' . esc_html__( 'You may experience problems running this plugin because SAFE MODE is enabled.', 'wp-super-cache' ) . '<br />';
477
478        // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.safe_mode_gidDeprecatedRemoved -- Version is checked before access.
479        if ( ! ini_get( 'safe_mode_gid' ) ) { // @codingStandardsIgnoreLine
480            esc_html_e( 'Your server is set up to check the owner of PHP scripts before allowing them to read and write files.', 'wp-super-cache' );
481            echo '<br />';
482            printf( __( 'You or an administrator may be able to make it work by changing the group owner of the plugin scripts to match that of the web server user. The group owner of the %s/cache/ directory must also be changed. See the  <a href="http://php.net/features.safe-mode">safe mode manual page</a> for further details.', 'wp-super-cache' ), esc_attr( WP_CONTENT_DIR ) );
483        } else {
484            _e( 'You or an administrator must disable this. See the <a href="http://php.net/features.safe-mode">safe mode manual page</a> for further details. This cannot be disabled in a .htaccess file unfortunately. It must be done in the php.ini config file.', 'wp-super-cache' );
485        }
486        echo '</p></div>';
487    }
488
489    if ( '' == get_option( 'permalink_structure' ) ) {
490        echo '<div class="notice notice-error"><h4>' . __( 'Permlink Structure Error', 'wp-super-cache' ) . '</h4>';
491        echo "<p>" . __( 'A custom url or permalink structure is required for this plugin to work correctly. Please go to the <a href="options-permalink.php">Permalinks Options Page</a> to configure your permalinks.', 'wp-super-cache' ) . "</p>";
492        echo '</div>';
493        return false;
494    }
495
496    if ( $wp_cache_debug || ! $wp_cache_cron_check ) {
497        if ( defined( 'DISABLE_WP_CRON' ) && constant( 'DISABLE_WP_CRON' ) ) {
498            ?>
499            <div class="notice notice-error"><h4><?php _e( 'CRON System Disabled', 'wp-super-cache' ); ?></h4>
500            <p><?php _e( 'The WordPress CRON jobs system is disabled. This means the garbage collection system will not work unless you run the CRON system manually.', 'wp-super-cache' ); ?></p>
501            </div>
502            <?php
503        } elseif ( function_exists( "wp_remote_get" ) == false ) {
504            $hostname = str_replace( 'http://', '', str_replace( 'https://', '', get_option( 'siteurl' ) ) );
505            if( strpos( $hostname, '/' ) )
506                $hostname = substr( $hostname, 0, strpos( $hostname, '/' ) );
507            $ip = gethostbyname( $hostname );
508            if( substr( $ip, 0, 3 ) == '127' || substr( $ip, 0, 7 ) == '192.168' ) {
509                ?><div class="notice notice-warning"><h4><?php printf( __( 'Warning! Your hostname "%s" resolves to %s', 'wp-super-cache' ), $hostname, $ip ); ?></h4>
510                    <p><?php printf( __( 'Your server thinks your hostname resolves to %s. Some services such as garbage collection by this plugin, and WordPress scheduled posts may not operate correctly.', 'wp-super-cache' ), $ip ); ?></p>
511                    <p><?php printf( __( 'Please see entry 16 in the <a href="%s">Troubleshooting section</a> of the readme.txt', 'wp-super-cache' ), 'https://wordpress.org/plugins/wp-super-cache/faq/' ); ?></p>
512                    </div>
513                    <?php
514                    return false;
515            } else {
516                wp_cache_replace_line('^ *\$wp_cache_cron_check', "\$wp_cache_cron_check = 1;", $wp_cache_config_file);
517            }
518        } else {
519            $cron_url = get_option( 'siteurl' ) . '/wp-cron.php?check=' . wp_hash('187425');
520            $cron = wp_remote_get($cron_url, array('timeout' => 0.01, 'blocking' => true));
521            if( is_array( $cron ) ) {
522                if( $cron[ 'response' ][ 'code' ] == '404' ) {
523                    ?><div class="notice notice-error"><h4>Warning! wp-cron.php not found!</h4>
524                    <p><?php _e( 'Unfortunately, WordPress cannot find the file wp-cron.php. This script is required for the correct operation of garbage collection by this plugin, WordPress scheduled posts as well as other critical activities.', 'wp-super-cache' ); ?></p>
525                    <p><?php printf( __( 'Please see entry 16 in the <a href="%s">Troubleshooting section</a> of the readme.txt', 'wp-super-cache' ), 'https://wordpress.org/plugins/wp-super-cache/faq/' ); ?></p>
526                    </div>
527                    <?php
528                } else {
529                    wp_cache_replace_line('^ *\$wp_cache_cron_check', "\$wp_cache_cron_check = 1;", $wp_cache_config_file);
530                }
531            }
532        }
533    }
534
535    if (
536        ! wpsc_check_advanced_cache() ||
537        ! wp_cache_verify_config_file() ||
538        ! wp_cache_verify_cache_dir()
539    ) {
540        echo '<p>' . __( "Cannot continue... fix previous problems and retry.", 'wp-super-cache' ) . '</p>';
541        return false;
542    }
543
544    if ( false == function_exists( 'wpsc_deep_replace' ) ) {
545        $msg = __( 'Warning! You must set WP_CACHE and WPCACHEHOME in your wp-config.php for this plugin to work correctly:' ) . '<br />';
546        $msg .= "<code>define( 'WP_CACHE', true );</code><br />";
547        $msg .= "<code>define( 'WPCACHEHOME', '" . __DIR__ . "/' );</code><br />";
548        wp_die( $msg );
549    }
550
551    if (!wp_cache_check_global_config()) {
552        return false;
553    }
554
555    if ( 1 == ini_get( 'zlib.output_compression' ) || "on" == strtolower( ini_get( 'zlib.output_compression' ) ) ) {
556        ?><div class="notice notice-warning"><h4><?php _e( 'Zlib Output Compression Enabled!', 'wp-super-cache' ); ?></h4>
557        <p><?php _e( 'PHP is compressing the data sent to the visitors of your site. Disabling this is recommended as the plugin caches the compressed output once instead of compressing the same page over and over again. Also see #21 in the Troubleshooting section. See <a href="http://php.net/manual/en/zlib.configuration.php">this page</a> for instructions on modifying your php.ini.', 'wp-super-cache' ); ?></p></div><?php
558    }
559
560    if (
561        $cache_enabled == true &&
562        $super_cache_enabled == true &&
563        $wp_cache_mod_rewrite &&
564        ! got_mod_rewrite() &&
565        ! $is_nginx
566    ) {
567        ?><div class="notice notice-warning"><h4><?php _e( 'Mod rewrite may not be installed!', 'wp-super-cache' ); ?></h4>
568        <p><?php _e( 'It appears that mod_rewrite is not installed. Sometimes this check isn&#8217;t 100% reliable, especially if you are not using Apache. Please verify that the mod_rewrite module is loaded. It is required for serving Super Cache static files in expert mode. You will still be able to simple mode.', 'wp-super-cache' ); ?></p></div><?php
569    }
570
571    if( !is_writeable_ACLSafe( $wp_cache_config_file ) ) {
572        if ( !defined( 'SUBMITDISABLED' ) )
573            define( "SUBMITDISABLED", 'disabled style="color: #aaa" ' );
574        ?><div class="notice notice-error"><h4><?php _e( 'Read Only Mode. Configuration cannot be changed.', 'wp-super-cache' ); ?></h4>
575        <p><?php printf( __( 'The WP Super Cache configuration file is <code>%s/wp-cache-config.php</code> and cannot be modified. That file must be writeable by the web server to make any changes.', 'wp-super-cache' ), WPCACHECONFIGPATH ); ?>
576        <?php _e( 'A simple way of doing that is by changing the permissions temporarily using the CHMOD command or through your ftp client. Make sure it&#8217;s globally writeable and it should be fine.', 'wp-super-cache' ); ?></p>
577        <p><?php _e( '<a href="https://codex.wordpress.org/Changing_File_Permissions">This page</a> explains how to change file permissions.', 'wp-super-cache' ); ?></p>
578        <?php _e( 'Writeable:', 'wp-super-cache' ); ?> <code>chmod 666 <?php echo WPCACHECONFIGPATH; ?>/wp-cache-config.php</code><br />
579        <?php _e( 'Read-only:', 'wp-super-cache' ); ?> <code>chmod 644 <?php echo WPCACHECONFIGPATH; ?>/wp-cache-config.php</code></p>
580        </div><?php
581    } elseif ( !defined( 'SUBMITDISABLED' ) ) {
582        define( "SUBMITDISABLED", ' ' );
583    }
584
585    $valid_nonce = isset($_REQUEST['_wpnonce']) ? wp_verify_nonce($_REQUEST['_wpnonce'], 'wp-cache') : false;
586    // Check that garbage collection is running
587    if ( $valid_nonce && isset( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'dismiss_gc_warning' ) {
588        wp_cache_replace_line('^ *\$dismiss_gc_warning', "\$dismiss_gc_warning = 1;", $wp_cache_config_file);
589        $dismiss_gc_warning = 1;
590    } elseif ( !isset( $dismiss_gc_warning ) ) {
591        $dismiss_gc_warning = 0;
592    }
593    if ( $cache_enabled && ( !isset( $wp_cache_shutdown_gc ) || $wp_cache_shutdown_gc == 0 ) && function_exists( 'get_gc_flag' ) ) {
594        $gc_flag = get_gc_flag();
595        if ( $dismiss_gc_warning == 0 ) {
596            if ( false == maybe_stop_gc( $gc_flag ) && false == wp_next_scheduled( 'wp_cache_gc' ) ) {
597                ?><div class="notice notice-warning"><h4><?php _e( 'Warning! Garbage collection is not scheduled!', 'wp-super-cache' ); ?></h4>
598                <p><?php _e( 'Garbage collection by this plugin clears out expired and old cached pages on a regular basis. Use <a href="#expirytime">this form</a> to enable it.', 'wp-super-cache' ); ?> </p>
599                <form action="" method="POST">
600                <input type="hidden" name="action" value="dismiss_gc_warning" />
601                <input type="hidden" name="page" value="wpsupercache" />
602                <?php wp_nonce_field( 'wp-cache' ); ?>
603                <input class='button-secondary' type='submit' value='<?php _e( 'Dismiss', 'wp-super-cache' ); ?>' />
604                </form>
605                <br />
606                </div>
607                <?php
608            }
609        }
610    }
611
612    // Server could be running as the owner of the wp-content directory.  Therefore, if it's
613    // writable, issue a warning only if the permissions aren't 755.
614    if ( $valid_nonce && isset( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'dismiss_readable_warning' ) {
615        wp_cache_replace_line('^ *\$dismiss_readable_warning', "\$dismiss_readable_warning = 1;", $wp_cache_config_file);
616        $dismiss_readable_warning = 1;
617    } elseif ( !isset( $dismiss_readable_warning ) ) {
618        $dismiss_readable_warning = 0;
619    }
620    if( $dismiss_readable_warning == 0 && is_writeable_ACLSafe( WP_CONTENT_DIR . '/' ) ) {
621        $wp_content_stat = stat(WP_CONTENT_DIR . '/');
622        $wp_content_mode = decoct( $wp_content_stat[ 'mode' ] & 0777 );
623        if( substr( $wp_content_mode, -2 ) == '77' ) {
624            ?><div class="notice notice-warning"><h4><?php printf( __( 'Warning! %s is writeable!', 'wp-super-cache' ), WP_CONTENT_DIR ); ?></h4>
625            <p><?php printf( __( 'You should change the permissions on %s and make it more restrictive. Use your ftp client, or the following command to fix things:', 'wp-super-cache' ), WP_CONTENT_DIR ); ?> <code>chmod 755 <?php echo WP_CONTENT_DIR; ?>/</code></p>
626            <p><?php _e( '<a href="https://codex.wordpress.org/Changing_File_Permissions">This page</a> explains how to change file permissions.', 'wp-super-cache' ); ?></p>
627            <form action="" method="POST">
628            <input type="hidden" name="action" value="dismiss_readable_warning" />
629            <input type="hidden" name="page" value="wpsupercache" />
630            <?php wp_nonce_field( 'wp-cache' ); ?>
631            <input class='button-secondary' type='submit' value='<?php _e( 'Dismiss', 'wp-super-cache' ); ?>' />
632            </form>
633            <br />
634            </div>
635            <?php
636        }
637    }
638
639    if ( ! $is_nginx && function_exists( "is_main_site" ) && true == is_main_site() ) {
640        if ( ! isset( $htaccess_path ) ) {
641            $home_path = trailingslashit( get_home_path() );
642        } else {
643            $home_path = $htaccess_path;
644        }
645
646        $scrules = implode( "\n", extract_from_markers( $home_path . '.htaccess', 'WPSuperCache' ) );
647        if (
648            $cache_enabled
649            && $wp_cache_mod_rewrite
650            && ! $wp_cache_mobile_enabled
651            && strpos( $scrules, addcslashes( str_replace( ', ', '|', $wp_cache_mobile_browsers ), ' ' ) )
652        ) {
653            echo '<div class="notice notice-warning"><h4>' . esc_html__( 'Mobile rewrite rules detected', 'wp-super-cache' ) . '</h4>';
654            echo '<p>' . esc_html__( 'For best performance you should enable "Mobile device support" or delete the mobile rewrite rules in your .htaccess. Look for the 2 lines with the text "2.0\ MMP|240x320" and delete those.', 'wp-super-cache' ) . '</p><p>' . esc_html__( 'This will have no affect on ordinary users but mobile users will see uncached pages.', 'wp-super-cache' ) . '</p></div>';
655        } elseif (
656            $wp_cache_mod_rewrite
657            && $cache_enabled
658            && $wp_cache_mobile_enabled
659            && $scrules != '' // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual
660            && (
661                (
662                    '' != $wp_cache_mobile_prefixes // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual
663                    && ! str_contains( $scrules, addcslashes( str_replace( ', ', '|', $wp_cache_mobile_prefixes ), ' ' ) )
664                )
665                || (
666                    '' != $wp_cache_mobile_browsers // phpcs:ignore Universal.Operators.StrictComparisons.LooseNotEqual
667                    && ! str_contains( $scrules, addcslashes( str_replace( ', ', '|', $wp_cache_mobile_browsers ), ' ' ) )
668                )
669            )
670        ) {
671            ?>
672            <div class="notice notice-warning"><h4><?php _e( 'Rewrite rules must be updated', 'wp-super-cache' ); ?></h4>
673            <p><?php _e( 'The rewrite rules required by this plugin have changed or are missing. ', 'wp-super-cache' ); ?>
674            <?php _e( 'Mobile support requires extra rules in your .htaccess file, or you can set the plugin to simple mode. Here are your options (in order of difficulty):', 'wp-super-cache' ); ?>
675            <ol><li> <?php _e( 'Set the plugin to simple mode and enable mobile support.', 'wp-super-cache' ); ?></li>
676            <li> <?php _e( 'Scroll down the Advanced Settings page and click the <strong>Update Mod_Rewrite Rules</strong> button.', 'wp-super-cache' ); ?></li>
677            <li> <?php printf( __( 'Delete the plugin mod_rewrite rules in %s.htaccess enclosed by <code># BEGIN WPSuperCache</code> and <code># END WPSuperCache</code> and let the plugin regenerate them by reloading this page.', 'wp-super-cache' ), $home_path ); ?></li>
678            <li> <?php printf( __( 'Add the rules yourself. Edit %s.htaccess and find the block of code enclosed by the lines <code># BEGIN WPSuperCache</code> and <code># END WPSuperCache</code>. There are two sections that look very similar. Just below the line <code>%%{HTTP:Cookie} !^.*(comment_author_|%s|wp-postpass_).*$</code> add these lines: (do it twice, once for each section)', 'wp-super-cache' ), $home_path, wpsc_get_logged_in_cookie() ); ?></p>
679            <div style='padding: 2px; margin: 2px; border: 1px solid #333; width:400px; overflow: scroll'><pre><?php echo "RewriteCond %{HTTP_user_agent} !^.*(" . addcslashes( str_replace( ', ', '|', $wp_cache_mobile_browsers ), ' ' ) . ").*\nRewriteCond %{HTTP_user_agent} !^(" . addcslashes( str_replace( ', ', '|', $wp_cache_mobile_prefixes ), ' ' ) . ").*"; ?></pre></div></li></ol></div><?php
680        }
681
682        if (
683            $cache_enabled
684            && $super_cache_enabled
685            && $wp_cache_mod_rewrite
686            && $scrules == '' // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
687        ) {
688            ?>
689            <div class='notice notice-warning'><h4><?php esc_html_e( 'Rewrite rules must be updated', 'wp-super-cache' ); ?></h4>
690            <p><?php esc_html_e( 'The rewrite rules required by this plugin have changed or are missing. ', 'wp-super-cache' ); ?>
691            <?php esc_html_e( 'Scroll down the Advanced Settings page and click the <strong>Update Mod_Rewrite Rules</strong> button.', 'wp-super-cache' ); ?></p></div>
692            <?php
693        }
694    }
695
696    if ( ! $is_nginx && $wp_cache_mod_rewrite && $super_cache_enabled && function_exists( 'apache_get_modules' ) ) {
697        $mods = apache_get_modules();
698        $required_modules = array( 'mod_mime' => __( 'Required to serve compressed supercache files properly.', 'wp-super-cache' ), 'mod_headers' => __( 'Required to set caching information on supercache pages. IE7 users will see old pages without this module.', 'wp-super-cache' ), 'mod_expires' => __( 'Set the expiry date on supercached pages. Visitors may not see new pages when they refresh or leave comments without this module.', 'wp-super-cache' ) );
699        foreach( $required_modules as $req => $desc ) {
700            if( !in_array( $req, $mods ) ) {
701                $missing_mods[ $req ] = $desc;
702            }
703        }
704        if( isset( $missing_mods) && is_array( $missing_mods ) ) {
705            ?><div class='notice notice-warning'><h4><?php _e( 'Missing Apache Modules', 'wp-super-cache' ); ?></h4>
706            <p><?php __( 'The following Apache modules are missing. The plugin will work in simple mode without them but in expert mode, your visitors may see corrupted pages or out of date content however.', 'wp-super-cache' ); ?></p><?php
707            echo "<ul>";
708            foreach( $missing_mods as $req => $desc ) {
709                echo "<li> $req - $desc</li>";
710            }
711            echo "</ul>";
712            echo "</div>";
713        }
714    }
715
716    if ( $valid_nonce && isset( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'dismiss_htaccess_warning' ) {
717        wp_cache_replace_line('^ *\$dismiss_htaccess_warning', "\$dismiss_htaccess_warning = 1;", $wp_cache_config_file);
718        $dismiss_htaccess_warning = 1;
719    } elseif ( !isset( $dismiss_htaccess_warning ) ) {
720        $dismiss_htaccess_warning = 0;
721    }
722    if ( ! $is_nginx && $dismiss_htaccess_warning == 0 && $wp_cache_mod_rewrite && $super_cache_enabled && get_option( 'siteurl' ) != get_option( 'home' ) ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual,Universal.Operators.StrictComparisons.LooseNotEqual
723        ?>
724        <div class="notice notice-info"><h4><?php esc_html_e( '.htaccess file may need to be moved', 'wp-super-cache' ); ?></h4>
725        <p><?php _e( 'It appears you have WordPress installed in a sub directory as described <a href="https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory">here</a>. Unfortunately, WordPress writes to the .htaccess in the install directory, not where your site is served from.<br />When you update the rewrite rules in this plugin you will have to copy the file to where your site is hosted. This will be fixed in the future.', 'wp-super-cache' ); ?></p>
726        <form action="" method="POST">
727        <input type="hidden" name="action" value="dismiss_htaccess_warning" />
728        <input type="hidden" name="page" value="wpsupercache" />
729        <?php wp_nonce_field( 'wp-cache' ); ?>
730        <input class='button-secondary' type='submit' value='<?php _e( 'Dismiss', 'wp-super-cache' ); ?>' />
731        </form>
732        <br />
733        </div><?php
734    }
735
736    return true;
737}
738add_filter( 'wp_super_cache_error_checking', 'wp_cache_manager_error_checks' );
739
740function wp_cache_manager_updates() {
741    global $wp_cache_mobile_enabled, $wp_cache_mfunc_enabled, $wp_supercache_cache_list, $wp_cache_config_file, $wp_cache_clear_on_post_edit, $cache_rebuild_files, $wp_cache_mutex_disabled, $wp_cache_not_logged_in, $wp_cache_make_known_anon, $cache_path, $wp_cache_refresh_single_only, $cache_compression, $wp_cache_mod_rewrite, $wp_supercache_304, $wp_super_cache_late_init, $wp_cache_front_page_checks, $cache_page_secret, $wp_cache_disable_utf8, $wp_cache_no_cache_for_get;
742    global $cache_schedule_type, $cache_max_time, $cache_time_interval, $wp_cache_shutdown_gc, $wpsc_save_headers;
743
744    if ( !wpsupercache_site_admin() )
745        return false;
746
747    if ( false == isset( $cache_page_secret ) ) {
748        $cache_page_secret = md5( gmdate( 'H:i:s' ) . wp_rand() );
749        wp_cache_replace_line('^ *\$cache_page_secret', "\$cache_page_secret = '" . $cache_page_secret . "';", $wp_cache_config_file);
750    }
751
752    $valid_nonce = isset($_REQUEST['_wpnonce']) ? wp_verify_nonce($_REQUEST['_wpnonce'], 'wp-cache') : false;
753    if ( $valid_nonce == false )
754        return false;
755
756    if ( isset( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'easysetup' ) {
757        $_POST[ 'action' ] = 'scupdates';
758        if( isset( $_POST[ 'wp_cache_easy_on' ] ) && $_POST[ 'wp_cache_easy_on' ] == 1 ) {
759            $_POST[ 'wp_cache_enabled' ] = 1;
760            $_POST[ 'super_cache_enabled' ] = 1;
761            $_POST[ 'cache_rebuild_files' ] = 1;
762            unset( $_POST[ 'cache_compression' ] );
763            if ( $cache_path != WP_CONTENT_DIR . '/cache/' )
764                $_POST[ 'wp_cache_location' ] = $cache_path;
765            //
766            // set up garbage collection with some default settings
767            if ( ( !isset( $wp_cache_shutdown_gc ) || $wp_cache_shutdown_gc == 0 ) && false == wp_next_scheduled( 'wp_cache_gc' ) ) {
768                if ( false == isset( $cache_schedule_type ) ) {
769                    $cache_schedule_type = 'interval';
770                    $cache_time_interval = 600;
771                    $cache_max_time = 1800;
772                    wp_cache_replace_line('^ *\$cache_schedule_type', "\$cache_schedule_type = '$cache_schedule_type';", $wp_cache_config_file);
773                    wp_cache_replace_line('^ *\$cache_time_interval', "\$cache_time_interval = '$cache_time_interval';", $wp_cache_config_file);
774                    wp_cache_replace_line('^ *\$cache_max_time', "\$cache_max_time = '$cache_max_time';", $wp_cache_config_file);
775                }
776                wp_schedule_single_event( time() + 600, 'wp_cache_gc' );
777            }
778
779        } else {
780            unset( $_POST[ 'wp_cache_enabled' ] );
781            wp_clear_scheduled_hook( 'wp_cache_check_site_hook' );
782            wp_clear_scheduled_hook( 'wp_cache_gc' );
783            wp_clear_scheduled_hook( 'wp_cache_gc_watcher' );
784        }
785        $advanced_settings = array( 'wp_super_cache_late_init', 'wp_cache_disable_utf8', 'wp_cache_no_cache_for_get', 'wp_supercache_304', 'wp_cache_mfunc_enabled', 'wp_cache_front_page_checks', 'wp_supercache_cache_list', 'wp_cache_clear_on_post_edit', 'wp_cache_make_known_anon', 'wp_cache_refresh_single_only', 'cache_compression' );
786        foreach( $advanced_settings as $setting ) {
787            if ( isset( $GLOBALS[ $setting ] ) && $GLOBALS[ $setting ] == 1 ) {
788                $_POST[ $setting ] = 1;
789            }
790        }
791        $_POST['wp_cache_not_logged_in'] = 2;
792    }
793
794    if( isset( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'scupdates' ) {
795        if( isset( $_POST[ 'wp_cache_location' ] ) && $_POST[ 'wp_cache_location' ] != '' ) {
796            $dir = realpath( trailingslashit( dirname( $_POST[ 'wp_cache_location' ] ) ) );
797            if ( $dir === realpath( '.' ) || false === $dir ) {
798                $dir = WP_CONTENT_DIR . '/cache/';
799            } else {
800                $dir = trailingslashit( $dir ) . trailingslashit(wpsc_deep_replace( array( '..', '\\' ), basename( $_POST[ 'wp_cache_location' ] ) ) );
801            }
802            $new_cache_path = $dir;
803        } else {
804            $new_cache_path = WP_CONTENT_DIR . '/cache/';
805        }
806        if ( $new_cache_path != $cache_path ) {
807            if ( file_exists( $new_cache_path ) == false )
808                rename( $cache_path, $new_cache_path );
809            $cache_path = preg_replace('/[ <>\'\"\r\n\t\(\)\$\[\];#]/', '', $new_cache_path );
810            wp_cache_replace_line('^ *\$cache_path', "\$cache_path = " . var_export( $cache_path, true ) . ";", $wp_cache_config_file);
811        }
812
813        if( isset( $_POST[ 'wp_super_cache_late_init' ] ) ) {
814            $wp_super_cache_late_init = 1;
815        } else {
816            $wp_super_cache_late_init = 0;
817        }
818        wp_cache_replace_line('^ *\$wp_super_cache_late_init', "\$wp_super_cache_late_init = " . $wp_super_cache_late_init . ";", $wp_cache_config_file);
819
820        if( isset( $_POST[ 'wp_cache_disable_utf8' ] ) ) {
821            $wp_cache_disable_utf8 = 1;
822        } else {
823            $wp_cache_disable_utf8 = 0;
824        }
825        wp_cache_replace_line('^ *\$wp_cache_disable_utf8', "\$wp_cache_disable_utf8 = " . $wp_cache_disable_utf8 . ";", $wp_cache_config_file);
826
827        if( isset( $_POST[ 'wp_cache_no_cache_for_get' ] ) ) {
828            $wp_cache_no_cache_for_get = 1;
829        } else {
830            $wp_cache_no_cache_for_get = 0;
831        }
832        wp_cache_replace_line('^ *\$wp_cache_no_cache_for_get', "\$wp_cache_no_cache_for_get = " . $wp_cache_no_cache_for_get . ";", $wp_cache_config_file);
833
834        if( isset( $_POST[ 'wp_supercache_304' ] ) ) {
835            $wp_supercache_304 = 1;
836        } else {
837            $wp_supercache_304 = 0;
838        }
839        wp_cache_replace_line('^ *\$wp_supercache_304', "\$wp_supercache_304 = " . $wp_supercache_304 . ";", $wp_cache_config_file);
840
841        if( isset( $_POST[ 'wp_cache_mfunc_enabled' ] ) ) {
842            $wp_cache_mfunc_enabled = 1;
843        } else {
844            $wp_cache_mfunc_enabled = 0;
845        }
846        wp_cache_replace_line('^ *\$wp_cache_mfunc_enabled', "\$wp_cache_mfunc_enabled = " . $wp_cache_mfunc_enabled . ";", $wp_cache_config_file);
847
848        if( isset( $_POST[ 'wp_cache_mobile_enabled' ] ) ) {
849            $wp_cache_mobile_enabled = 1;
850        } else {
851            $wp_cache_mobile_enabled = 0;
852        }
853        wp_cache_replace_line('^ *\$wp_cache_mobile_enabled', "\$wp_cache_mobile_enabled = " . $wp_cache_mobile_enabled . ";", $wp_cache_config_file);
854
855        if( isset( $_POST[ 'wp_cache_front_page_checks' ] ) ) {
856            $wp_cache_front_page_checks = 1;
857        } else {
858            $wp_cache_front_page_checks = 0;
859        }
860        wp_cache_replace_line('^ *\$wp_cache_front_page_checks', "\$wp_cache_front_page_checks = " . $wp_cache_front_page_checks . ";", $wp_cache_config_file);
861
862        if( isset( $_POST[ 'wp_supercache_cache_list' ] ) ) {
863            $wp_supercache_cache_list = 1;
864        } else {
865            $wp_supercache_cache_list = 0;
866        }
867        wp_cache_replace_line('^ *\$wp_supercache_cache_list', "\$wp_supercache_cache_list = " . $wp_supercache_cache_list . ";", $wp_cache_config_file);
868
869        if ( isset( $_POST[ 'wp_cache_enabled' ] ) ) {
870            wp_cache_enable();
871            if ( ! defined( 'DISABLE_SUPERCACHE' ) ) {
872                wp_cache_debug( 'DISABLE_SUPERCACHE is not set, super_cache enabled.' );
873                wp_super_cache_enable();
874                $super_cache_enabled = true;
875            }
876        } else {
877            wp_cache_disable();
878            wp_super_cache_disable();
879            $super_cache_enabled = false;
880        }
881
882        if ( isset( $_POST[ 'wp_cache_mod_rewrite' ] ) && $_POST[ 'wp_cache_mod_rewrite' ] == 1 ) {
883            $wp_cache_mod_rewrite = 1;
884            add_mod_rewrite_rules();
885        } else {
886            $wp_cache_mod_rewrite = 0; // cache files served by PHP
887            remove_mod_rewrite_rules();
888        }
889        wp_cache_setting( 'wp_cache_mod_rewrite', $wp_cache_mod_rewrite );
890
891        if( isset( $_POST[ 'wp_cache_clear_on_post_edit' ] ) ) {
892            $wp_cache_clear_on_post_edit = 1;
893        } else {
894            $wp_cache_clear_on_post_edit = 0;
895        }
896        wp_cache_replace_line('^ *\$wp_cache_clear_on_post_edit', "\$wp_cache_clear_on_post_edit = " . $wp_cache_clear_on_post_edit . ";", $wp_cache_config_file);
897
898        if( isset( $_POST[ 'cache_rebuild_files' ] ) ) {
899            $cache_rebuild_files = 1;
900        } else {
901            $cache_rebuild_files = 0;
902        }
903        wp_cache_replace_line('^ *\$cache_rebuild_files', "\$cache_rebuild_files = " . $cache_rebuild_files . ";", $wp_cache_config_file);
904
905        if ( isset( $_POST[ 'wpsc_save_headers' ] ) ) {
906            $wpsc_save_headers = 1;
907        } else {
908            $wpsc_save_headers = 0;
909        }
910        wp_cache_replace_line('^ *\$wpsc_save_headers', "\$wpsc_save_headers = " . $wpsc_save_headers . ";", $wp_cache_config_file);
911
912        if( isset( $_POST[ 'wp_cache_mutex_disabled' ] ) ) {
913            $wp_cache_mutex_disabled = 0;
914        } else {
915            $wp_cache_mutex_disabled = 1;
916        }
917        if( defined( 'WPSC_DISABLE_LOCKING' ) ) {
918            $wp_cache_mutex_disabled = 1;
919        }
920        wp_cache_replace_line('^ *\$wp_cache_mutex_disabled', "\$wp_cache_mutex_disabled = " . $wp_cache_mutex_disabled . ";", $wp_cache_config_file);
921
922        if ( isset( $_POST['wp_cache_not_logged_in'] ) && $_POST['wp_cache_not_logged_in'] != 0 ) {
923            if ( $wp_cache_not_logged_in == 0 && function_exists( 'prune_super_cache' ) ) {
924                prune_super_cache( $cache_path, true );
925            }
926            $wp_cache_not_logged_in = (int)$_POST['wp_cache_not_logged_in'];
927        } else {
928            $wp_cache_not_logged_in = 0;
929        }
930        wp_cache_replace_line('^ *\$wp_cache_not_logged_in', "\$wp_cache_not_logged_in = " . $wp_cache_not_logged_in . ";", $wp_cache_config_file);
931
932        if( isset( $_POST[ 'wp_cache_make_known_anon' ] ) ) {
933            if( $wp_cache_make_known_anon == 0 && function_exists( 'prune_super_cache' ) )
934                prune_super_cache ($cache_path, true);
935            $wp_cache_make_known_anon = 1;
936        } else {
937            $wp_cache_make_known_anon = 0;
938        }
939        wp_cache_replace_line('^ *\$wp_cache_make_known_anon', "\$wp_cache_make_known_anon = " . $wp_cache_make_known_anon . ";", $wp_cache_config_file);
940
941        if( isset( $_POST[ 'wp_cache_refresh_single_only' ] ) ) {
942            $wp_cache_refresh_single_only = 1;
943        } else {
944            $wp_cache_refresh_single_only = 0;
945        }
946        wp_cache_setting( 'wp_cache_refresh_single_only', $wp_cache_refresh_single_only );
947
948        if ( defined( 'WPSC_DISABLE_COMPRESSION' ) ) {
949            $cache_compression = 0;
950            wp_cache_replace_line('^ *\$cache_compression', "\$cache_compression = " . $cache_compression . ";", $wp_cache_config_file);
951        } else {
952            if ( isset( $_POST[ 'cache_compression' ] ) ) {
953                $new_cache_compression = 1;
954            } else {
955                $new_cache_compression = 0;
956            }
957            if ( 1 == ini_get( 'zlib.output_compression' ) || "on" == strtolower( ini_get( 'zlib.output_compression' ) ) ) {
958                echo '<div class="notice notice-error">' . __( "<strong>Warning!</strong> You attempted to enable compression but <code>zlib.output_compression</code> is enabled. See #21 in the Troubleshooting section of the readme file.", 'wp-super-cache' ) . '</div>';
959            } elseif ( $new_cache_compression !== (int) $cache_compression ) {
960                $cache_compression = $new_cache_compression;
961                wp_cache_replace_line( '^ *\$cache_compression', "\$cache_compression = $cache_compression;", $wp_cache_config_file );
962                if ( function_exists( 'prune_super_cache' ) ) {
963                    prune_super_cache( $cache_path, true );
964                }
965                delete_option( 'super_cache_meta' );
966            }
967        }
968    }
969}
970if ( isset( $_GET[ 'page' ] ) && $_GET[ 'page' ] == 'wpsupercache' )
971    add_action( 'admin_init', 'wp_cache_manager_updates' );
972
973function wp_cache_manager() {
974    global $wp_cache_config_file, $valid_nonce, $supercachedir, $cache_path, $cache_enabled, $cache_compression, $super_cache_enabled;
975    global $wp_cache_clear_on_post_edit, $cache_rebuild_files, $wp_cache_mutex_disabled, $wp_cache_mobile_enabled, $wp_cache_mobile_browsers, $wp_cache_no_cache_for_get;
976    global $wp_cache_not_logged_in, $wp_cache_make_known_anon, $wp_supercache_cache_list, $cache_page_secret;
977    global $wp_super_cache_front_page_check, $wp_cache_refresh_single_only, $wp_cache_mobile_prefixes;
978    global $wp_cache_mod_rewrite, $wp_supercache_304, $wp_super_cache_late_init, $wp_cache_front_page_checks, $wp_cache_disable_utf8, $wp_cache_mfunc_enabled;
979    global $wp_super_cache_comments, $wp_cache_home_path, $wpsc_save_headers, $is_nginx;
980    global $wpsc_promo_links;
981
982    if ( !wpsupercache_site_admin() )
983        return false;
984
985    // used by mod_rewrite rules and config file
986    if ( function_exists( "cfmobi_default_browsers" ) ) {
987        $wp_cache_mobile_browsers = cfmobi_default_browsers( "mobile" );
988        $wp_cache_mobile_browsers = array_merge( $wp_cache_mobile_browsers, cfmobi_default_browsers( "touch" ) );
989    } elseif ( function_exists( 'lite_detection_ua_contains' ) ) {
990        $wp_cache_mobile_browsers = explode( '|', lite_detection_ua_contains() );
991    } else {
992        $wp_cache_mobile_browsers = array( '2.0 MMP', '240x320', '400X240', 'AvantGo', 'BlackBerry', 'Blazer', 'Cellphone', 'Danger', 'DoCoMo', 'Elaine/3.0', 'EudoraWeb', 'Googlebot-Mobile', 'hiptop', 'IEMobile', 'KYOCERA/WX310K', 'LG/U990', 'MIDP-2.', 'MMEF20', 'MOT-V', 'NetFront', 'Newt', 'Nintendo Wii', 'Nitro', 'Nokia', 'Opera Mini', 'Palm', 'PlayStation Portable', 'portalmmm', 'Proxinet', 'ProxiNet', 'SHARP-TQ-GX10', 'SHG-i900', 'Small', 'SonyEricsson', 'Symbian OS', 'SymbianOS', 'TS21i-10', 'UP.Browser', 'UP.Link', 'webOS', 'Windows CE', 'WinWAP', 'YahooSeeker/M1A1-R2D2', 'iPhone', 'iPod', 'iPad', 'Android', 'BlackBerry9530', 'LG-TU915 Obigo', 'LGE VX', 'webOS', 'Nokia5800' );
993    }
994    if ( function_exists( "lite_detection_ua_prefixes" ) ) {
995        $wp_cache_mobile_prefixes = lite_detection_ua_prefixes();
996    } else {
997        $wp_cache_mobile_prefixes = array( 'w3c ', 'w3c-', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac', 'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'htc_', 'inno', 'ipaq', 'ipod', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-', 'lg/u', 'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-', 'newt', 'noki', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox', 'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar', 'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-', 'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp', 'wapr', 'webc', 'winw', 'winw', 'xda ', 'xda-' ); // from http://svn.wp-plugins.org/wordpress-mobile-pack/trunk/plugins/wpmp_switcher/lite_detection.php
998    }
999    $wp_cache_mobile_browsers = apply_filters( 'cached_mobile_browsers', $wp_cache_mobile_browsers ); // Allow mobile plugins access to modify the mobile UA list
1000    $wp_cache_mobile_prefixes = apply_filters( 'cached_mobile_prefixes', $wp_cache_mobile_prefixes ); // Allow mobile plugins access to modify the mobile UA prefix list
1001    if ( function_exists( 'do_cacheaction' ) ) {
1002        $wp_cache_mobile_browsers = do_cacheaction( 'wp_super_cache_mobile_browsers', $wp_cache_mobile_browsers );
1003        $wp_cache_mobile_prefixes = do_cacheaction( 'wp_super_cache_mobile_prefixes', $wp_cache_mobile_prefixes );
1004    }
1005    $mobile_groups = apply_filters( 'cached_mobile_groups', array() ); // Group mobile user agents by capabilities. Lump them all together by default
1006    // mobile_groups = array( 'apple' => array( 'ipod', 'iphone' ), 'nokia' => array( 'nokia5800', 'symbianos' ) );
1007
1008    $wp_cache_mobile_browsers = implode( ', ', $wp_cache_mobile_browsers );
1009    $wp_cache_mobile_prefixes = implode( ', ', $wp_cache_mobile_prefixes );
1010
1011    if ( false == apply_filters( 'wp_super_cache_error_checking', true ) )
1012        return false;
1013
1014    if ( function_exists( 'get_supercache_dir' ) )
1015        $supercachedir = get_supercache_dir();
1016    if( get_option( 'gzipcompression' ) == 1 )
1017        update_option( 'gzipcompression', 0 );
1018    if( !isset( $cache_rebuild_files ) )
1019        $cache_rebuild_files = 0;
1020
1021    $valid_nonce = isset($_REQUEST['_wpnonce']) ? wp_verify_nonce($_REQUEST['_wpnonce'], 'wp-cache') : false;
1022    /* http://www.netlobo.com/div_hiding.html */
1023    ?>
1024<script type='text/javascript'>
1025<!--
1026function toggleLayer( whichLayer ) {
1027    var elem, vis;
1028    if( document.getElementById ) // this is the way the standards work
1029        elem = document.getElementById( whichLayer );
1030    else if( document.all ) // this is the way old msie versions work
1031        elem = document.all[whichLayer];
1032    else if( document.layers ) // this is the way nn4 works
1033        elem = document.layers[whichLayer];
1034    vis = elem.style;
1035    // if the style.display value is blank we try to figure it out here
1036    if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
1037        vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
1038    vis.display = (vis.display==''||vis.display=='block')?'none':'block';
1039}
1040// -->
1041//Clicking header opens fieldset options
1042jQuery(document).ready(function(){
1043    jQuery("fieldset h4").css("cursor","pointer").on("click",function(){
1044        jQuery(this).parent("fieldset").find("p,form,ul,blockquote").toggle("slow");
1045    });
1046});
1047</script>
1048
1049<style type='text/css'>
1050#nav h3 {
1051    border-bottom: 1px solid #ccc;
1052    padding-bottom: 0;
1053    height: 1.5em;
1054}
1055table.wpsc-settings-table {
1056    clear: both;
1057}
1058</style>
1059<div id="wpsc-dashboard">
1060<?php
1061    wpsc_render_header();
1062
1063    echo '<div class="wpsc-body">';
1064    echo '<a name="top"></a>';
1065
1066    // Set a default.
1067    if ( false === $cache_enabled && ! isset( $wp_cache_mod_rewrite ) ) {
1068        $wp_cache_mod_rewrite = 0;
1069    } elseif ( ! isset( $wp_cache_mod_rewrite ) && $cache_enabled && $super_cache_enabled ) {
1070        $wp_cache_mod_rewrite = 1;
1071    }
1072
1073    $admin_url = admin_url( 'options-general.php?page=wpsupercache' );
1074    $curr_tab  = ! empty( $_GET['tab'] ) ? sanitize_text_field( stripslashes( $_GET['tab'] ) ) : ''; // WPCS: sanitization ok.
1075    if ( empty( $curr_tab ) ) {
1076        $curr_tab = 'easy';
1077        if ( $wp_cache_mod_rewrite ) {
1078            $curr_tab = 'settings';
1079            echo '<div class="notice notice-info is-dismissible"><p>' .  __( 'Notice: <em>Expert mode caching enabled</em>. Showing Advanced Settings Page by default.', 'wp-super-cache' ) . '</p></div>';
1080        }
1081    }
1082
1083    if ( 'preload' === $curr_tab ) {
1084        if ( true == $super_cache_enabled && ! defined( 'DISABLESUPERCACHEPRELOADING' ) ) {
1085            global $wp_cache_preload_interval, $wp_cache_preload_on, $wp_cache_preload_taxonomies, $wp_cache_preload_email_me, $wp_cache_preload_email_volume, $wp_cache_preload_posts, $wpdb;
1086            wpsc_preload_settings();
1087            $currently_preloading = false;
1088
1089            echo '<div id="wpsc-preload-status"></div>';
1090        }
1091    }
1092
1093    wpsc_admin_tabs( $curr_tab );
1094    echo '<div class="wpsc-body-content wrap">';
1095
1096    if ( isset( $wp_super_cache_front_page_check ) && $wp_super_cache_front_page_check == 1 && ! wp_next_scheduled( 'wp_cache_check_site_hook' ) ) {
1097        wp_schedule_single_event( time() + 360, 'wp_cache_check_site_hook' );
1098        wp_cache_debug( 'scheduled wp_cache_check_site_hook for 360 seconds time.', 2 );
1099    }
1100
1101    if ( isset( $_REQUEST['wp_restore_config'] ) && $valid_nonce ) {
1102        unlink( $wp_cache_config_file );
1103        echo '<strong>' . esc_html__( 'Configuration file changed, some values might be wrong. Load the page again from the "Settings" menu to reset them.', 'wp-super-cache' ) . '</strong>';
1104    }
1105
1106    if ( substr( get_option( 'permalink_structure' ), -1 ) == '/' ) {
1107        wp_cache_replace_line( '^ *\$wp_cache_slash_check', "\$wp_cache_slash_check = 1;", $wp_cache_config_file );
1108    } else {
1109        wp_cache_replace_line( '^ *\$wp_cache_slash_check', "\$wp_cache_slash_check = 0;", $wp_cache_config_file );
1110    }
1111    $home_path = parse_url( site_url() );
1112    $home_path = trailingslashit( array_key_exists( 'path', $home_path ) ? $home_path['path'] : '' );
1113    if ( ! isset( $wp_cache_home_path ) ) {
1114        $wp_cache_home_path = '/';
1115        wp_cache_setting( 'wp_cache_home_path', '/' );
1116    }
1117    if ( "$home_path" != "$wp_cache_home_path" ) {
1118        wp_cache_setting( 'wp_cache_home_path', $home_path );
1119    }
1120
1121    if ( $wp_cache_mobile_enabled == 1 ) {
1122        update_cached_mobile_ua_list( $wp_cache_mobile_browsers, $wp_cache_mobile_prefixes, $mobile_groups );
1123    }
1124
1125    ?>
1126    <style>
1127        .wpsc-boost-banner {
1128            margin: 2px 1.25rem 1.25rem 0;
1129            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03), 0 1px 2px rgba(0, 0, 0, 0.03);
1130            border: 1px solid #d5d5d5;
1131            position: relative;
1132        }
1133
1134        .wpsc-boost-banner-inner {
1135            display: flex;
1136            grid-template-columns: minmax(auto, 750px) 500px;
1137            justify-content: space-between;
1138            min-height: 300px;
1139            background: #fff;
1140            overflow: hidden;
1141        }
1142
1143        .wpsc-boost-banner-content {
1144            display: inline-flex;
1145            flex-direction: column;
1146            padding: 2.5rem;
1147            text-align: left;
1148        }
1149
1150        .wpsc-boost-banner-image-container {
1151            position: relative;
1152            background-image: url( <?php echo esc_url( plugin_dir_url( __FILE__ ) . '/assets/jetpack-colors.svg' ); ?> );
1153            background-size: cover;
1154            min-width: 40%;
1155            max-width: 40%;
1156            overflow: hidden;
1157            text-align: right;
1158        }
1159
1160        .wpsc-boost-banner-image-container img {
1161            position: relative;
1162            top: 50%;
1163            transform: translateY(-50%);
1164        }
1165
1166        .wpsc-boost-banner h3 {
1167            font-size: 24px;
1168            line-height: 32px;
1169        }
1170
1171        .wpsc-boost-banner p {
1172            font-size: 14px;
1173            line-height: 24px;
1174            margin: 0 0 1.9rem;
1175        }
1176
1177        .wpsc-boost-banner .wpsc-boost-dismiss {
1178            position: absolute;
1179            top: 10px;
1180            right: 10px;
1181            color: black;
1182            cursor:pointer;
1183        }
1184
1185        .wpsc-boost-banner .button-primary {
1186            background: black;
1187            border-color: black;
1188            color: #fff;
1189            width: fit-content;
1190            padding: 0.4rem 1rem;
1191            font-size: 16px;
1192            line-height: 23px;
1193        }
1194
1195        .wpsc-boost-banner .button-primary:hover {
1196            background-color: #333;
1197        }
1198
1199        .wpsc-boost-banner .button-primary:visited {
1200            background-color: black;
1201            border-color: black;
1202        }
1203    </style>
1204
1205    <table class="wpsc-settings-table"><td valign="top">
1206
1207    <?php
1208    wpsc_jetpack_boost_install_banner();
1209
1210    switch ( $curr_tab ) {
1211        case 'cdn':
1212            scossdl_off_options();
1213            break;
1214        case 'tester':
1215        case 'contents':
1216            echo '<a name="test"></a>';
1217            wp_cache_files();
1218            break;
1219        case 'preload':
1220            wpsc_render_partial(
1221                'preload',
1222                compact(
1223                    'cache_enabled',
1224                    'super_cache_enabled',
1225                    'admin_url',
1226                    'wp_cache_preload_interval',
1227                    'wp_cache_preload_on',
1228                    'wp_cache_preload_taxonomies',
1229                    'wp_cache_preload_email_me',
1230                    'wp_cache_preload_email_volume',
1231                    'currently_preloading',
1232                    'wp_cache_preload_posts'
1233                )
1234            );
1235
1236            break;
1237        case 'plugins':
1238            wpsc_plugins_tab();
1239            break;
1240        case 'debug':
1241            global $wp_super_cache_debug, $wp_cache_debug_log, $wp_cache_debug_ip, $wp_cache_debug_ip;
1242            global $wp_super_cache_front_page_text, $wp_super_cache_front_page_notification;
1243            global $wp_super_cache_advanced_debug, $wp_cache_debug_username, $wp_super_cache_front_page_clear;
1244            wpsc_render_partial(
1245                'debug',
1246                compact( 'wp_super_cache_debug', 'wp_cache_debug_log', 'wp_cache_debug_ip', 'cache_path', 'valid_nonce', 'wp_cache_config_file', 'wp_super_cache_comments', 'wp_super_cache_front_page_check', 'wp_super_cache_front_page_clear', 'wp_super_cache_front_page_text', 'wp_super_cache_front_page_notification', 'wp_super_cache_advanced_debug', 'wp_cache_debug_username', 'wp_cache_home_path' )
1247            );
1248            break;
1249        case 'settings':
1250            global $cache_acceptable_files, $wpsc_rejected_cookies, $cache_rejected_uri, $wp_cache_pages;
1251            global $cache_max_time, $wp_cache_config_file, $valid_nonce, $super_cache_enabled, $cache_schedule_type, $cache_scheduled_time, $cache_schedule_interval, $cache_time_interval, $cache_gc_email_me, $wp_cache_preload_on;
1252
1253            wp_cache_update_rejected_pages();
1254            wp_cache_update_rejected_cookies();
1255            wp_cache_update_rejected_strings();
1256            wp_cache_update_accepted_strings();
1257            wp_cache_time_update();
1258
1259            wpsc_render_partial(
1260                'advanced',
1261                compact(
1262                    'wp_cache_front_page_checks',
1263                    'admin_url',
1264                    'cache_enabled',
1265                    'super_cache_enabled',
1266                    'wp_cache_mod_rewrite',
1267                    'is_nginx',
1268                    'wp_cache_not_logged_in',
1269                    'wp_cache_no_cache_for_get',
1270                    'cache_compression',
1271                    'cache_rebuild_files',
1272                    'wpsc_save_headers',
1273                    'wp_supercache_304',
1274                    'wp_cache_make_known_anon',
1275                    'wp_cache_mfunc_enabled',
1276                    'wp_cache_mobile_enabled',
1277                    'wp_cache_mobile_browsers',
1278                    'wp_cache_disable_utf8',
1279                    'wp_cache_clear_on_post_edit',
1280                    'wp_cache_front_page_checks',
1281                    'wp_cache_refresh_single_only',
1282                    'wp_supercache_cache_list',
1283                    'wp_cache_mutex_disabled',
1284                    'wp_super_cache_late_init',
1285                    'cache_page_secret',
1286                    'cache_path',
1287                    'cache_acceptable_files',
1288                    'wpsc_rejected_cookies',
1289                    'cache_rejected_uri',
1290                    'wp_cache_pages',
1291                    'cache_max_time',
1292                    'valid_nonce',
1293                    'super_cache_enabled',
1294                    'cache_schedule_type',
1295                    'cache_scheduled_time',
1296                    'cache_schedule_interval',
1297                    'cache_time_interval',
1298                    'cache_gc_email_me',
1299                    'wp_cache_mobile_prefixes',
1300                    'wp_cache_preload_on'
1301                )
1302            );
1303
1304            wpsc_edit_tracking_parameters();
1305            wpsc_edit_rejected_ua();
1306            wpsc_lockdown();
1307            wpsc_restore_settings();
1308
1309            break;
1310        case 'easy':
1311        default:
1312            wpsc_render_partial(
1313                'easy',
1314                array(
1315                    'admin_url'     => $admin_url,
1316                    'cache_enabled' => $cache_enabled,
1317                    'is_nginx'      => $is_nginx,
1318                    'wp_cache_mod_rewrite' => $wp_cache_mod_rewrite,
1319                    'valid_nonce' => $valid_nonce,
1320                    'cache_path'              => $cache_path,
1321                    'wp_super_cache_comments' => $wp_super_cache_comments,
1322                )
1323            );
1324            break;
1325    }
1326    ?>
1327
1328    </fieldset>
1329    </td><td valign='top' style='width: 300px'>
1330    <!-- TODO: Hide #wpsc-callout from all pages except the Easy tab -->
1331    <div class="wpsc-card" id="wpsc-callout">
1332    <?php if ( ! empty( $wpsc_promo_links ) && is_array( $wpsc_promo_links ) ) : ?>
1333    <h4><?php esc_html_e( 'Other Site Tools', 'wp-super-cache' ); ?></h4>
1334    <ul style="list-style: square; margin-left: 2em;">
1335        <li><a href="<?php echo esc_url( $wpsc_promo_links['boost'] ); ?>"><?php esc_html_e( 'Boost your page speed scores', 'wp-super-cache' ); ?></a></li>
1336        <li><a href="<?php echo esc_url( $wpsc_promo_links['photon'] ); ?>"><?php esc_html_e( 'Speed up images and photos (free)', 'wp-super-cache' ); ?></a></li>
1337        <li><a href="<?php echo esc_url( $wpsc_promo_links['videopress'] ); ?>"><?php esc_html_e( 'Fast video hosting (paid)', 'wp-super-cache' ); ?></a></li>
1338        <li><a href="<?php echo esc_url( $wpsc_promo_links['crowdsignal'] ); ?>"><?php esc_html_e( 'Add Surveys and Polls to your site', 'wp-super-cache' ); ?></a></li>
1339    </ul>
1340    <?php endif; ?>
1341    <h4><?php _e( 'Need Help?', 'wp-super-cache' ); ?></h4>
1342    <ol>
1343    <li><?php printf( __( 'Use the <a href="%1$s">Debug tab</a> for diagnostics.', 'wp-super-cache' ), admin_url( 'options-general.php?page=wpsupercache&tab=debug' ) ); ?></li>
1344    <li>
1345        <?php
1346            echo wp_kses_post(
1347                sprintf(
1348                    /* translators: %s is the URL for the documentation. */
1349                    __( 'Check out the <a href="%s">plugin documentation</a>.', 'wp-super-cache' ),
1350                    'https://jetpack.com/support/wp-super-cache/'
1351                )
1352            );
1353        ?>
1354    </li>
1355    <li>
1356        <?php
1357            echo wp_kses_post(
1358                sprintf(
1359                    /* translators: %1$s is the URL for the support forum. */
1360                    __( 'Visit the <a href="%1$s">support forum</a>.', 'wp-super-cache' ),
1361                    'https://wordpress.org/support/plugin/wp-super-cache/'
1362                )
1363            );
1364        ?>
1365    </li>
1366    <li><?php printf( __( 'Try out the <a href="%1$s">development version</a> for the latest fixes (<a href="%2$s">changelog</a>).', 'wp-super-cache' ), 'https://odd.blog/y/2o', 'https://plugins.trac.wordpress.org/log/wp-super-cache/' ); ?></li>
1367    </ol>
1368    <h4><?php esc_html_e( 'Rate This Plugin', 'wp-super-cache' ); ?></h4>
1369    <p><?php printf( __( 'Please <a href="%s">rate us</a> and give feedback.', 'wp-super-cache' ), 'https://wordpress.org/support/plugin/wp-super-cache/reviews?rate=5#new-post' ); ?></p>
1370
1371    <?php
1372    if ( isset( $wp_supercache_cache_list ) && $wp_supercache_cache_list ) {
1373        $start_date = get_option( 'wpsupercache_start' );
1374        if ( ! $start_date ) {
1375            $start_date = time();
1376        }
1377        ?>
1378        <p><?php printf( __( 'Cached pages since %1$s : <strong>%2$s</strong>', 'wp-super-cache' ), date( 'M j, Y', $start_date ), number_format( get_option( 'wpsupercache_count' ) ) ); ?></p>
1379        <p><?php _e( 'Newest Cached Pages:', 'wp-super-cache' ); ?><ol>
1380            <?php
1381            foreach ( array_reverse( (array) get_option( 'supercache_last_cached' ) ) as $url ) {
1382                $since = time() - strtotime( $url['date'] );
1383                echo "<li><a title='" . sprintf( esc_html__( 'Cached %s seconds ago', 'wp-super-cache' ), (int) $since ) . "' href='" . site_url( $url['url'] ) . "'>" . substr( $url['url'], 0, 20 ) . "</a></li>\n";
1384            }
1385            ?>
1386            </ol>
1387            <small><?php esc_html_e( '(may not always be accurate on busy sites)', 'wp-super-cache' ); ?></small>
1388        </p><?php
1389    } elseif ( false == get_option( 'wpsupercache_start' ) ) {
1390            update_option( 'wpsupercache_start', time() );
1391            update_option( 'wpsupercache_count', 0 );
1392    }
1393    ?>
1394    </div>
1395    </td></table>
1396    </div>
1397    </div>
1398    <?php wpsc_render_footer(); ?>
1399    </div>
1400    <?php
1401}
1402
1403function wpsc_plugins_tab() {
1404    echo '<div class="wpsc-card">';
1405    echo '<p>' . esc_html__( 'Cache plugins are PHP scripts you\'ll find in a dedicated folder inside the WP Super Cache folder (wp-super-cache/plugins/). They load at the same time as WP Super Cache, and before regular WordPress plugins.', 'wp-super-cache' ) . '</p>';
1406    echo '<p>' . esc_html__( 'Keep in mind that cache plugins are for advanced users only. To create and manage them, you\'ll need extensive knowledge of both PHP and WordPress actions.', 'wp-super-cache' ) . '</p>';
1407    echo '<p>' . sprintf( __( '<strong>Warning</strong>! Due to the way WordPress upgrades plugins, the ones you upload to the WP Super Cache folder (wp-super-cache/plugins/) will be deleted when you upgrade WP Super Cache. To avoid this loss, load your cache plugins from a different location. When you set <strong>$wp_cache_plugins_dir</strong> to the new location in wp-config.php, WP Super Cache will look there instead. <br />You can find additional details in the <a href="%s">developer documentation</a>.', 'wp-super-cache' ), 'https://odd.blog/wp-super-cache-developers/' ) . '</p>';
1408    echo '</div>';
1409    echo '<div class="wpsc-card">';
1410    ob_start();
1411    if ( defined( 'WP_CACHE' ) ) {
1412        if ( function_exists( 'do_cacheaction' ) ) {
1413            do_cacheaction( 'cache_admin_page' );
1414        }
1415    }
1416    $out = ob_get_contents();
1417    ob_end_clean();
1418
1419    if ( SUBMITDISABLED == ' ' && $out != '' ) {
1420        echo '<h4>' . esc_html__( 'Available Plugins', 'wp-super-cache' ) . '</h4>';
1421        echo '<ol>';
1422        echo $out;
1423        echo '</ol>';
1424    }
1425    echo '</div>';
1426}
1427
1428function wpsc_admin_tabs( $current = '' ) {
1429    global $cache_enabled, $super_cache_enabled, $wp_cache_mod_rewrite;
1430
1431    if ( '' === $current ) {
1432        $current = ! empty( $_GET['tab'] ) ? stripslashes( $_GET['tab'] ) : ''; // WPCS: CSRF ok, sanitization ok.
1433    }
1434
1435    $admin_url  = admin_url( 'options-general.php?page=wpsupercache' );
1436    $admin_tabs = array(
1437        'easy'     => __( 'Easy', 'wp-super-cache' ),
1438        'settings' => __( 'Advanced', 'wp-super-cache' ),
1439        'cdn'      => __( 'CDN', 'wp-super-cache' ),
1440        'contents' => __( 'Contents', 'wp-super-cache' ),
1441        'preload'  => __( 'Preload', 'wp-super-cache' ),
1442        'plugins'  => __( 'Plugins', 'wp-super-cache' ),
1443        'debug'    => __( 'Debug', 'wp-super-cache' ),
1444    );
1445
1446    echo '<div class="wpsc-nav-container"><ul class="wpsc-nav">';
1447
1448    foreach ( $admin_tabs as $tab => $name ) {
1449        printf(
1450            '<li class="%s"><a href="%s">%s</a></li>',
1451            esc_attr( $tab === $current ? 'wpsc-nav-tab wpsc-nav-tab-selected' : 'wpsc-nav-tab' ),
1452            esc_url_raw( add_query_arg( 'tab', $tab, $admin_url ) ),
1453            esc_html( $name )
1454        );
1455    }
1456
1457    echo '</ul></div>';
1458}
1459
1460function wpsc_restore_settings() {
1461    $admin_url = admin_url( 'options-general.php?page=wpsupercache' );
1462    wpsc_render_partial(
1463        'restore',
1464        compact( 'admin_url' )
1465    );
1466}
1467
1468function comment_form_lockdown_message() {
1469    ?><p><?php _e( "Comment moderation is enabled. Your comment may take some time to appear.", 'wp-super-cache' ); ?></p><?php
1470}
1471if( defined( 'WPLOCKDOWN' ) && constant( 'WPLOCKDOWN' ) )
1472    add_action( 'comment_form', 'comment_form_lockdown_message' );
1473
1474function wp_update_lock_down() {
1475    global $cache_path, $wp_cache_config_file, $valid_nonce;
1476
1477    if ( isset( $_POST[ 'wp_lock_down' ] ) && $valid_nonce ) {
1478        $wp_lock_down = $_POST[ 'wp_lock_down' ] == '1' ? '1' : '0';
1479        wp_cache_replace_line( '^.*WPLOCKDOWN', "if ( ! defined( 'WPLOCKDOWN' ) ) define( 'WPLOCKDOWN', '$wp_lock_down' );", $wp_cache_config_file );
1480        if ( false == defined( 'WPLOCKDOWN' ) )
1481            define( 'WPLOCKDOWN', $wp_lock_down );
1482        if ( $wp_lock_down == '0' && function_exists( 'prune_super_cache' ) )
1483            prune_super_cache( $cache_path, true ); // clear the cache after lockdown
1484        return $wp_lock_down;
1485    }
1486    if ( defined( 'WPLOCKDOWN' ) )
1487        return constant( 'WPLOCKDOWN' );
1488    else
1489        return 0;
1490}
1491
1492function wpsc_update_direct_pages() {
1493    global $cached_direct_pages, $valid_nonce, $cache_path, $wp_cache_config_file;
1494
1495    if ( false == isset( $cached_direct_pages ) )
1496        $cached_direct_pages = array();
1497    $out = '';
1498    if ( $valid_nonce && array_key_exists('direct_pages', $_POST) && is_array( $_POST[ 'direct_pages' ] ) && !empty( $_POST[ 'direct_pages' ] ) ) {
1499        $expiredfiles = array_diff( $cached_direct_pages, $_POST[ 'direct_pages' ] );
1500        $cached_direct_pages = array();
1501        foreach( $_POST[ 'direct_pages' ] as $page ) {
1502            $page = str_replace( '..', '', preg_replace( '/[ <>\'\"\r\n\t\(\)\$\[\];#]/', '', $page ) );
1503            if ( $page != '' ) {
1504                $cached_direct_pages[] = $page;
1505                $out .= "'$page', ";
1506            }
1507        }
1508    }
1509    if ( $valid_nonce && array_key_exists('new_direct_page', $_POST) && $_POST[ 'new_direct_page' ] && '' != $_POST[ 'new_direct_page' ] ) {
1510        $page = str_replace( get_option( 'siteurl' ), '', $_POST[ 'new_direct_page' ] );
1511        $page = str_replace( '..', '', preg_replace( '/[ <>\'\"\r\n\t\(\)\$\[\];#]/', '', $page ) );
1512        if ( substr( $page, 0, 1 ) != '/' )
1513            $page = '/' . $page;
1514        if ( $page != '/' || false == is_array( $cached_direct_pages ) || in_array( $page, $cached_direct_pages ) == false ) {
1515            $cached_direct_pages[] = $page;
1516            $out .= "'$page', ";
1517
1518            @unlink( trailingslashit( ABSPATH . $page ) . "index.html" );
1519            wpsc_delete_files( get_supercache_dir() . $page );
1520        }
1521    }
1522
1523    if ( $out != '' ) {
1524        $out = substr( $out, 0, -2 );
1525    }
1526    if ( $out == "''" ) {
1527        $out = '';
1528    }
1529    $out = '$cached_direct_pages = array( ' . $out . ' );';
1530    wp_cache_replace_line('^ *\$cached_direct_pages', "$out", $wp_cache_config_file);
1531
1532    if ( !empty( $expiredfiles ) ) {
1533        foreach( $expiredfiles as $file ) {
1534            if( $file != '' ) {
1535                $firstfolder = explode( '/', $file );
1536                $firstfolder = ABSPATH . $firstfolder[1];
1537                $file = ABSPATH . $file;
1538                $file = realpath( str_replace( '..', '', preg_replace('/[ <>\'\"\r\n\t\(\)]/', '', $file ) ) );
1539                if ( $file ) {
1540                    @unlink( trailingslashit( $file ) . "index.html" );
1541                    @unlink( trailingslashit( $file ) . "index.html.gz" );
1542                    RecursiveFolderDelete( trailingslashit( $firstfolder ) );
1543                }
1544            }
1545        }
1546    }
1547
1548    if ( $valid_nonce && array_key_exists('deletepage', $_POST) && $_POST[ 'deletepage' ] ) {
1549        $page = str_replace( '..', '', preg_replace('/[ <>\'\"\r\n\t\(\)]/', '', $_POST['deletepage'] ) ) . '/';
1550        $pagefile = realpath( ABSPATH . $page . 'index.html' );
1551        if ( substr( $pagefile, 0, strlen( ABSPATH ) ) != ABSPATH || false == wp_cache_confirm_delete( ABSPATH . $page ) ) {
1552            die( __( 'Cannot delete directory', 'wp-super-cache' ) );
1553        }
1554        $firstfolder = explode( '/', $page );
1555        $firstfolder = ABSPATH . $firstfolder[1];
1556        $page = ABSPATH . $page;
1557        if( is_file( $pagefile ) && is_writeable_ACLSafe( $pagefile ) && is_writeable_ACLSafe( $firstfolder ) ) {
1558            @unlink( $pagefile );
1559            @unlink( $pagefile . '.gz' );
1560            RecursiveFolderDelete( $firstfolder );
1561        }
1562    }
1563
1564    return $cached_direct_pages;
1565}
1566
1567function wpsc_lockdown() {
1568    global $cached_direct_pages, $cache_enabled, $super_cache_enabled;
1569
1570    $admin_url = admin_url( 'options-general.php?page=wpsupercache' );
1571    $wp_lock_down = wp_update_lock_down();
1572
1573    wpsc_render_partial(
1574        'lockdown',
1575        compact( 'cached_direct_pages', 'cache_enabled', 'super_cache_enabled', 'admin_url', 'wp_lock_down' )
1576    );
1577}
1578
1579function RecursiveFolderDelete ( $folderPath ) { // from http://www.php.net/manual/en/function.rmdir.php
1580    if( trailingslashit( constant( 'ABSPATH' ) ) == trailingslashit( $folderPath ) )
1581        return false;
1582    if ( @is_dir ( $folderPath ) ) {
1583        $dh  = @opendir($folderPath);
1584        while (false !== ($value = @readdir($dh))) {
1585            if ( $value != "." && $value != ".." ) {
1586                $value = $folderPath . "/" . $value;
1587                if ( @is_dir ( $value ) ) {
1588                    RecursiveFolderDelete ( $value );
1589                }
1590            }
1591        }
1592        return @rmdir ( $folderPath );
1593    } else {
1594        return FALSE;
1595    }
1596}
1597
1598function wp_cache_time_update() {
1599    global $cache_max_time, $wp_cache_config_file, $valid_nonce, $cache_schedule_type, $cache_scheduled_time, $cache_schedule_interval, $cache_time_interval, $cache_gc_email_me;
1600    if ( isset( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'expirytime' ) {
1601
1602        if ( false == $valid_nonce )
1603            return false;
1604
1605        if( !isset( $cache_schedule_type ) ) {
1606            $cache_schedule_type = 'interval';
1607            wp_cache_replace_line('^ *\$cache_schedule_type', "\$cache_schedule_type = '$cache_schedule_type';", $wp_cache_config_file);
1608        }
1609
1610        if( !isset( $cache_scheduled_time ) ) {
1611            $cache_scheduled_time = '00:00';
1612            wp_cache_replace_line('^ *\$cache_scheduled_time', "\$cache_scheduled_time = '$cache_scheduled_time';", $wp_cache_config_file);
1613        }
1614
1615        if( !isset( $cache_max_time ) ) {
1616            $cache_max_time = 3600;
1617            wp_cache_replace_line('^ *\$cache_max_time', "\$cache_max_time = $cache_max_time;", $wp_cache_config_file);
1618        }
1619
1620        if ( !isset( $cache_time_interval ) ) {
1621            $cache_time_interval = $cache_max_time;
1622            wp_cache_replace_line('^ *\$cache_time_interval', "\$cache_time_interval = '$cache_time_interval';", $wp_cache_config_file);
1623        }
1624
1625        if ( isset( $_POST['wp_max_time'] ) ) {
1626            $cache_max_time = (int)$_POST['wp_max_time'];
1627            wp_cache_replace_line('^ *\$cache_max_time', "\$cache_max_time = $cache_max_time;", $wp_cache_config_file);
1628            // schedule gc watcher
1629            if ( false == wp_next_scheduled( 'wp_cache_gc_watcher' ) )
1630                wp_schedule_event( time()+600, 'hourly', 'wp_cache_gc_watcher' );
1631        }
1632
1633        if ( isset( $_POST[ 'cache_gc_email_me' ] ) ) {
1634            $cache_gc_email_me = 1;
1635            wp_cache_replace_line('^ *\$cache_gc_email_me', "\$cache_gc_email_me = $cache_gc_email_me;", $wp_cache_config_file);
1636        } else {
1637            $cache_gc_email_me = 0;
1638            wp_cache_replace_line('^ *\$cache_gc_email_me', "\$cache_gc_email_me = $cache_gc_email_me;", $wp_cache_config_file);
1639        }
1640        if ( isset( $_POST[ 'cache_schedule_type' ] ) && $_POST[ 'cache_schedule_type' ] == 'interval' && isset( $_POST['cache_time_interval'] ) ) {
1641            wp_clear_scheduled_hook( 'wp_cache_gc' );
1642            $cache_schedule_type = 'interval';
1643            if ( (int)$_POST[ 'cache_time_interval' ] == 0 )
1644                $_POST[ 'cache_time_interval' ] = 600;
1645            $cache_time_interval = (int)$_POST[ 'cache_time_interval' ];
1646            wp_schedule_single_event( time() + $cache_time_interval, 'wp_cache_gc' );
1647            wp_cache_replace_line('^ *\$cache_schedule_type', "\$cache_schedule_type = '$cache_schedule_type';", $wp_cache_config_file);
1648            wp_cache_replace_line('^ *\$cache_time_interval', "\$cache_time_interval = '$cache_time_interval';", $wp_cache_config_file);
1649        } else { // clock
1650            wp_clear_scheduled_hook( 'wp_cache_gc' );
1651            $cache_schedule_type = 'time';
1652            if ( !isset( $_POST[ 'cache_scheduled_time' ] ) ||
1653                $_POST[ 'cache_scheduled_time' ] == '' ||
1654                5 != strlen( $_POST[ 'cache_scheduled_time' ] ) ||
1655                ":" != substr( $_POST[ 'cache_scheduled_time' ], 2, 1 )
1656            )
1657                $_POST[ 'cache_scheduled_time' ] = '00:00';
1658
1659            $cache_scheduled_time = $_POST[ 'cache_scheduled_time' ];
1660
1661            if ( ! preg_match( '/[0-9][0-9]:[0-9][0-9]/', $cache_scheduled_time ) ) {
1662                $cache_scheduled_time = '00:00';
1663            }
1664            $schedules = wp_get_schedules();
1665            if ( !isset( $cache_schedule_interval ) )
1666                $cache_schedule_interval = 'daily';
1667            if ( isset( $_POST[ 'cache_schedule_interval' ] ) && isset( $schedules[ $_POST[ 'cache_schedule_interval' ] ] ) )
1668                $cache_schedule_interval = $_POST[ 'cache_schedule_interval' ];
1669            wp_cache_replace_line('^ *\$cache_schedule_type', "\$cache_schedule_type = '$cache_schedule_type';", $wp_cache_config_file);
1670            wp_cache_replace_line('^ *\$cache_schedule_interval', "\$cache_schedule_interval = '{$cache_schedule_interval}';", $wp_cache_config_file);
1671            wp_cache_replace_line('^ *\$cache_scheduled_time', "\$cache_scheduled_time = '$cache_scheduled_time';", $wp_cache_config_file);
1672            wp_schedule_event( strtotime( $cache_scheduled_time ), $cache_schedule_interval, 'wp_cache_gc' );
1673        }
1674    }
1675}
1676
1677function wp_cache_sanitize_value($text, & $array) {
1678    $text = esc_html(strip_tags($text));
1679    $array = preg_split( '/[\s,]+/', rtrim( $text ) );
1680    $text = var_export($array, true);
1681    $text = preg_replace('/[\s]+/', ' ', $text);
1682    return $text;
1683}
1684
1685function wp_cache_update_rejected_ua() {
1686    global $cache_rejected_user_agent, $wp_cache_config_file, $valid_nonce;
1687
1688    if ( isset( $_POST[ 'wp_rejected_user_agent' ] ) && $valid_nonce ) {
1689        $_POST[ 'wp_rejected_user_agent' ] = str_replace( ' ', '___', $_POST[ 'wp_rejected_user_agent' ] );
1690        $text = str_replace( '___', ' ', wp_cache_sanitize_value( $_POST[ 'wp_rejected_user_agent' ], $cache_rejected_user_agent ) );
1691        wp_cache_replace_line( '^ *\$cache_rejected_user_agent', "\$cache_rejected_user_agent = $text;", $wp_cache_config_file );
1692        foreach( $cache_rejected_user_agent as $k => $ua ) {
1693            $cache_rejected_user_agent[ $k ] = str_replace( '___', ' ', $ua );
1694        }
1695        reset( $cache_rejected_user_agent );
1696    }
1697}
1698
1699function wpsc_edit_rejected_ua() {
1700    global $cache_rejected_user_agent;
1701
1702    $admin_url = admin_url( 'options-general.php?page=wpsupercache' );
1703    wp_cache_update_rejected_ua();
1704    wpsc_render_partial(
1705        'rejected_user_agents',
1706        compact( 'cache_rejected_user_agent', 'admin_url' )
1707    );
1708}
1709
1710function wp_cache_update_rejected_pages() {
1711    global $wp_cache_config_file, $valid_nonce, $wp_cache_pages;
1712
1713    if ( isset( $_POST[ 'wp_edit_rejected_pages' ] ) && $valid_nonce ) {
1714        $pages = array( 'single', 'pages', 'archives', 'tag', 'frontpage', 'home', 'category', 'feed', 'author', 'search' );
1715        foreach( $pages as $page ) {
1716            if ( isset( $_POST[ 'wp_cache_pages' ][ $page ] ) ) {
1717                $value = 1;
1718            } else {
1719                $value = 0;
1720            }
1721            wp_cache_replace_line('^ *\$wp_cache_pages\[ "' . $page . '" \]', "\$wp_cache_pages[ \"{$page}\" ] = $value;", $wp_cache_config_file);
1722            $wp_cache_pages[ $page ] = $value;
1723        }
1724    }
1725}
1726
1727function wpsc_update_tracking_parameters() {
1728    global $wpsc_tracking_parameters, $valid_nonce, $wp_cache_config_file;
1729
1730    if ( isset( $_POST['tracking_parameters'] ) && $valid_nonce ) {
1731        $text = wp_cache_sanitize_value( str_replace( '\\\\', '\\', $_POST['tracking_parameters'] ), $wpsc_tracking_parameters );
1732        wp_cache_replace_line( '^ *\$wpsc_tracking_parameters', "\$wpsc_tracking_parameters = $text;", $wp_cache_config_file );
1733        wp_cache_setting( 'wpsc_ignore_tracking_parameters', isset( $_POST['wpsc_ignore_tracking_parameters'] ) ? 1 : 0 );
1734    }
1735}
1736
1737function wpsc_edit_tracking_parameters() {
1738    global $wpsc_tracking_parameters, $wpsc_ignore_tracking_parameters;
1739
1740    $admin_url = admin_url( 'options-general.php?page=wpsupercache' );
1741    wpsc_update_tracking_parameters();
1742
1743    if ( ! isset( $wpsc_tracking_parameters ) ) {
1744        $wpsc_tracking_parameters = array( 'fbclid', 'ref', 'gclid', 'fb_source', 'mc_cid', 'mc_eid', 'utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'utm_expid', 'mtm_source', 'mtm_medium', 'mtm_campaign', 'mtm_keyword', 'mtm_content', 'mtm_cid', 'mtm_group', 'mtm_placement', 'ysclid', 'srsltid', 'yclid' );
1745    }
1746
1747    if ( ! isset( $wpsc_ignore_tracking_parameters ) ) {
1748        $wpsc_ignore_tracking_parameters = 0;
1749    }
1750    wpsc_render_partial(
1751        'tracking_parameters',
1752        compact( 'wpsc_ignore_tracking_parameters', 'wpsc_tracking_parameters', 'admin_url' )
1753    );
1754}
1755
1756function wp_cache_update_rejected_cookies() {
1757    global $wpsc_rejected_cookies, $wp_cache_config_file, $valid_nonce;
1758
1759    if ( isset( $_POST['wp_rejected_cookies'] ) && $valid_nonce ) {
1760        $text = wp_cache_sanitize_value( str_replace( '\\\\', '\\', $_POST['wp_rejected_cookies'] ), $wpsc_rejected_cookies );
1761        wp_cache_replace_line( '^ *\$wpsc_rejected_cookies', "\$wpsc_rejected_cookies = $text;", $wp_cache_config_file );
1762    }
1763}
1764
1765function wp_cache_update_rejected_strings() {
1766    global $cache_rejected_uri, $wp_cache_config_file, $valid_nonce;
1767
1768    if ( isset($_REQUEST['wp_rejected_uri']) && $valid_nonce ) {
1769        $text = wp_cache_sanitize_value( str_replace( '\\\\', '\\', $_REQUEST['wp_rejected_uri'] ), $cache_rejected_uri );
1770        wp_cache_replace_line('^ *\$cache_rejected_uri', "\$cache_rejected_uri = $text;", $wp_cache_config_file);
1771    }
1772}
1773
1774function wp_cache_update_accepted_strings() {
1775    global $cache_acceptable_files, $wp_cache_config_file, $valid_nonce;
1776
1777    if ( isset( $_REQUEST[ 'wp_accepted_files' ] ) && $valid_nonce ) {
1778        $text = wp_cache_sanitize_value( $_REQUEST[ 'wp_accepted_files' ], $cache_acceptable_files );
1779        wp_cache_replace_line( '^ *\$cache_acceptable_files', "\$cache_acceptable_files = $text;", $wp_cache_config_file );
1780    }
1781}
1782
1783function wpsc_update_debug_settings() {
1784    global $wp_super_cache_debug, $wp_cache_debug_log, $wp_cache_debug_ip, $cache_path, $valid_nonce, $wp_cache_config_file, $wp_super_cache_comments;
1785    global $wp_super_cache_front_page_check, $wp_super_cache_front_page_clear, $wp_super_cache_front_page_text, $wp_super_cache_front_page_notification, $wp_super_cache_advanced_debug;
1786    global $wp_cache_debug_username;
1787
1788    if ( ! isset( $wp_super_cache_comments ) ) {
1789        $wp_super_cache_comments = 1; // defaults to "enabled".
1790        wp_cache_setting( 'wp_super_cache_comments', $wp_super_cache_comments );
1791    }
1792
1793    if ( false == $valid_nonce ) {
1794        return array (
1795            'wp_super_cache_debug' => $wp_super_cache_debug,
1796            'wp_cache_debug_log' => $wp_cache_debug_log,
1797            'wp_cache_debug_ip' => $wp_cache_debug_ip,
1798            'wp_super_cache_comments' => $wp_super_cache_comments,
1799            'wp_super_cache_front_page_check' => $wp_super_cache_front_page_check,
1800            'wp_super_cache_front_page_clear' => $wp_super_cache_front_page_clear,
1801            'wp_super_cache_front_page_text' => $wp_super_cache_front_page_text,
1802            'wp_super_cache_front_page_notification' => $wp_super_cache_front_page_notification,
1803            'wp_super_cache_advanced_debug' => $wp_super_cache_advanced_debug,
1804            'wp_cache_debug_username' => $wp_cache_debug_username,
1805        );
1806    }
1807
1808    if ( isset( $_POST[ 'wpsc_delete_log' ] ) && $_POST[ 'wpsc_delete_log' ] == 1 && $wp_cache_debug_log != '' ) {
1809        @unlink( $cache_path . $wp_cache_debug_log );
1810        extract( wpsc_create_debug_log( $wp_cache_debug_log, $wp_cache_debug_username ) ); // $wp_cache_debug_log, $wp_cache_debug_username
1811    }
1812
1813    if ( ! isset( $wp_cache_debug_log ) || $wp_cache_debug_log == '' ) {
1814        extract( wpsc_create_debug_log() ); // $wp_cache_debug_log, $wp_cache_debug_username
1815    } elseif ( ! file_exists( $cache_path . $wp_cache_debug_log ) ) { // make sure debug log exists before toggling debugging
1816        extract( wpsc_create_debug_log( $wp_cache_debug_log, $wp_cache_debug_username ) ); // $wp_cache_debug_log, $wp_cache_debug_username
1817    }
1818    $wp_super_cache_debug = ( isset( $_POST[ 'wp_super_cache_debug' ] ) && $_POST[ 'wp_super_cache_debug' ] == 1 ) ? 1 : 0;
1819    wp_cache_setting( 'wp_super_cache_debug', $wp_super_cache_debug );
1820
1821    if ( isset( $_POST[ 'wp_cache_debug' ] ) ) {
1822        wp_cache_setting( 'wp_cache_debug_username', $wp_cache_debug_username );
1823        wp_cache_setting( 'wp_cache_debug_log', $wp_cache_debug_log );
1824        $wp_super_cache_comments = isset( $_POST[ 'wp_super_cache_comments' ] ) ? 1 : 0;
1825        wp_cache_setting( 'wp_super_cache_comments', $wp_super_cache_comments );
1826        if ( isset( $_POST[ 'wp_cache_debug_ip' ] ) && filter_var( $_POST[ 'wp_cache_debug_ip' ], FILTER_VALIDATE_IP ) ) {
1827            $wp_cache_debug_ip = esc_html( preg_replace( '/[ <>\'\"\r\n\t\(\)\$\[\];#]/', '', $_POST[ 'wp_cache_debug_ip' ] ) );
1828        } else {
1829            $wp_cache_debug_ip = '';
1830        }
1831        wp_cache_setting( 'wp_cache_debug_ip', $wp_cache_debug_ip );
1832        $wp_super_cache_front_page_check = isset( $_POST[ 'wp_super_cache_front_page_check' ] ) ? 1 : 0;
1833        wp_cache_setting( 'wp_super_cache_front_page_check', $wp_super_cache_front_page_check );
1834        $wp_super_cache_front_page_clear = isset( $_POST[ 'wp_super_cache_front_page_clear' ] ) ? 1 : 0;
1835        wp_cache_setting( 'wp_super_cache_front_page_clear', $wp_super_cache_front_page_clear );
1836        if ( isset( $_POST[ 'wp_super_cache_front_page_text' ] ) ) {
1837            $wp_super_cache_front_page_text = esc_html( preg_replace( '/[ <>\'\"\r\n\t\(\)\$\[\];#]/', '', $_POST[ 'wp_super_cache_front_page_text' ] ) );
1838        } else {
1839            $wp_super_cache_front_page_text = '';
1840        }
1841        wp_cache_setting( 'wp_super_cache_front_page_text', $wp_super_cache_front_page_text );
1842        $wp_super_cache_front_page_notification = isset( $_POST[ 'wp_super_cache_front_page_notification' ] ) ? 1 : 0;
1843        wp_cache_setting( 'wp_super_cache_front_page_notification', $wp_super_cache_front_page_notification );
1844        if ( $wp_super_cache_front_page_check == 1 && !wp_next_scheduled( 'wp_cache_check_site_hook' ) ) {
1845            wp_schedule_single_event( time() + 360 , 'wp_cache_check_site_hook' );
1846            wp_cache_debug( 'scheduled wp_cache_check_site_hook for 360 seconds time.' );
1847        }
1848    }
1849
1850    return array (
1851        'wp_super_cache_debug' => $wp_super_cache_debug,
1852        'wp_cache_debug_log' => $wp_cache_debug_log,
1853        'wp_cache_debug_ip' => $wp_cache_debug_ip,
1854        'wp_super_cache_comments' => $wp_super_cache_comments,
1855        'wp_super_cache_front_page_check' => $wp_super_cache_front_page_check,
1856        'wp_super_cache_front_page_clear' => $wp_super_cache_front_page_clear,
1857        'wp_super_cache_front_page_text' => $wp_super_cache_front_page_text,
1858        'wp_super_cache_front_page_notification' => $wp_super_cache_front_page_notification,
1859        'wp_super_cache_advanced_debug' => $wp_super_cache_advanced_debug,
1860        'wp_cache_debug_username' => $wp_cache_debug_username,
1861    );
1862}
1863
1864function wp_cache_enable() {
1865    global $wp_cache_config_file, $cache_enabled;
1866
1867    if ( $cache_enabled ) {
1868        wp_cache_debug( 'wp_cache_enable: already enabled' );
1869        return true;
1870    }
1871
1872    wp_cache_setting( 'cache_enabled', true );
1873    wp_cache_debug( 'wp_cache_enable: enable cache' );
1874
1875    $cache_enabled = true;
1876
1877    if ( wpsc_set_default_gc() ) {
1878        // gc might not be scheduled, check and schedule
1879        $timestamp = wp_next_scheduled( 'wp_cache_gc' );
1880        if ( false == $timestamp ) {
1881            wp_schedule_single_event( time() + 600, 'wp_cache_gc' );
1882        }
1883    }
1884}
1885
1886function wp_cache_disable() {
1887    global $wp_cache_config_file, $cache_enabled;
1888
1889    if ( ! $cache_enabled ) {
1890        wp_cache_debug( 'wp_cache_disable: already disabled' );
1891        return true;
1892    }
1893
1894    wp_cache_setting( 'cache_enabled', false );
1895    wp_cache_debug( 'wp_cache_disable: disable cache' );
1896
1897    $cache_enabled = false;
1898
1899    wp_clear_scheduled_hook( 'wp_cache_check_site_hook' );
1900    wp_clear_scheduled_hook( 'wp_cache_gc' );
1901    wp_clear_scheduled_hook( 'wp_cache_gc_watcher' );
1902}
1903
1904function wp_super_cache_enable() {
1905    global $supercachedir, $wp_cache_config_file, $super_cache_enabled;
1906
1907    if ( $super_cache_enabled ) {
1908        wp_cache_debug( 'wp_super_cache_enable: already enabled' );
1909        return true;
1910    }
1911
1912    wp_cache_setting( 'super_cache_enabled', true );
1913    wp_cache_debug( 'wp_super_cache_enable: enable cache' );
1914
1915    $super_cache_enabled = true;
1916
1917    if ( ! $supercachedir ) {
1918        $supercachedir = get_supercache_dir();
1919    }
1920
1921    if ( is_dir( $supercachedir . '.disabled' ) ) {
1922        if ( is_dir( $supercachedir ) ) {
1923            prune_super_cache( $supercachedir . '.disabled', true );
1924            @unlink( $supercachedir . '.disabled' );
1925        } else {
1926            @rename( $supercachedir . '.disabled', $supercachedir );
1927        }
1928    }
1929}
1930
1931function wp_super_cache_disable() {
1932    global $cache_path, $supercachedir, $wp_cache_config_file, $super_cache_enabled;
1933
1934    if ( ! $super_cache_enabled ) {
1935        wp_cache_debug( 'wp_super_cache_disable: already disabled' );
1936        return true;
1937    }
1938
1939    wp_cache_setting( 'super_cache_enabled', false );
1940    wp_cache_debug( 'wp_super_cache_disable: disable cache' );
1941
1942    $super_cache_enabled = false;
1943
1944    if ( ! $supercachedir ) {
1945        $supercachedir = get_supercache_dir();
1946    }
1947
1948    if ( is_dir( $supercachedir ) ) {
1949        @rename( $supercachedir, $supercachedir . '.disabled' );
1950    }
1951    sleep( 1 ); // allow existing processes to write to the supercachedir and then delete it
1952    if ( function_exists( 'prune_super_cache' ) && is_dir( $supercachedir ) ) {
1953        prune_super_cache( $cache_path, true );
1954    }
1955
1956    if ( $GLOBALS['wp_cache_mod_rewrite'] === 1 ) {
1957        remove_mod_rewrite_rules();
1958    }
1959}
1960
1961function wp_cache_is_enabled() {
1962    global $wp_cache_config_file;
1963
1964    if ( get_option( 'gzipcompression' ) ) {
1965        echo '<strong>' . __( 'Warning', 'wp-super-cache' ) . '</strong>: ' . __( 'GZIP compression is enabled in WordPress, wp-cache will be bypassed until you disable gzip compression.', 'wp-super-cache' );
1966        return false;
1967    }
1968
1969    $lines = file( $wp_cache_config_file );
1970    foreach ( $lines as $line ) {
1971        if ( preg_match( '/^\s*\$cache_enabled\s*=\s*true\s*;/', $line ) ) {
1972            return true;
1973        }
1974    }
1975
1976    return false;
1977}
1978
1979function wp_cache_remove_index() {
1980    global $cache_path;
1981
1982    if ( empty( $cache_path ) ) {
1983        return;
1984    }
1985
1986    @unlink( $cache_path . "index.html" );
1987    @unlink( $cache_path . "supercache/index.html" );
1988    @unlink( $cache_path . "blogs/index.html" );
1989    if ( is_dir( $cache_path . "blogs" ) ) {
1990        $dir = new DirectoryIterator( $cache_path . "blogs" );
1991        foreach( $dir as $fileinfo ) {
1992            if ( $fileinfo->isDot() ) {
1993                continue;
1994            }
1995            if ( $fileinfo->isDir() ) {
1996                $directory = $cache_path . "blogs/" . $fileinfo->getFilename();
1997                if ( is_file( $directory . "/index.html" ) ) {
1998                    unlink( $directory . "/index.html" );
1999                }
2000                if ( is_dir( $directory . "/meta" ) ) {
2001                    if ( is_file( $directory . "/meta/index.html" ) ) {
2002                        unlink( $directory . "/meta/index.html" );
2003                    }
2004                }
2005            }
2006        }
2007    }
2008}
2009
2010function wp_cache_index_notice() {
2011    global $cache_path;
2012
2013    if ( false == wpsupercache_site_admin() )
2014        return false;
2015    if ( false == get_site_option( 'wp_super_cache_index_detected' ) )
2016        return false;
2017
2018    if ( strlen( $cache_path ) < strlen( ABSPATH )
2019        || ABSPATH != substr( $cache_path, 0, strlen( ABSPATH ) ) )
2020        return false; // cache stored outside web root
2021
2022    if ( get_site_option( 'wp_super_cache_index_detected' ) == 2 ) {
2023        update_site_option( 'wp_super_cache_index_detected', 3 );
2024        echo "<div class='error' style='padding: 10px 10px 50px 10px'>";
2025        echo "<h2>" . __( 'WP Super Cache Warning!', 'wp-super-cache' ) . '</h2>';
2026        echo '<p>' . __( 'All users of this site have been logged out to refresh their login cookies.', 'wp-super-cache' ) . '</p>';
2027        echo '</div>';
2028        return false;
2029    } elseif ( get_site_option( 'wp_super_cache_index_detected' ) != 3 ) {
2030        echo "<div id='wpsc-index-warning' class='error notice' style='padding: 10px 10px 50px 10px'>";
2031        echo "<h2>" . __( 'WP Super Cache Warning!', 'wp-super-cache' ) . '</h2>';
2032        echo '<p>' . __( 'Your server is configured to show files and directories, which may expose sensitive data such as login cookies to attackers in the cache directories. That has been fixed by adding a file named index.html to each directory. If you use simple caching, consider moving the location of the cache directory on the Advanced Settings page.', 'wp-super-cache' ) . '</p>';
2033        echo "<p><strong>";
2034        _e( 'If you just installed WP Super Cache for the first time, you can dismiss this message. Otherwise, you should probably refresh the login cookies of all logged in WordPress users here by clicking the logout link below.', 'wp-super-cache' );
2035        echo "</strong></p>";
2036        echo '<p>' . esc_html__( 'The logout link will log out all WordPress users on this site except you. Your authentication cookie will be updated, but you will not be logged out.', 'wp-super-cache' ) . '</p>';
2037        echo '<a id="wpsc-dismiss" href="#">' . esc_html__( 'Dismiss', 'wp-super-cache' ) . '</a>';
2038        echo '    | <a href="' . esc_url( wp_nonce_url( admin_url( '?action=wpsclogout' ), 'wpsc_logout' ) ) . '">' . esc_html__( 'Logout', 'wp-super-cache' ) . '</a>';
2039        echo '</div>';
2040?>
2041        <script  type='text/javascript'>
2042        <!--
2043            jQuery(document).ready(function(){
2044                jQuery('#wpsc-dismiss').on("click",function() {
2045                        jQuery.ajax({
2046                            type: "post",url: "admin-ajax.php",data: { action: 'wpsc-index-dismiss', _ajax_nonce: '<?php echo wp_create_nonce( 'wpsc-index-dismiss' ); ?>' },
2047                            beforeSend: function() {jQuery("#wpsc-index-warning").fadeOut('slow');},
2048                        });
2049                })
2050            })
2051        //-->
2052        </script>
2053<?php
2054    }
2055}
2056add_action( 'admin_notices', 'wp_cache_index_notice' );
2057
2058function wpsc_config_file_notices() {
2059    global $wp_cache_config_file;
2060    if ( ! isset( $_GET['page'] ) || $_GET['page'] != 'wpsupercache' ) {
2061        return false;
2062    }
2063    $notice = get_transient( 'wpsc_config_error' );
2064    if ( ! $notice ) {
2065        return false;
2066    }
2067    switch( $notice ) {
2068        case 'error_move_tmp_config_file':
2069            $msg = sprintf( __( 'Error: Could not rename temporary file to configuration file. Please make sure %s is writeable by the webserver.' ), $wp_cache_config_file );
2070            break;
2071        case 'config_file_ro':
2072            $msg = sprintf( __( 'Error: Configuration file is read only. Please make sure %s is writeable by the webserver.' ), $wp_cache_config_file );
2073            break;
2074        case 'tmp_file_ro':
2075            $msg = sprintf( __( 'Error: The directory containing the configuration file %s is read only. Please make sure it is writeable by the webserver.' ), $wp_cache_config_file );
2076            break;
2077        case 'config_file_not_loaded':
2078            $msg = sprintf( __( 'Error: Configuration file %s could not be loaded. Please reload the page.' ), $wp_cache_config_file );
2079            break;
2080        case 'config_file_missing':
2081            $msg = sprintf( __( 'Error: Configuration file %s is missing. Please reload the page.' ), $wp_cache_config_file );
2082            break;
2083
2084    }
2085    echo '<div class="error"><p><strong>' . $msg . '</strong></p></div>';
2086}
2087add_action( 'admin_notices', 'wpsc_config_file_notices' );
2088function wpsc_dismiss_indexhtml_warning() {
2089        check_ajax_referer( "wpsc-index-dismiss" );
2090        update_site_option( 'wp_super_cache_index_detected', 3 );
2091        die( 0 );
2092}
2093add_action( 'wp_ajax_wpsc-index-dismiss', 'wpsc_dismiss_indexhtml_warning' );
2094
2095function wp_cache_logout_all() {
2096    global $current_user;
2097    if ( isset( $_GET[ 'action' ] ) && $_GET[ 'action' ] == 'wpsclogout' && wp_verify_nonce( $_GET[ '_wpnonce' ], 'wpsc_logout' ) ) {
2098        $user_id = $current_user->ID;
2099        WP_Session_Tokens::destroy_all_for_all_users();
2100        wp_set_auth_cookie( $user_id, false, is_ssl() );
2101        update_site_option( 'wp_super_cache_index_detected', 2 );
2102        wp_redirect( admin_url() );
2103    }
2104}
2105if ( isset( $_GET[ 'action' ] ) && $_GET[ 'action' ] == 'wpsclogout' )
2106    add_action( 'admin_init', 'wp_cache_logout_all' );
2107
2108function wp_cache_add_index_protection() {
2109    global $cache_path, $blog_cache_dir;
2110
2111    if ( is_dir( $cache_path ) && false == is_file( "$cache_path/index.html" ) ) {
2112        $page = wp_remote_get( home_url( "/wp-content/cache/" ) );
2113        if ( false == is_wp_error( $page ) ) {
2114            if ( false == get_site_option( 'wp_super_cache_index_detected' )
2115                && $page[ 'response' ][ 'code' ] == 200
2116                && stripos( $page[ 'body' ], 'index of' ) ) {
2117                add_site_option( 'wp_super_cache_index_detected', 1 ); // only show this once
2118            }
2119        }
2120        if ( ! function_exists( 'insert_with_markers' ) ) {
2121                        include_once( ABSPATH . 'wp-admin/includes/misc.php' );
2122        }
2123        insert_with_markers( $cache_path . '.htaccess', "INDEX", array( 'Options -Indexes' ) );
2124    }
2125
2126    $directories = array( $cache_path, $cache_path . '/supercache/', $cache_path . '/blogs/', $blog_cache_dir, $blog_cache_dir . "/meta" );
2127    foreach( $directories as $dir ) {
2128        if ( false == is_dir( $dir ) )
2129            @mkdir( $dir );
2130        if ( is_dir( $dir ) && false == is_file( "$dir/index.html" ) ) {
2131            $fp = @fopen( "$dir/index.html", 'w' );
2132            if ( $fp )
2133                fclose( $fp );
2134        }
2135    }
2136}
2137
2138function wp_cache_add_site_cache_index() {
2139    global $cache_path;
2140
2141    wp_cache_add_index_protection(); // root and supercache
2142
2143    if ( is_dir( $cache_path . "blogs" ) ) {
2144        $dir = new DirectoryIterator( $cache_path . "blogs" );
2145        foreach( $dir as $fileinfo ) {
2146            if ( $fileinfo->isDot() ) {
2147                continue;
2148            }
2149            if ( $fileinfo->isDir() ) {
2150                $directory = $cache_path . "blogs/" . $fileinfo->getFilename();
2151                if ( false == is_file( $directory . "/index.html" ) ) {
2152                    $fp = @fopen( $directory . "/index.html", 'w' );
2153                    if ( $fp )
2154                        fclose( $fp );
2155                }
2156                if ( is_dir( $directory . "/meta" ) ) {
2157                    if ( false == is_file( $directory . "/meta/index.html" ) ) {
2158                        $fp = @fopen( $directory . "/meta/index.html", 'w' );
2159                        if ( $fp )
2160                            fclose( $fp );
2161                    }
2162                }
2163            }
2164        }
2165    }
2166}
2167
2168function wp_cache_verify_cache_dir() {
2169    global $cache_path, $blog_cache_dir;
2170
2171    $dir = dirname($cache_path);
2172    if ( !file_exists($cache_path) ) {
2173        if ( !is_writeable_ACLSafe( $dir ) || !($dir = mkdir( $cache_path ) ) ) {
2174                echo "<strong>" . __( 'Error', 'wp-super-cache' ) . ":</strong> " . sprintf( __( 'Your cache directory (<strong>%1$s</strong>) did not exist and couldn&#8217;t be created by the web server. Check %1$s permissions.', 'wp-super-cache' ), $dir );
2175                return false;
2176        }
2177    }
2178    if ( !is_writeable_ACLSafe($cache_path)) {
2179        echo "<strong>" . __( 'Error', 'wp-super-cache' ) . ":</strong> " . sprintf( __( 'Your cache directory (<strong>%1$s</strong>) or <strong>%2$s</strong> need to be writable for this plugin to work. Double-check it.', 'wp-super-cache' ), $cache_path, $dir );
2180        return false;
2181    }
2182
2183    if ( '/' != substr($cache_path, -1)) {
2184        $cache_path .= '/';
2185    }
2186
2187    if( false == is_dir( $blog_cache_dir ) ) {
2188        @mkdir( $cache_path . "blogs" );
2189        if( $blog_cache_dir != $cache_path . "blogs/" )
2190            @mkdir( $blog_cache_dir );
2191    }
2192
2193    if( false == is_dir( $blog_cache_dir . 'meta' ) )
2194        @mkdir( $blog_cache_dir . 'meta' );
2195
2196    wp_cache_add_index_protection();
2197    return true;
2198}
2199
2200function wp_cache_verify_config_file() {
2201    global $wp_cache_config_file, $wp_cache_config_file_sample, $sem_id, $cache_path;
2202    global $WPSC_HTTP_HOST;
2203
2204    $new = false;
2205    $dir = dirname($wp_cache_config_file);
2206
2207    if ( file_exists($wp_cache_config_file) ) {
2208        $lines = implode( ' ', file( $wp_cache_config_file ) );
2209        if ( ! str_contains( $lines, 'WPCACHEHOME' ) ) {
2210            if( is_writeable_ACLSafe( $wp_cache_config_file ) ) {
2211                @unlink( $wp_cache_config_file );
2212            } else {
2213                echo "<strong>" . __( 'Error', 'wp-super-cache' ) . ":</strong> " . sprintf( __( 'Your WP-Cache config file (<strong>%s</strong>) is out of date and not writable by the Web server. Please delete it and refresh this page.', 'wp-super-cache' ), $wp_cache_config_file );
2214                return false;
2215            }
2216        }
2217    } elseif( !is_writeable_ACLSafe($dir)) {
2218        echo "<strong>" . __( 'Error', 'wp-super-cache' ) . ":</strong> " . sprintf( __( 'Configuration file missing and %1$s  directory (<strong>%2$s</strong>) is not writable by the web server. Check its permissions.', 'wp-super-cache' ), WP_CONTENT_DIR, $dir );
2219        return false;
2220    }
2221
2222    if ( !file_exists($wp_cache_config_file) ) {
2223        if ( !file_exists($wp_cache_config_file_sample) ) {
2224            echo "<strong>" . __( 'Error', 'wp-super-cache' ) . ":</strong> " . sprintf( __( 'Sample WP-Cache config file (<strong>%s</strong>) does not exist. Verify your installation.', 'wp-super-cache' ), $wp_cache_config_file_sample );
2225            return false;
2226        }
2227        copy($wp_cache_config_file_sample, $wp_cache_config_file);
2228        $dir = str_replace( str_replace( '\\', '/', WP_CONTENT_DIR ), '', str_replace( '\\', '/', __DIR__ ) );
2229        if ( is_file( __DIR__ . '/wp-cache-config-sample.php' ) ) {
2230            wp_cache_replace_line('define\(\ \'WPCACHEHOME', "\tdefine( 'WPCACHEHOME', WP_CONTENT_DIR . \"{$dir}/\" );", $wp_cache_config_file);
2231        } elseif ( is_file( __DIR__ . '/wp-super-cache/wp-cache-config-sample.php' ) ) {
2232            wp_cache_replace_line('define\(\ \'WPCACHEHOME', "\tdefine( 'WPCACHEHOME', WP_CONTENT_DIR . \"{$dir}/wp-super-cache/\" );", $wp_cache_config_file);
2233        }
2234        $new = true;
2235    }
2236    if ( $sem_id == 5419 && $cache_path != '' && $WPSC_HTTP_HOST != '' ) {
2237        $sem_id = crc32( $WPSC_HTTP_HOST . $cache_path ) & 0x7fffffff;
2238        wp_cache_replace_line('sem_id', '$sem_id = ' . $sem_id . ';', $wp_cache_config_file);
2239    }
2240    if ( $new ) {
2241        require($wp_cache_config_file);
2242        wpsc_set_default_gc( true );
2243    }
2244    return true;
2245}
2246
2247function wp_cache_create_advanced_cache() {
2248    global $wpsc_advanced_cache_filename, $wpsc_advanced_cache_dist_filename;
2249    if ( file_exists( ABSPATH . 'wp-config.php') ) {
2250        $global_config_file = ABSPATH . 'wp-config.php';
2251    } elseif ( file_exists( dirname( ABSPATH ) . '/wp-config.php' ) ) {
2252        $global_config_file = dirname( ABSPATH ) . '/wp-config.php';
2253    } elseif ( defined( 'DEBIAN_FILE' ) && file_exists( DEBIAN_FILE ) ) {
2254        $global_config_file = DEBIAN_FILE;
2255    } else {
2256        die('Cannot locate wp-config.php');
2257    }
2258
2259    $line = 'define( \'WPCACHEHOME\', \'' . __DIR__ . '/\' );';
2260
2261    if ( ! apply_filters( 'wpsc_enable_wp_config_edit', true ) ) {
2262        echo '<div class="notice notice-error"><h4>' . __( 'Warning', 'wp-super-cache' ) . "! " . sprintf( __( 'Not allowed to edit %s per configuration.', 'wp-super-cache' ), $global_config_file ) . "</h4></div>";
2263        return false;
2264    }
2265
2266    if (
2267        ! strpos( file_get_contents( $global_config_file ), "WPCACHEHOME" ) ||
2268        (
2269            defined( 'WPCACHEHOME' ) &&
2270            (
2271                constant( 'WPCACHEHOME' ) == '' ||
2272                (
2273                    constant( 'WPCACHEHOME' ) != '' &&
2274                    ! file_exists( constant( 'WPCACHEHOME' ) . '/wp-cache.php' )
2275                )
2276            )
2277        )
2278    ) {
2279        if (
2280            ! is_writeable_ACLSafe( $global_config_file ) ||
2281            ! wp_cache_replace_line( 'define *\( *\'WPCACHEHOME\'', $line, $global_config_file )
2282        ) {
2283            echo '<div class="notice notice-error"><h4>' . __( 'Warning', 'wp-super-cache' ) . "! <em>" . sprintf( __( 'Could not update %s!</em> WPCACHEHOME must be set in config file.', 'wp-super-cache' ), $global_config_file ) . "</h4></div>";
2284            return false;
2285        }
2286    }
2287    $ret = true;
2288
2289    if ( file_exists( $wpsc_advanced_cache_filename ) ) {
2290        $file = file_get_contents( $wpsc_advanced_cache_filename );
2291        if (
2292            ! strpos( $file, "WP SUPER CACHE 0.8.9.1" ) &&
2293            ! strpos( $file, "WP SUPER CACHE 1.2" )
2294        ) {
2295            return false;
2296        }
2297    }
2298
2299    $file = file_get_contents( $wpsc_advanced_cache_dist_filename );
2300    $fp = @fopen( $wpsc_advanced_cache_filename, 'w' );
2301    if( $fp ) {
2302        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite
2303        fwrite( $fp, $file );
2304        fclose( $fp );
2305        do_action( 'wpsc_created_advanced_cache' );
2306    } else {
2307        $ret = false;
2308    }
2309    return $ret;
2310}
2311
2312/**
2313 * Identify the advanced cache plugin used
2314 *
2315 * @return string The name of the advanced cache plugin, BOOST, WPSC or OTHER.
2316 */
2317function wpsc_identify_advanced_cache() {
2318    global $wpsc_advanced_cache_filename;
2319    if ( ! file_exists( $wpsc_advanced_cache_filename ) ) {
2320        return 'NONE';
2321    }
2322    $contents = file_get_contents( $wpsc_advanced_cache_filename ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
2323
2324    if ( false !== str_contains( $contents, 'Boost Cache Plugin' ) ) {
2325        return 'BOOST';
2326    }
2327
2328    if ( str_contains( $contents, 'WP SUPER CACHE 0.8.9.1' ) || str_contains( $contents, 'WP SUPER CACHE 1.2' ) ) {
2329        return 'WPSC';
2330    }
2331
2332    return 'OTHER';
2333}
2334
2335function wpsc_check_advanced_cache() {
2336    global $wpsc_advanced_cache_filename;
2337
2338    $ret                  = false;
2339    $other_advanced_cache = false;
2340    if ( file_exists( $wpsc_advanced_cache_filename ) ) {
2341        $cache_type = wpsc_identify_advanced_cache();
2342        switch ( $cache_type ) {
2343            case 'WPSC':
2344                return true;
2345            case 'BOOST':
2346                $other_advanced_cache = 'BOOST';
2347                break;
2348            default:
2349                $other_advanced_cache = true;
2350                break;
2351        }
2352    } else {
2353        $ret = wp_cache_create_advanced_cache();
2354    }
2355
2356    if ( false == $ret ) {
2357        if ( $other_advanced_cache === 'BOOST' ) {
2358            wpsc_deactivate_boost_cache_notice();
2359        } elseif ( $other_advanced_cache ) {
2360            echo '<div style="width: 50%" class="notice notice-error"><h2>' . __( 'Warning! You may not be allowed to use this plugin on your site.', 'wp-super-cache' ) . "</h2>";
2361            echo '<p>' .
2362                sprintf(
2363                    __( 'The file %s was created by another plugin or by your system administrator. Please examine the file carefully by FTP or SSH and consult your hosting documentation. ', 'wp-super-cache' ),
2364                    $wpsc_advanced_cache_filename
2365                ) .
2366                '</p>';
2367            echo '<p>' .
2368                __( 'If it was created by another caching plugin please uninstall that plugin first before activating WP Super Cache. If the file is not removed by that action you should delete the file manually.', 'wp-super-cache' ),
2369                '</p>';
2370            echo '<p><strong>' .
2371                __( 'If you need support for this problem contact your hosting provider.', 'wp-super-cache' ),
2372                '</strong></p>';
2373            echo '</div>';
2374        } elseif ( ! is_writeable_ACLSafe( $wpsc_advanced_cache_filename ) ) {
2375            echo '<div class="notice notice-error"><h2>' . __( 'Warning', 'wp-super-cache' ) . "! <em>" . sprintf( __( '%s/advanced-cache.php</em> cannot be updated.', 'wp-super-cache' ), WP_CONTENT_DIR ) . "</h2>";
2376            echo '<ol>';
2377            echo "<li>" .
2378                sprintf(
2379                    __( 'Make %1$s writable using the chmod command through your ftp or server software. (<em>chmod 777 %1$s</em>) and refresh this page. This is only a temporary measure and you&#8217;ll have to make it read only afterwards again. (Change 777 to 755 in the previous command)', 'wp-super-cache' ),
2380                    WP_CONTENT_DIR
2381                ) .
2382                "</li>";
2383            echo "<li>" . sprintf( __( 'Refresh this page to update <em>%s/advanced-cache.php</em>', 'wp-super-cache' ), WP_CONTENT_DIR ) . "</li></ol>";
2384            echo sprintf( __( 'If that doesn&#8217;t work, make sure the file <em>%s/advanced-cache.php</em> doesn&#8217;t exist:', 'wp-super-cache' ), WP_CONTENT_DIR ) . "<ol>";
2385            echo "</ol>";
2386            echo '</div>';
2387        }
2388        return false;
2389    }
2390    return true;
2391}
2392
2393function wp_cache_check_global_config() {
2394    global $wp_cache_check_wp_config;
2395
2396    if ( !isset( $wp_cache_check_wp_config ) )
2397        return true;
2398
2399
2400    if ( file_exists( ABSPATH . 'wp-config.php') ) {
2401        $global_config_file = ABSPATH . 'wp-config.php';
2402    } else {
2403        $global_config_file = dirname( ABSPATH ) . '/wp-config.php';
2404    }
2405
2406    if ( preg_match( '#^\s*(define\s*\(\s*[\'"]WP_CACHE[\'"]|const\s+WP_CACHE\s*=)#m', file_get_contents( $global_config_file ) ) === 1 ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
2407        if ( defined( 'WP_CACHE' ) && ! constant( 'WP_CACHE' ) ) {
2408            ?>
2409            <div class="notice notice-error"><h4><?php esc_html_e( 'WP_CACHE constant set to false', 'wp-super-cache' ); ?></h4>
2410            <p><?php esc_html_e( 'The WP_CACHE constant is used by WordPress to load the code that serves cached pages. Unfortunately, it is set to false. Please edit your wp-config.php and add or edit the following line above the final require_once command:', 'wp-super-cache' ); ?></p>
2411            <p><code>define('WP_CACHE', true);</code></p></div>
2412            <?php
2413            return false;
2414        } else {
2415            return true;
2416        }
2417    }
2418
2419    $line = 'define(\'WP_CACHE\', true);';
2420    if (
2421        ! is_writeable_ACLSafe( $global_config_file ) ||
2422        ! wp_cache_replace_line( 'define *\( *\'WP_CACHE\'', $line, $global_config_file )
2423    ) {
2424        if ( defined( 'WP_CACHE' ) && constant( 'WP_CACHE' ) == false ) {
2425            echo '<div class="notice notice-error">' . __( "<h4>WP_CACHE constant set to false</h4><p>The WP_CACHE constant is used by WordPress to load the code that serves cached pages. Unfortunately, it is set to false. Please edit your wp-config.php and add or edit the following line above the final require_once command:<br /><br /><code>define('WP_CACHE', true);</code></p>", 'wp-super-cache' ) . "</div>";
2426        } else {
2427            echo '<div class="notice notice-error"><p>' . __( "<strong>Error: WP_CACHE is not enabled</strong> in your <code>wp-config.php</code> file and I couldn&#8217;t modify it.", 'wp-super-cache' ) . "</p>";
2428            echo "<p>" . sprintf( __( "Edit <code>%s</code> and add the following line:<br /> <code>define('WP_CACHE', true);</code><br />Otherwise, <strong>WP-Cache will not be executed</strong> by WordPress core. ", 'wp-super-cache' ), $global_config_file ) . "</p></div>";
2429        }
2430        return false;
2431    }  else {
2432        echo "<div class='notice notice-warning'>" . __( '<h4>WP_CACHE constant added to wp-config.php</h4><p>If you continue to see this warning message please see point 5 of the <a href="https://wordpress.org/plugins/wp-super-cache/faq/">Troubleshooting Guide</a>. The WP_CACHE line must be moved up.', 'wp-super-cache' ) . "</p></div>";
2433    }
2434    return true;
2435}
2436
2437function wpsc_generate_sizes_array() {
2438    $sizes = array();
2439    $cache_types  = apply_filters( 'wpsc_cache_types', array( 'supercache', 'wpcache' ) );
2440    $cache_states = apply_filters( 'wpsc_cache_state', array( 'expired', 'cached' ) );
2441    foreach( $cache_types as $type ) {
2442        reset( $cache_states );
2443        foreach( $cache_states as $state ) {
2444            $sizes[ $type ][ $state ] = 0;
2445        }
2446        $sizes[ $type ][ 'fsize' ] = 0;
2447        $sizes[ $type ][ 'cached_list' ] = array();
2448        $sizes[ $type ][ 'expired_list' ] = array();
2449    }
2450    return $sizes;
2451}
2452
2453function wp_cache_format_fsize( $fsize ) {
2454    if ( $fsize > 1024 ) {
2455        $fsize = number_format( $fsize / 1024, 2 ) . "MB";
2456    } elseif ( $fsize != 0 ) {
2457        $fsize = number_format( $fsize, 2 ) . "KB";
2458    } else {
2459        $fsize = "0KB";
2460    }
2461    return $fsize;
2462}
2463
2464function wp_cache_regenerate_cache_file_stats() {
2465    global $cache_compression, $supercachedir, $file_prefix, $wp_cache_preload_on, $cache_max_time;
2466
2467    if ( $supercachedir == '' )
2468        $supercachedir = get_supercache_dir();
2469
2470    $sizes = wpsc_generate_sizes_array();
2471    $now = time();
2472    if (is_dir( $supercachedir ) ) {
2473        if ( $dh = opendir( $supercachedir ) ) {
2474            while ( ( $entry = readdir( $dh ) ) !== false ) {
2475                if ( $entry != '.' && $entry != '..' ) {
2476                    $sizes = wpsc_dirsize( trailingslashit( $supercachedir ) . $entry, $sizes );
2477                }
2478            }
2479            closedir( $dh );
2480        }
2481    }
2482    foreach( $sizes as $cache_type => $list ) {
2483        foreach( array( 'cached_list', 'expired_list' ) as $status ) {
2484            $cached_list = array();
2485            foreach( $list[ $status ] as $dir => $details ) {
2486                if ( $details[ 'files' ] == 2 && !isset( $details[ 'upper_age' ] ) ) {
2487                    $details[ 'files' ] = 1;
2488                }
2489                $cached_list[ $dir ] = $details;
2490            }
2491            $sizes[ $cache_type ][ $status ] = $cached_list;
2492        }
2493    }
2494    if ( $cache_compression ) {
2495        $sizes[ 'supercache' ][ 'cached' ]  = intval( $sizes[ 'supercache' ][ 'cached' ] / 2 );
2496        $sizes[ 'supercache' ][ 'expired' ] = intval( $sizes[ 'supercache' ][ 'expired' ] / 2 );
2497    }
2498    $cache_stats = array( 'generated' => time(), 'supercache' => $sizes[ 'supercache' ], 'wpcache' => $sizes[ 'wpcache' ] );
2499    update_option( 'supercache_stats', $cache_stats );
2500    return $cache_stats;
2501}
2502
2503function wp_cache_files() {
2504    global $cache_path, $file_prefix, $cache_max_time, $valid_nonce, $supercachedir, $super_cache_enabled, $blog_cache_dir, $cache_compression;
2505    global $wp_cache_preload_on;
2506
2507    if ( '/' != substr($cache_path, -1)) {
2508        $cache_path .= '/';
2509    }
2510
2511    if ( $valid_nonce ) {
2512        if(isset($_REQUEST['wp_delete_cache'])) {
2513            wp_cache_clean_cache($file_prefix);
2514            $_GET[ 'action' ] = 'regenerate_cache_stats';
2515        }
2516        if ( isset( $_REQUEST[ 'wp_delete_all_cache' ] ) ) {
2517            wp_cache_clean_cache( $file_prefix, true );
2518            $_GET[ 'action' ] = 'regenerate_cache_stats';
2519        }
2520        if(isset($_REQUEST['wp_delete_expired'])) {
2521            wp_cache_clean_expired($file_prefix);
2522            $_GET[ 'action' ] = 'regenerate_cache_stats';
2523        }
2524    }
2525    echo "<a name='listfiles'></a>";
2526    echo '<div class="wpsc-card">';
2527    echo '<fieldset class="options" id="show-this-fieldset"><h4>' . __( 'Cache Contents', 'wp-super-cache' ) . '</h4>';
2528
2529    $cache_stats = get_option( 'supercache_stats' );
2530    if ( !is_array( $cache_stats ) || ( isset( $_GET[ 'listfiles' ] ) ) || ( $valid_nonce && array_key_exists('action', $_GET) && $_GET[ 'action' ] == 'regenerate_cache_stats' ) ) {
2531    $count = 0;
2532    $expired = 0;
2533    $now = time();
2534    $wp_cache_fsize = 0;
2535    if ( ( $handle = @opendir( $blog_cache_dir ) ) ) {
2536        if ( $valid_nonce && isset( $_GET[ 'action' ] ) && $_GET[ 'action' ] == 'deletewpcache' ) {
2537            $deleteuri = wpsc_deep_replace( array( '..', '\\', 'index.php' ), preg_replace( '/[ <>\'\"\r\n\t\(\)]/', '', base64_decode( $_GET[ 'uri' ] ) ) );
2538        } else {
2539            $deleteuri = '';
2540        }
2541
2542        if ( $valid_nonce && isset( $_GET[ 'action' ] ) && $_GET[ 'action' ] == 'deletesupercache' ) {
2543            $supercacheuri = wpsc_deep_replace( array( '..', '\\', 'index.php' ), preg_replace( '/[ <>\'\"\r\n\t\(\)]/', '', preg_replace("/(\?.*)?$/", '', base64_decode( $_GET[ 'uri' ] ) ) ) );
2544            $supercacheuri = trailingslashit( realpath( $cache_path . 'supercache/' . $supercacheuri ) );
2545            if ( wp_cache_confirm_delete( $supercacheuri ) ) {
2546                printf( __( "Deleting supercache file: <strong>%s</strong><br />", 'wp-super-cache' ), $supercacheuri );
2547                wpsc_delete_files( $supercacheuri );
2548                prune_super_cache( $supercacheuri . 'page', true );
2549                @rmdir( $supercacheuri );
2550            } else {
2551                wp_die( __( 'Warning! You are not allowed to delete that file', 'wp-super-cache' ) );
2552            }
2553        }
2554        while( false !== ( $file = readdir( $handle ) ) ) {
2555            if ( // phpcs:ignore Generic.WhiteSpace.ScopeIndent.IncorrectExact
2556                str_contains( $file, $file_prefix )
2557                && substr( $file, -4 ) == '.php' // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual
2558            ) { // phpcs:ignore Generic.WhiteSpace.ScopeIndent.Incorrect
2559                if ( false == file_exists( $blog_cache_dir . 'meta/' . $file ) ) {
2560                    @unlink( $blog_cache_dir . $file );
2561                    continue; // meta does not exist
2562                }
2563                $mtime = filemtime( $blog_cache_dir . 'meta/' . $file );
2564                $fsize = @filesize( $blog_cache_dir . $file );
2565                if ( $fsize > 0 )
2566                    $fsize = $fsize - 15; // die() command takes 15 bytes at the start of the file
2567
2568                $age = $now - $mtime;
2569                if ( $valid_nonce && isset( $_GET[ 'listfiles' ] ) ) {
2570                    $meta = json_decode( wp_cache_get_legacy_cache( $blog_cache_dir . 'meta/' . $file ), true );
2571                    if ( $deleteuri != '' && $meta[ 'uri' ] == $deleteuri ) {
2572                        printf( __( "Deleting wp-cache file: <strong>%s</strong><br />", 'wp-super-cache' ), esc_html( $deleteuri ) );
2573                        @unlink( $blog_cache_dir . 'meta/' . $file );
2574                        @unlink( $blog_cache_dir . $file );
2575                        continue;
2576                    }
2577                    $meta[ 'age' ] = $age;
2578                    foreach( $meta as $key => $val )
2579                        $meta[ $key ] = esc_html( $val );
2580                    if ( $cache_max_time > 0 && $age > $cache_max_time ) {
2581                        $expired_list[ $age ][] = $meta;
2582                    } else {
2583                        $cached_list[ $age ][] = $meta;
2584                    }
2585                }
2586
2587                if ( $cache_max_time > 0 && $age > $cache_max_time ) {
2588                        ++$expired;
2589                } else {
2590                        ++$count;
2591                }
2592                $wp_cache_fsize += $fsize;
2593            }
2594        }
2595        closedir($handle);
2596    }
2597    if( $wp_cache_fsize != 0 ) {
2598        $wp_cache_fsize = $wp_cache_fsize/1024;
2599    } else {
2600        $wp_cache_fsize = 0;
2601    }
2602    if( $wp_cache_fsize > 1024 ) {
2603        $wp_cache_fsize = number_format( $wp_cache_fsize / 1024, 2 ) . "MB";
2604    } elseif( $wp_cache_fsize != 0 ) {
2605        $wp_cache_fsize = number_format( $wp_cache_fsize, 2 ) . "KB";
2606    } else {
2607        $wp_cache_fsize = '0KB';
2608    }
2609    $cache_stats = wp_cache_regenerate_cache_file_stats();
2610    } else {
2611        echo "<p>" . __( 'Cache stats are not automatically generated. You must click the link below to regenerate the stats on this page.', 'wp-super-cache' ) . "</p>";
2612        echo "<a href='" . wp_nonce_url( add_query_arg( array( 'page' => 'wpsupercache', 'tab' => 'contents', 'action' => 'regenerate_cache_stats' ) ), 'wp-cache' ) . "'>" . __( 'Regenerate cache stats', 'wp-super-cache' ) . "</a>";
2613        if ( ! empty( $cache_stats['generated'] ) ) {
2614            echo "<p>" . sprintf( __( 'Cache stats last generated: %s minutes ago.', 'wp-super-cache' ), number_format( ( time() - $cache_stats[ 'generated' ] ) / 60 ) ) . "</p>";
2615        }
2616        $cache_stats = get_option( 'supercache_stats' );
2617    }// regerate stats cache
2618
2619    if ( is_array( $cache_stats ) ) {
2620        $fsize = wp_cache_format_fsize( $cache_stats[ 'wpcache' ][ 'fsize' ] / 1024 );
2621        echo "<p><strong>" . __( 'WP-Cache', 'wp-super-cache' ) . " ({$fsize})</strong></p>";
2622        echo "<ul><li>" . sprintf( __( '%s Cached Pages', 'wp-super-cache' ), $cache_stats[ 'wpcache' ][ 'cached' ] ) . "</li>";
2623        echo "<li>" . sprintf( __( '%s Expired Pages', 'wp-super-cache' ),    $cache_stats[ 'wpcache' ][ 'expired' ] ) . "</li></ul>";
2624        if ( array_key_exists('fsize', (array)$cache_stats[ 'supercache' ]) )
2625            $fsize = $cache_stats[ 'supercache' ][ 'fsize' ] / 1024;
2626        else
2627            $fsize = 0;
2628        $fsize = wp_cache_format_fsize( $fsize );
2629        echo "<p><strong>" . __( 'WP-Super-Cache', 'wp-super-cache' ) . " ({$fsize})</strong></p>";
2630        echo "<ul><li>" . sprintf( __( '%s Cached Pages', 'wp-super-cache' ), $cache_stats[ 'supercache' ][ 'cached' ] ) . "</li>";
2631        if ( isset( $now ) && ! empty( $cache_stats['generated'] ) ) {
2632            $age = intval( ( $now - $cache_stats['generated'] ) / 60 );
2633        } else {
2634            $age = 0;
2635        }
2636        echo "<li>" . sprintf( __( '%s Expired Pages', 'wp-super-cache' ), $cache_stats[ 'supercache' ][ 'expired' ] ) . "</li></ul>";
2637        if ( $valid_nonce && array_key_exists('listfiles', $_GET) && isset( $_GET[ 'listfiles' ] ) ) {
2638            echo "<div style='padding: 10px; border: 1px solid #333; height: 400px; width: 90%; overflow: auto'>";
2639            $cache_description = array( 'supercache' => __( 'WP-Super-Cached', 'wp-super-cache' ), 'wpcache' => __( 'WP-Cached', 'wp-super-cache' ) );
2640            foreach( $cache_stats as $type => $details ) {
2641                if ( is_array( $details ) == false )
2642                    continue;
2643                foreach( array( 'cached_list' => 'Fresh', 'expired_list' => 'Stale' ) as $list => $description ) {
2644                    if ( is_array( $details[ $list ] ) & !empty( $details[ $list ] ) ) {
2645                        echo "<h5>" . sprintf( __( '%s %s Files', 'wp-super-cache' ), $description, $cache_description[ $type ] ) . "</h5>";
2646                        echo "<table class='widefat'><tr><th>#</th><th>" . __( 'URI', 'wp-super-cache' ) . "</th><th>" . __( 'Files', 'wp-super-cache' ) . "</th><th>" . __( 'Age', 'wp-super-cache' ) . "</th><th>" . __( 'Delete', 'wp-super-cache' ) . "</th></tr>";
2647                        $c = 1;
2648                        $flip = 1;
2649
2650                        ksort( $details[ $list ] );
2651                        foreach( $details[ $list ] as $directory => $d ) {
2652                            if ( isset( $d[ 'upper_age' ] ) ) {
2653                                $age = "{$d[ 'lower_age' ]} - {$d[ 'upper_age' ]}";
2654                            } else {
2655                                $age = $d[ 'lower_age' ];
2656                            }
2657                            $bg = $flip ? 'style="background: #EAEAEA;"' : '';
2658                            echo "<tr $bg><td>$c</td><td> <a href='http://{$directory}'>{$directory}</a></td><td>{$d[ 'files' ]}</td><td>{$age}</td><td><a href='" . wp_nonce_url( add_query_arg( array( 'page' => 'wpsupercache', 'action' => 'deletesupercache', 'uri' => base64_encode( $directory ) ) ), 'wp-cache' ) . "#listfiles'>X</a></td></tr>\n";
2659                            $flip = !$flip;
2660                            ++$c;
2661                        }
2662                        echo "</table>";
2663                    }
2664                }
2665            }
2666            echo "</div>";
2667            echo "<p><a href='?page=wpsupercache&tab=contents#top'>" . __( 'Hide file list', 'wp-super-cache' ) . "</a></p>";
2668        } elseif ( $cache_stats[ 'supercache' ][ 'cached' ] > 500 || $cache_stats[ 'supercache' ][ 'expired' ] > 500 || $cache_stats[ 'wpcache' ][ 'cached' ] > 500 || $cache_stats[ 'wpcache' ][ 'expired' ] > 500 ) {
2669            echo "<p><em>" . __( 'Too many cached files, no listing possible.', 'wp-super-cache' ) . "</em></p>";
2670        } else {
2671            echo "<p><a href='" . wp_nonce_url( add_query_arg( array( 'page' => 'wpsupercache', 'listfiles' => '1' ) ), 'wp-cache' ) . "#listfiles'>" . __( 'List all cached files', 'wp-super-cache' ) . "</a></p>";
2672        }
2673        if ( $cache_max_time > 0 )
2674            echo "<p>" . sprintf( __( 'Expired files are files older than %s seconds. They are still used by the plugin and are deleted periodically.', 'wp-super-cache' ), $cache_max_time ) . "</p>";
2675        if ( $wp_cache_preload_on )
2676            echo "<p>" . __( 'Preload mode is enabled. Supercache files will never be expired.', 'wp-super-cache' ) . "</p>";
2677    } // cache_stats
2678    wp_cache_delete_buttons();
2679
2680    echo '</fieldset>';
2681    echo '</div>';
2682}
2683
2684function wp_cache_delete_buttons() {
2685
2686    $admin_url = admin_url( 'options-general.php?page=wpsupercache' );
2687
2688    echo '<form name="wp_cache_content_expired" action="' . esc_url_raw( add_query_arg( 'tab', 'contents', $admin_url ) . '#listfiles' ) . '" method="post">';
2689    echo '<input type="hidden" name="wp_delete_expired" />';
2690    echo '<div class="submit" style="float:left"><input class="button-primary" type="submit" ' . SUBMITDISABLED . 'value="' . __( 'Delete Expired', 'wp-super-cache' ) . '" /></div>';
2691    wp_nonce_field('wp-cache');
2692    echo "</form>\n";
2693
2694    echo '<form name="wp_cache_content_delete" action="' . esc_url_raw( add_query_arg( 'tab', 'contents', $admin_url ) . '#listfiles' ) . '" method="post">';
2695    echo '<input type="hidden" name="wp_delete_cache" />';
2696    echo '<div class="submit" style="float:left;margin-left:10px"><input id="deletepost" class="button-secondary" type="submit" ' . SUBMITDISABLED . 'value="' . __( 'Delete Cache', 'wp-super-cache' ) . '" /></div>';
2697    wp_nonce_field('wp-cache');
2698    echo "</form>\n";
2699    if ( is_multisite() && wpsupercache_site_admin() ) {
2700        echo '<form name="wp_cache_content_delete" action="' . esc_url_raw( add_query_arg( 'tab', 'contents', $admin_url ) . '#listfiles' ) . '" method="post">';
2701        echo '<input type="hidden" name="wp_delete_all_cache" />';
2702        echo '<div class="submit" style="float:left;margin-left:10px"><input id="deleteallpost" class="button-secondary" type="submit" ' . SUBMITDISABLED . 'value="' . __( 'Delete Cache On All Blogs', 'wp-super-cache' ) . '" /></div>';
2703        wp_nonce_field('wp-cache');
2704        echo "</form>\n";
2705    }
2706}
2707
2708function delete_cache_dashboard() {
2709    if ( function_exists( '_deprecated_function' ) ) {
2710        _deprecated_function( __FUNCTION__, 'WP Super Cache 1.6.4' );
2711    }
2712
2713    if ( false == wpsupercache_site_admin() )
2714        return false;
2715
2716    if ( function_exists('current_user_can') && !current_user_can('manage_options') )
2717        return false;
2718
2719    echo "<li><a href='" . wp_nonce_url( 'options-general.php?page=wpsupercache&wp_delete_cache=1', 'wp-cache' ) . "' target='_blank' title='" . __( 'Delete Super Cache cached files (opens in new window)', 'wp-super-cache' ) . "'>" . __( 'Delete Cache', 'wp-super-cache' ) . "</a></li>";
2720}
2721//add_action( 'dashmenu', 'delete_cache_dashboard' );
2722
2723function wpsc_dirsize($directory, $sizes) {
2724    global $cache_max_time, $cache_path, $valid_nonce, $wp_cache_preload_on, $file_prefix;
2725    $now = time();
2726
2727    if (is_dir($directory)) {
2728        if( $dh = opendir( $directory ) ) {
2729            while( ( $entry = readdir( $dh ) ) !== false ) {
2730                if ($entry != '.' && $entry != '..') {
2731                    $sizes = wpsc_dirsize( trailingslashit( $directory ) . $entry, $sizes );
2732                }
2733            }
2734            closedir($dh);
2735        }
2736    } elseif ( is_file( $directory ) && strpos( $directory, 'meta-' . $file_prefix ) === false ) {
2737        if ( strpos( $directory, '/' . $file_prefix ) !== false ) {
2738            $cache_type = 'wpcache';
2739        } else {
2740            $cache_type = 'supercache';
2741        }
2742        $keep_fresh = false;
2743        if ( $cache_type === 'supercache' && $wp_cache_preload_on ) {
2744            $keep_fresh = true;
2745        }
2746        $filem = filemtime( $directory );
2747        if ( ! $keep_fresh && $cache_max_time > 0 && $filem + $cache_max_time <= $now ) {
2748            $cache_status = 'expired';
2749        } else {
2750            $cache_status = 'cached';
2751        }
2752        $sizes[ $cache_type ][ $cache_status ] += 1;
2753        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Presumably the caller should handle it if necessary.
2754        if ( $valid_nonce && isset( $_GET['listfiles'] ) ) {
2755            $dir = str_replace( $cache_path . 'supercache/', '', dirname( $directory ) );
2756            $age = $now - $filem;
2757            if ( ! isset( $sizes[ $cache_type ][ $cache_status . '_list' ][ $dir ] ) ) {
2758                $sizes[ $cache_type ][ $cache_status . '_list' ][ $dir ]['lower_age'] = $age;
2759                $sizes[ $cache_type ][ $cache_status . '_list' ][ $dir ]['files']     = 1;
2760            } else {
2761                $sizes[ $cache_type ][ $cache_status . '_list' ][ $dir ]['files'] += 1;
2762                if ( $age <= $sizes[ $cache_type ][ $cache_status . '_list' ][ $dir ]['lower_age'] ) {
2763
2764                    if ( $age < $sizes[ $cache_type ][ $cache_status . '_list' ][ $dir ]['lower_age'] && ! isset( $sizes[ $cache_type ][ $cache_status . '_list' ][ $dir ]['upper_age'] ) ) {
2765                        $sizes[ $cache_type ][ $cache_status . '_list' ][ $dir ]['upper_age'] = $sizes[ $cache_type ][ $cache_status . '_list' ][ $dir ]['lower_age'];
2766                    }
2767
2768                    $sizes[ $cache_type ][ $cache_status . '_list' ][ $dir ]['lower_age'] = $age;
2769
2770                } elseif ( ! isset( $sizes[ $cache_type ][ $cache_status . '_list' ][ $dir ]['upper_age'] ) || $age > $sizes[ $cache_type ][ $cache_status . '_list' ][ $dir ]['upper_age'] ) {
2771
2772                    $sizes[ $cache_type ][ $cache_status . '_list' ][ $dir ]['upper_age'] = $age;
2773
2774                }
2775            }
2776        }
2777        if ( ! isset( $sizes['fsize'] ) ) {
2778            // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
2779            $sizes[ $cache_type ]['fsize'] = @filesize( $directory );
2780        } else {
2781            // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
2782            $sizes[ $cache_type ]['fsize'] += @filesize( $directory );
2783        }
2784    }
2785    return $sizes;
2786}
2787
2788function wp_cache_clean_cache( $file_prefix, $all = false ) {
2789    global $cache_path, $supercachedir, $blog_cache_dir;
2790
2791    do_action( 'wp_cache_cleared' );
2792
2793    if ( $all == true && wpsupercache_site_admin() && function_exists( 'prune_super_cache' ) ) {
2794        prune_super_cache( $cache_path, true );
2795        return true;
2796    }
2797    if ( $supercachedir == '' )
2798        $supercachedir = get_supercache_dir();
2799
2800    if (function_exists ('prune_super_cache')) {
2801        if( is_dir( $supercachedir ) ) {
2802            prune_super_cache( $supercachedir, true );
2803        } elseif( is_dir( $supercachedir . '.disabled' ) ) {
2804            prune_super_cache( $supercachedir . '.disabled', true );
2805        }
2806        $_POST[ 'super_cache_stats' ] = 1; // regenerate super cache stats;
2807    } else {
2808        wp_cache_debug( 'Warning! prune_super_cache() not found in wp-cache.php', 1 );
2809    }
2810
2811    wp_cache_clean_legacy_files( $blog_cache_dir, $file_prefix );
2812    wp_cache_clean_legacy_files( $cache_path, $file_prefix );
2813}
2814
2815function wpsc_delete_post_cache( $id ) {
2816    $post = get_post( $id );
2817    wpsc_delete_url_cache( get_author_posts_url( (int) $post->post_author ) );
2818    $permalink = get_permalink( $id );
2819    if ( $permalink != '' ) {
2820        wpsc_delete_url_cache( $permalink );
2821        return true;
2822    } else {
2823        return false;
2824    }
2825}
2826
2827function wp_cache_clean_legacy_files( $dir, $file_prefix ) {
2828    global $wpdb;
2829
2830    $dir = trailingslashit( $dir );
2831    if ( @is_dir( $dir . 'meta' ) == false )
2832        return false;
2833
2834    if ( $handle = @opendir( $dir ) ) {
2835        $curr_blog_id = is_multisite() ? get_current_blog_id() : false;
2836
2837        while ( false !== ( $file = readdir( $handle ) ) ) {
2838            if ( is_file( $dir . $file ) == false || $file == 'index.html' ) {
2839                continue;
2840            }
2841
2842            if ( str_contains( $file, $file_prefix ) ) {
2843                if ( strpos( $file, '.html' ) ) {
2844                    // delete old WPCache files immediately
2845                    @unlink( $dir . $file);
2846                    @unlink( $dir . 'meta/' . str_replace( '.html', '.meta', $file ) );
2847                } else {
2848                    $meta = json_decode( wp_cache_get_legacy_cache( $dir . 'meta/' . $file ), true );
2849                    if ( $curr_blog_id && $curr_blog_id !== (int) $meta['blog_id'] ) {
2850                        continue;
2851                    }
2852                    @unlink( $dir . $file);
2853                    @unlink( $dir . 'meta/' . $file);
2854                }
2855            }
2856        }
2857        closedir($handle);
2858    }
2859}
2860
2861function wp_cache_clean_expired($file_prefix) {
2862    global $cache_max_time, $blog_cache_dir, $wp_cache_preload_on;
2863
2864    if ( $cache_max_time == 0 ) {
2865        return false;
2866    }
2867
2868    // If phase2 was compiled, use its function to avoid race-conditions
2869    if(function_exists('wp_cache_phase2_clean_expired')) {
2870        if ( $wp_cache_preload_on != 1 && function_exists ('prune_super_cache')) {
2871            $dir = get_supercache_dir();
2872            if( is_dir( $dir ) ) {
2873                prune_super_cache( $dir );
2874            } elseif( is_dir( $dir . '.disabled' ) ) {
2875                prune_super_cache( $dir . '.disabled' );
2876            }
2877            $_POST[ 'super_cache_stats' ] = 1; // regenerate super cache stats;
2878        }
2879        return wp_cache_phase2_clean_expired($file_prefix);
2880    }
2881
2882    $now = time();
2883    if ( $handle = @opendir( $blog_cache_dir ) ) {
2884        while ( false !== ( $file = readdir( $handle ) ) ) {
2885            if ( str_contains( $file, $file_prefix ) ) {
2886                if ( strpos( $file, '.html' ) ) {
2887                    @unlink( $blog_cache_dir . $file);
2888                    @unlink( $blog_cache_dir . 'meta/' . str_replace( '.html', '.meta', $file ) );
2889                } elseif ( ( filemtime( $blog_cache_dir . $file ) + $cache_max_time ) <= $now ) {
2890                    @unlink( $blog_cache_dir . $file );
2891                    @unlink( $blog_cache_dir . 'meta/' . $file );
2892                }
2893            }
2894        }
2895        closedir($handle);
2896    }
2897}
2898
2899function wpsc_remove_marker( $filename, $marker ) {
2900    if (!file_exists( $filename ) || is_writeable_ACLSafe( $filename ) ) {
2901        if (!file_exists( $filename ) ) {
2902            return '';
2903        } else {
2904            $markerdata = explode( "\n", implode( '', file( $filename ) ) );
2905        }
2906
2907        $f = fopen( $filename, 'w' );
2908        $state = true;
2909        foreach ( $markerdata as $n => $markerline ) {
2910            if ( strpos( $markerline, '# BEGIN ' . $marker ) !== false ) {
2911                $state = false;
2912            }
2913            if ( $state ) {
2914                if ( $n + 1 < count( $markerdata ) ) {
2915                    fwrite( $f, "{$markerline}\n" ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite
2916                } else {
2917                    fwrite( $f, "{$markerline}" ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite
2918                }
2919            }
2920            if ( strpos( $markerline, '# END ' . $marker ) !== false ) {
2921                $state = true;
2922            }
2923        }
2924        return true;
2925    } else {
2926        return false;
2927    }
2928}
2929
2930if( get_option( 'gzipcompression' ) )
2931    update_option( 'gzipcompression', 0 );
2932
2933// Catch 404 requests. Themes that use query_posts() destroy $wp_query->is_404
2934function wp_cache_catch_404() {
2935    global $wp_cache_404;
2936    if ( function_exists( '_deprecated_function' ) )
2937        _deprecated_function( __FUNCTION__, 'WP Super Cache 1.5.6' );
2938    $wp_cache_404 = false;
2939    if( is_404() )
2940        $wp_cache_404 = true;
2941}
2942//More info - https://github.com/Automattic/wp-super-cache/pull/373
2943//add_action( 'template_redirect', 'wp_cache_catch_404' );
2944
2945function wp_cache_favorite_action( $actions ) {
2946    if ( function_exists( '_deprecated_function' ) ) {
2947        _deprecated_function( __FUNCTION__, 'WP Super Cache 1.6.4' );
2948    }
2949
2950    if ( false == wpsupercache_site_admin() )
2951        return $actions;
2952
2953    if ( function_exists('current_user_can') && !current_user_can('manage_options') )
2954        return $actions;
2955
2956    $actions[ wp_nonce_url( 'options-general.php?page=wpsupercache&wp_delete_cache=1&tab=contents', 'wp-cache' ) ] = array( __( 'Delete Cache', 'wp-super-cache' ), 'manage_options' );
2957
2958    return $actions;
2959}
2960//add_filter( 'favorite_actions', 'wp_cache_favorite_action' );
2961
2962function wp_cache_plugin_notice( $plugin ) {
2963    global $cache_enabled;
2964    if( $plugin == 'wp-super-cache/wp-cache.php' && !$cache_enabled && function_exists( 'admin_url' ) )
2965        echo '<td colspan="5" class="plugin-update">' . sprintf( __( 'WP Super Cache must be configured. Go to <a href="%s">the admin page</a> to enable and configure the plugin.', 'wp-super-cache' ), admin_url( 'options-general.php?page=wpsupercache' ) ) . '</td>';
2966}
2967add_action( 'after_plugin_row', 'wp_cache_plugin_notice' );
2968
2969function wp_cache_plugin_actions( $links, $file ) {
2970    if ( $file === 'wp-super-cache/wp-cache.php' && function_exists( 'admin_url' ) && is_array( $links ) ) {
2971        $settings_link = '<a href="' . admin_url( 'options-general.php?page=wpsupercache' ) . '">' . __( 'Settings', 'wp-super-cache' ) . '</a>';
2972        array_unshift( $links, $settings_link ); // before other links
2973    }
2974    return $links;
2975}
2976add_filter( 'plugin_action_links', 'wp_cache_plugin_actions', 10, 2 );
2977
2978function wp_cache_admin_notice() {
2979    global $cache_enabled, $wp_cache_phase1_loaded;
2980    if( substr( $_SERVER['PHP_SELF'], -11 ) == 'plugins.php' && !$cache_enabled && function_exists( 'admin_url' ) )
2981        echo '<div class="notice notice-info"><p><strong>' . sprintf( __('WP Super Cache is disabled. Please go to the <a href="%s">plugin admin page</a> to enable caching.', 'wp-super-cache' ), admin_url( 'options-general.php?page=wpsupercache' ) ) . '</strong></p></div>';
2982
2983    if ( defined( 'WP_CACHE' ) && WP_CACHE == true && ( defined( 'ADVANCEDCACHEPROBLEM' ) || ( $cache_enabled && false == isset( $wp_cache_phase1_loaded ) ) ) ) {
2984        if ( wp_cache_create_advanced_cache() ) {
2985            echo '<div class="notice notice-error"><p>' . sprintf( __( 'Warning! WP Super Cache caching <strong>was</strong> broken but has been <strong>fixed</strong>! The script advanced-cache.php could not load wp-cache-phase1.php.<br /><br />The file %1$s/advanced-cache.php has been recreated and WPCACHEHOME fixed in your wp-config.php. Reload to hide this message.', 'wp-super-cache' ), WP_CONTENT_DIR ) . '</p></div>';
2986        }
2987    }
2988}
2989add_action( 'admin_notices', 'wp_cache_admin_notice' );
2990
2991function wp_cache_check_site() {
2992    global $wp_super_cache_front_page_check, $wp_super_cache_front_page_clear, $wp_super_cache_front_page_text, $wp_super_cache_front_page_notification, $wpdb;
2993
2994    if ( empty( $wp_super_cache_front_page_check ) ) {
2995        return false;
2996    }
2997
2998    if ( function_exists( "wp_remote_get" ) == false ) {
2999        return false;
3000    }
3001    $front_page = wp_remote_get( site_url(), array('timeout' => 60, 'blocking' => true ) );
3002    if( is_array( $front_page ) ) {
3003        // Check for gzipped front page
3004        if ( $front_page[ 'headers' ][ 'content-type' ] == 'application/x-gzip' ) {
3005            if ( ! isset( $wp_super_cache_front_page_clear ) || $wp_super_cache_front_page_clear === 0 ) {
3006                wp_mail( get_option( 'admin_email' ), sprintf( __( '[%s] Front page is gzipped! Please clear cache!', 'wp-super-cache' ), home_url() ), sprintf( __( "Please visit %s to clear the cache as the front page of your site is now downloading!", 'wp-super-cache' ), admin_url( 'options-general.php?page=wpsupercache' ) ) );
3007            } else {
3008                wp_cache_clear_cache( $wpdb->blogid );
3009                wp_mail( get_option( 'admin_email' ), sprintf( __( '[%s] Front page is gzipped! Cache Cleared!', 'wp-super-cache' ), home_url() ), sprintf( __( "The cache on your blog has been cleared because the front page of your site is now downloading. Please visit %s to verify the cache has been cleared.", 'wp-super-cache' ), admin_url( 'options-general.php?page=wpsupercache' ) ) );
3010            }
3011        }
3012
3013        // Check for broken front page
3014        if (
3015            ! empty( $wp_super_cache_front_page_text )
3016            && ! str_contains( $front_page['body'], $wp_super_cache_front_page_text )
3017        ) {
3018            if ( ! isset( $wp_super_cache_front_page_clear ) || $wp_super_cache_front_page_clear === 0 ) {
3019                wp_mail( get_option( 'admin_email' ), sprintf( __( '[%s] Front page is not correct! Please clear cache!', 'wp-super-cache' ), home_url() ), sprintf( __( 'Please visit %1$s to clear the cache as the front page of your site is not correct and missing the text, "%2$s"!', 'wp-super-cache' ), admin_url( 'options-general.php?page=wpsupercache' ), $wp_super_cache_front_page_text ) );
3020            } else {
3021                wp_cache_clear_cache( $wpdb->blogid );
3022                wp_mail( get_option( 'admin_email' ), sprintf( __( '[%s] Front page is not correct! Cache Cleared!', 'wp-super-cache' ), home_url() ), sprintf( __( 'The cache on your blog has been cleared because the front page of your site is missing the text "%2$s". Please visit %1$s to verify the cache has been cleared.', 'wp-super-cache' ), admin_url( 'options-general.php?page=wpsupercache' ), $wp_super_cache_front_page_text ) );
3023            }
3024        }
3025    }
3026    if ( isset( $wp_super_cache_front_page_notification ) && $wp_super_cache_front_page_notification == 1 ) {
3027        wp_mail( get_option( 'admin_email' ), sprintf( __( '[%s] Front page check!', 'wp-super-cache' ), home_url() ), sprintf( __( "WP Super Cache has checked the front page of your blog. Please visit %s if you would like to disable this.", 'wp-super-cache' ) . "\n\n", admin_url( 'options-general.php?page=wpsupercache' ) ) );
3028    }
3029
3030    if ( !wp_next_scheduled( 'wp_cache_check_site_hook' ) ) {
3031        wp_schedule_single_event( time() + 360 , 'wp_cache_check_site_hook' );
3032        wp_cache_debug( 'scheduled wp_cache_check_site_hook for 360 seconds time.', 2 );
3033    }
3034}
3035add_action( 'wp_cache_check_site_hook', 'wp_cache_check_site' );
3036
3037function update_cached_mobile_ua_list( $mobile_browsers, $mobile_prefixes = 0, $mobile_groups = 0 ) {
3038    global $wp_cache_config_file, $wp_cache_mobile_browsers, $wp_cache_mobile_prefixes, $wp_cache_mobile_groups;
3039    wp_cache_setting( 'wp_cache_mobile_browsers', $mobile_browsers );
3040    wp_cache_setting( 'wp_cache_mobile_prefixes', $mobile_prefixes );
3041    if ( is_array( $mobile_groups ) ) {
3042        $wp_cache_mobile_groups = $mobile_groups;
3043        wp_cache_replace_line('^ *\$wp_cache_mobile_groups', "\$wp_cache_mobile_groups = '" . implode( ', ', $mobile_groups ) . "';", $wp_cache_config_file);
3044    }
3045
3046    return true;
3047}
3048
3049function wpsc_update_htaccess() {
3050    extract( wpsc_get_htaccess_info() ); // $document_root, $apache_root, $home_path, $home_root, $home_root_lc, $inst_root, $wprules, $scrules, $condition_rules, $rules, $gziprules
3051    // @phan-suppress-next-line PhanTypeSuspiciousStringExpression -- $home_path is set via extract()
3052    wpsc_remove_marker( $home_path.'.htaccess', 'WordPress' ); // remove original WP rules so SuperCache rules go on top
3053    // @phan-suppress-next-line PhanTypeSuspiciousStringExpression -- $home_path is set via extract()
3054    if( insert_with_markers( $home_path.'.htaccess', 'WPSuperCache', explode( "\n", $rules ) ) && insert_with_markers( $home_path.'.htaccess', 'WordPress', explode( "\n", $wprules ) ) ) {
3055        return true;
3056    } else {
3057        return false;
3058    }
3059}
3060
3061function wpsc_update_htaccess_form( $short_form = true ) {
3062    global $wpmu_version;
3063
3064    $admin_url = admin_url( 'options-general.php?page=wpsupercache' );
3065    extract( wpsc_get_htaccess_info() ); // $document_root, $apache_root, $home_path, $home_root, $home_root_lc, $inst_root, $wprules, $scrules, $condition_rules, $rules, $gziprules
3066    // @phan-suppress-next-line PhanTypeSuspiciousStringExpression -- $home_path is set via extract()
3067    if( !is_writeable_ACLSafe( $home_path . ".htaccess" ) ) {
3068        echo "<div style='padding:0 8px;color:#9f6000;background-color:#feefb3;border:1px solid #9f6000;'><h5>" . __( 'Cannot update .htaccess', 'wp-super-cache' ) . "</h5><p>" . sprintf( __( 'The file <code>%s.htaccess</code> cannot be modified by the web server. Please correct this using the chmod command or your ftp client.', 'wp-super-cache' ), $home_path ) . "</p><p>" . __( 'Refresh this page when the file permissions have been modified.' ) . "</p><p>" . sprintf( __( 'Alternatively, you can edit your <code>%s.htaccess</code> file manually and add the following code (before any WordPress rules):', 'wp-super-cache' ), $home_path ) . "</p>";
3069        echo "<p><pre># BEGIN WPSuperCache\n" . esc_html( $rules ) . "# END WPSuperCache</pre></p></div>";
3070    } else {
3071        if ( $short_form == false ) {
3072            echo "<p>" . sprintf( __( 'To serve static html files your server must have the correct mod_rewrite rules added to a file called <code>%s.htaccess</code>', 'wp-super-cache' ), $home_path ) . " ";
3073            _e( "You can edit the file yourself. Add the following rules.", 'wp-super-cache' );
3074            echo __( " Make sure they appear before any existing WordPress rules. ", 'wp-super-cache' ) . "</p>";
3075            echo "<div style='overflow: auto; width: 800px; height: 400px; padding:0 8px;color:#9f6000;background-color:#feefb3;border:1px solid #9f6000;'>";
3076            echo "<pre># BEGIN WPSuperCache\n" . esc_html( $rules ) . "# END WPSuperCache</pre></p>";
3077            echo "</div>";
3078            echo "<h5>" . sprintf( __( 'Rules must be added to %s too:', 'wp-super-cache' ), WP_CONTENT_DIR . "/cache/.htaccess" ) . "</h5>";
3079            echo "<div style='overflow: auto; width: 800px; height: 400px; padding:0 8px;color:#9f6000;background-color:#feefb3;border:1px solid #9f6000;'>";
3080            echo "<pre># BEGIN supercache\n" . esc_html( $gziprules ) . "# END supercache</pre></p>";
3081            echo "</div>";
3082        }
3083        if ( !isset( $wpmu_version ) || $wpmu_version == '' ) {
3084            echo '<form name="updatehtaccess" action="' . esc_url_raw( add_query_arg( 'tab', 'settings', $admin_url ) . '#modrewrite' ) . '" method="post">';
3085            echo '<input type="hidden" name="updatehtaccess" value="1" />';
3086            echo '<div class="submit"><input class="button-primary" type="submit" ' . SUBMITDISABLED . 'id="updatehtaccess" value="' . __( 'Update Mod_Rewrite Rules', 'wp-super-cache' ) . '" /></div>';
3087            wp_nonce_field('wp-cache');
3088            echo "</form>\n";
3089        }
3090    }
3091}
3092
3093/*
3094 * Return LOGGED_IN_COOKIE if it doesn't begin with wordpress_logged_in
3095 * to avoid having people update their .htaccess file
3096 */
3097function wpsc_get_logged_in_cookie() {
3098    $logged_in_cookie = 'wordpress_logged_in';
3099    if ( defined( 'LOGGED_IN_COOKIE' ) && substr( constant( 'LOGGED_IN_COOKIE' ), 0, 19 ) != 'wordpress_logged_in' )
3100        $logged_in_cookie = constant( 'LOGGED_IN_COOKIE' );
3101    return $logged_in_cookie;
3102}
3103
3104function wpsc_get_htaccess_info() {
3105    global $wp_cache_mobile_enabled, $wp_cache_mobile_prefixes, $wp_cache_mobile_browsers, $wp_cache_disable_utf8;
3106    global $htaccess_path;
3107
3108    if ( isset( $_SERVER[ "PHP_DOCUMENT_ROOT" ] ) ) {
3109        $document_root = $_SERVER[ "PHP_DOCUMENT_ROOT" ];
3110        $apache_root = $_SERVER[ "PHP_DOCUMENT_ROOT" ];
3111    } else {
3112        $document_root = $_SERVER[ "DOCUMENT_ROOT" ];
3113        $apache_root = '%{DOCUMENT_ROOT}';
3114    }
3115    $content_dir_root = $document_root;
3116    if ( strpos( $document_root, '/kunden/homepages/' ) === 0 ) {
3117        // https://wordpress.org/support/topic/plugin-wp-super-cache-how-to-get-mod_rewrite-working-on-1and1-shared-hosting?replies=1
3118        // On 1and1, PHP's directory structure starts with '/homepages'. The
3119        // Apache directory structure has an extra '/kunden' before it.
3120        // Also 1and1 does not support the %{DOCUMENT_ROOT} variable in
3121        // .htaccess files.
3122        // This prevents the $inst_root from being calculated correctly and
3123        // means that the $apache_root is wrong.
3124        //
3125        // e.g. This is an example of how Apache and PHP see the directory
3126        // structure on    1and1:
3127        // Apache: /kunden/homepages/xx/dxxxxxxxx/htdocs/site1/index.html
3128        // PHP:           /homepages/xx/dxxxxxxxx/htdocs/site1/index.html
3129        // Here we fix up the paths to make mode_rewrite work on 1and1 shared hosting.
3130        $content_dir_root = substr( $content_dir_root, 7 );
3131        $apache_root = $document_root;
3132    }
3133    $home_path = get_home_path();
3134    $home_root = parse_url(get_bloginfo('url'));
3135    $home_root = isset( $home_root[ 'path' ] ) ? trailingslashit( $home_root[ 'path' ] ) : '/';
3136    if ( isset( $htaccess_path ) ) {
3137        $home_path = $htaccess_path;
3138    } elseif (
3139        $home_root == '/' &&
3140        $home_path != $_SERVER[ 'DOCUMENT_ROOT' ]
3141    ) {
3142        $home_path = $_SERVER[ 'DOCUMENT_ROOT' ];
3143    } elseif (
3144        $home_root != '/' &&
3145        $home_path != str_replace( '//', '/', $_SERVER[ 'DOCUMENT_ROOT' ] . $home_root ) &&
3146        is_dir( $_SERVER[ 'DOCUMENT_ROOT' ] . $home_root )
3147    ) {
3148        $home_path = str_replace( '//', '/', $_SERVER[ 'DOCUMENT_ROOT' ] . $home_root );
3149    }
3150
3151    $home_path = trailingslashit( $home_path );
3152    $home_root_lc = str_replace( '//', '/', strtolower( $home_root ) );
3153    $inst_root = str_replace( '//', '/', '/' . trailingslashit( str_replace( $content_dir_root, '', str_replace( '\\', '/', WP_CONTENT_DIR ) ) ) );
3154    $wprules = implode( "\n", extract_from_markers( $home_path.'.htaccess', 'WordPress' ) );
3155    $wprules = str_replace( "RewriteEngine On\n", '', $wprules );
3156    $wprules = str_replace( "RewriteBase $home_root\n", '', $wprules );
3157    $scrules = implode( "\n", extract_from_markers( $home_path.'.htaccess', 'WPSuperCache' ) );
3158
3159    if( substr( get_option( 'permalink_structure' ), -1 ) == '/' ) {
3160        $condition_rules[] = "RewriteCond %{REQUEST_URI} !^.*[^/]$";
3161        $condition_rules[] = "RewriteCond %{REQUEST_URI} !^.*//.*$";
3162    }
3163    $condition_rules[] = "RewriteCond %{REQUEST_METHOD} !POST";
3164    $condition_rules[] = "RewriteCond %{QUERY_STRING} ^$";
3165    $condition_rules[] = "RewriteCond %{HTTP:Cookie} !^.*(comment_author_|" . wpsc_get_logged_in_cookie() . wpsc_get_extra_cookies() . "|wp-postpass_).*$";
3166    $condition_rules[] = "RewriteCond %{HTTP:X-Wap-Profile} !^[a-z0-9\\\"]+ [NC]";
3167    $condition_rules[] = "RewriteCond %{HTTP:Profile} !^[a-z0-9\\\"]+ [NC]";
3168    if ( $wp_cache_mobile_enabled ) {
3169        if ( isset( $wp_cache_mobile_browsers ) && "" != $wp_cache_mobile_browsers )
3170            $condition_rules[] = "RewriteCond %{HTTP_USER_AGENT} !^.*(" . addcslashes( str_replace( ', ', '|', $wp_cache_mobile_browsers ), ' ' ) . ").* [NC]";
3171        if ( isset( $wp_cache_mobile_prefixes ) && "" != $wp_cache_mobile_prefixes )
3172            $condition_rules[] = "RewriteCond %{HTTP_USER_AGENT} !^(" . addcslashes( str_replace( ', ', '|', $wp_cache_mobile_prefixes ), ' ' ) . ").* [NC]";
3173    }
3174    $condition_rules = apply_filters( 'supercacherewriteconditions', $condition_rules );
3175
3176    $rules = "<IfModule mod_rewrite.c>\n";
3177    $rules .= "RewriteEngine On\n";
3178    $rules .= "RewriteBase $home_root\n"; // props Chris Messina
3179    $rules .= "#If you serve pages from behind a proxy you may want to change 'RewriteCond %{HTTPS} on' to something more sensible\n";
3180    if ( isset( $wp_cache_disable_utf8 ) == false || $wp_cache_disable_utf8 == 0 ) {
3181        $charset = get_option('blog_charset') == '' ? 'UTF-8' : get_option('blog_charset');
3182        $rules .= "AddDefaultCharset {$charset}\n";
3183    }
3184
3185    $rules .= "CONDITION_RULES";
3186    $rules .= "RewriteCond %{HTTP:Accept-Encoding} gzip\n";
3187    $rules .= "RewriteCond %{HTTPS} on\n";
3188    $rules .= "RewriteCond {$apache_root}{$inst_root}cache/supercache/%{SERVER_NAME}{$home_root_lc}$1/index-https.html.gz -f\n";
3189    $rules .= "RewriteRule ^(.*) \"{$inst_root}cache/supercache/%{SERVER_NAME}{$home_root_lc}$1/index-https.html.gz\" [L]\n\n";
3190
3191    $rules .= "CONDITION_RULES";
3192    $rules .= "RewriteCond %{HTTP:Accept-Encoding} gzip\n";
3193    $rules .= "RewriteCond %{HTTPS} !on\n";
3194    $rules .= "RewriteCond {$apache_root}{$inst_root}cache/supercache/%{SERVER_NAME}{$home_root_lc}$1/index.html.gz -f\n";
3195    $rules .= "RewriteRule ^(.*) \"{$inst_root}cache/supercache/%{SERVER_NAME}{$home_root_lc}$1/index.html.gz\" [L]\n\n";
3196
3197    $rules .= "CONDITION_RULES";
3198    $rules .= "RewriteCond %{HTTPS} on\n";
3199    $rules .= "RewriteCond {$apache_root}{$inst_root}cache/supercache/%{SERVER_NAME}{$home_root_lc}$1/index-https.html -f\n";
3200    $rules .= "RewriteRule ^(.*) \"{$inst_root}cache/supercache/%{SERVER_NAME}{$home_root_lc}$1/index-https.html\" [L]\n\n";
3201
3202    $rules .= "CONDITION_RULES";
3203    $rules .= "RewriteCond %{HTTPS} !on\n";
3204    $rules .= "RewriteCond {$apache_root}{$inst_root}cache/supercache/%{SERVER_NAME}{$home_root_lc}$1/index.html -f\n";
3205    $rules .= "RewriteRule ^(.*) \"{$inst_root}cache/supercache/%{SERVER_NAME}{$home_root_lc}$1/index.html\" [L]\n";
3206    $rules .= "</IfModule>\n";
3207    $rules = apply_filters( 'supercacherewriterules', $rules );
3208
3209    $rules = str_replace( "CONDITION_RULES", implode( "\n", $condition_rules ) . "\n", $rules );
3210
3211    $gziprules =  "<IfModule mod_mime.c>\n  <FilesMatch \"\\.html\\.gz\$\">\n    ForceType text/html\n    FileETag None\n  </FilesMatch>\n  AddEncoding gzip .gz\n  AddType text/html .gz\n</IfModule>\n";
3212    $gziprules .= "<IfModule mod_deflate.c>\n  SetEnvIfNoCase Request_URI \.gz$ no-gzip\n</IfModule>\n";
3213
3214    // Default headers.
3215    $headers = array(
3216        'Vary'          => 'Accept-Encoding, Cookie',
3217        'Cache-Control' => 'max-age=3, must-revalidate',
3218    );
3219
3220    // Allow users to override the Vary header with WPSC_VARY_HEADER.
3221    if ( defined( 'WPSC_VARY_HEADER' ) && ! empty( WPSC_VARY_HEADER ) ) {
3222        $headers['Vary'] = WPSC_VARY_HEADER;
3223    }
3224
3225    // Allow users to override Cache-control header with WPSC_CACHE_CONTROL_HEADER
3226    if ( defined( 'WPSC_CACHE_CONTROL_HEADER' ) && ! empty( WPSC_CACHE_CONTROL_HEADER ) ) {
3227        $headers['Cache-Control'] = WPSC_CACHE_CONTROL_HEADER;
3228    }
3229
3230    // Allow overriding headers with a filter.
3231    $headers = apply_filters( 'wpsc_htaccess_mod_headers', $headers );
3232
3233    // Combine headers into a block of text.
3234    $headers_text = implode(
3235        "\n",
3236        array_map(
3237            function ( $key, $value ) {
3238                return "  Header set $key '" . addcslashes( $value, "'" ) . "'";
3239            },
3240            array_keys( $headers ),
3241            array_values( $headers )
3242        )
3243    );
3244
3245    // Pack headers into gziprules (for historic reasons) - TODO refactor the values
3246    // returned to better reflect the blocks being written.
3247    if ( $headers_text != '' ) {
3248        $gziprules .= "<IfModule mod_headers.c>\n$headers_text\n</IfModule>\n";
3249    }
3250
3251    // Deafult mod_expires rules.
3252    $expires_rules = array(
3253        'ExpiresActive On',
3254        'ExpiresByType text/html A3',
3255    );
3256
3257    // Allow overriding mod_expires rules with a filter.
3258    $expires_rules = apply_filters( 'wpsc_htaccess_mod_expires', $expires_rules );
3259
3260    $gziprules .= "<IfModule mod_expires.c>\n";
3261    $gziprules .= implode(
3262        "\n",
3263        array_map(
3264            function ( $line ) {
3265                return "  $line";
3266            },
3267            $expires_rules
3268        )
3269    );
3270    $gziprules .= "\n</IfModule>\n";
3271
3272    $gziprules .= "Options -Indexes\n";
3273
3274    return array(
3275        'document_root'   => $document_root,
3276        'apache_root'     => $apache_root,
3277        'home_path'       => $home_path,
3278        'home_root'       => $home_root,
3279        'home_root_lc'    => $home_root_lc,
3280        'inst_root'       => $inst_root,
3281        'wprules'         => $wprules,
3282        'scrules'         => $scrules,
3283        'condition_rules' => $condition_rules,
3284        'rules'           => $rules,
3285        'gziprules'       => $gziprules,
3286    );
3287}
3288
3289function clear_post_supercache( $post_id ) {
3290    $dir = get_current_url_supercache_dir( $post_id );
3291    if ( false == @is_dir( $dir ) )
3292        return false;
3293
3294    if ( get_supercache_dir() == $dir ) {
3295        wp_cache_debug( "clear_post_supercache: not deleting post_id $post_id as it points at homepage: $dir" );
3296        return false;
3297    }
3298
3299    wp_cache_debug( "clear_post_supercache: post_id: $post_id. deleting files in $dir" );
3300    if ( get_post_type( $post_id ) != 'page') { // don't delete child pages if they exist
3301        prune_super_cache( $dir, true );
3302    } else {
3303        wpsc_delete_files( $dir );
3304    }
3305}
3306
3307/**
3308 * Serves an AJAX endpoint to return the current state of the preload process.
3309 */
3310function wpsc_ajax_get_preload_status() {
3311    $preload_status = wpsc_get_preload_status( true );
3312    wp_send_json_success( $preload_status, null, JSON_UNESCAPED_SLASHES );
3313}
3314add_action( 'wp_ajax_wpsc_get_preload_status', 'wpsc_ajax_get_preload_status' );
3315
3316/**
3317 * Returns the location of the preload status file.
3318 */
3319function wpsc_get_preload_status_file_path() {
3320    global $cache_path;
3321    return $cache_path . 'preload_permalink.txt';
3322}
3323
3324/**
3325 * Get the timestamp of the next preload.
3326 */
3327function wpsc_get_next_preload_time() {
3328    $next = wp_next_scheduled( 'wp_cache_preload_hook' );
3329    if ( ! $next ) {
3330        $next = wp_next_scheduled( 'wp_cache_full_preload_hook' );
3331    }
3332
3333    return $next;
3334}
3335
3336/**
3337 * Read the preload status. Caches the result in a static variable.
3338 */
3339function wpsc_get_preload_status( $include_next = false ) {
3340    $status = array(
3341        'running'  => false,
3342        'history'  => array(),
3343        'next'     => false,
3344        'previous' => null,
3345    );
3346
3347    $filename = wpsc_get_preload_status_file_path();
3348    if ( file_exists( $filename ) ) {
3349        $data = wp_json_file_decode( $filename, array( 'associative' => true ) );
3350        if ( is_array( $data ) ) {
3351            $status = $data;
3352        }
3353    }
3354
3355    if ( $include_next ) {
3356        $status['next'] = wpsc_get_next_preload_time();
3357    }
3358
3359    return $status;
3360}
3361
3362/**
3363 * Update the preload status file during a preload.
3364 */
3365function wpsc_update_active_preload( $group = null, $progress = null, $url = null ) {
3366    $preload_status = wpsc_get_preload_status();
3367
3368    $preload_status['running'] = true;
3369
3370    // Add the new entry to the history.
3371    array_unshift(
3372        $preload_status['history'],
3373        array(
3374            'group'    => $group,
3375            'progress' => $progress,
3376            'url'      => $url,
3377        )
3378    );
3379
3380    // Limit to 5 in the history.
3381    $preload_status['history'] = array_slice( $preload_status['history'], 0, 5 );
3382
3383    $filename = wpsc_get_preload_status_file_path();
3384    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
3385    if ( false === file_put_contents( $filename, wp_json_encode( $preload_status, JSON_UNESCAPED_SLASHES ) ) ) {
3386        wp_cache_debug( "wpsc_update_active_preload: failed to write to $filename" );
3387    }
3388}
3389
3390/**
3391 * Update the preload status to indicate it is idle. If a finish time is specified, store it.
3392 */
3393function wpsc_update_idle_preload( $finish_time = null ) {
3394    $preload_status = wpsc_get_preload_status();
3395
3396    $preload_status['running'] = false;
3397    $preload_status['history'] = array();
3398
3399    if ( ! empty( $finish_time ) ) {
3400        $preload_status['previous'] = $finish_time;
3401    }
3402
3403    $filename = wpsc_get_preload_status_file_path();
3404    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
3405    if ( false === file_put_contents( $filename, wp_json_encode( $preload_status, JSON_UNESCAPED_SLASHES ) ) ) {
3406        wp_cache_debug( "wpsc_update_idle_preload: failed to write to $filename" );
3407    }
3408}
3409
3410function wp_cron_preload_cache() {
3411    global $wpdb, $wp_cache_preload_interval, $wp_cache_preload_posts, $wp_cache_preload_email_me, $wp_cache_preload_email_volume, $cache_path, $wp_cache_preload_taxonomies;
3412
3413    // check if stop_preload.txt exists and preload should be stopped.
3414    // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
3415    if ( @file_exists( $cache_path . 'stop_preload.txt' ) ) {
3416        wp_cache_debug( 'wp_cron_preload_cache: preload cancelled. Aborting preload.' );
3417        wpsc_reset_preload_settings();
3418        return true;
3419    }
3420
3421    /*
3422     * The mutex file is used to prevent multiple preload processes from running at the same time.
3423     * If the mutex file is found, the preload process will wait 3-8 seconds and then check again.
3424     * If the mutex file is still found, the preload process will abort.
3425     * If the mutex file is not found, the preload process will create the mutex file and continue.
3426     * The mutex file is deleted at the end of the preload process.
3427     * The mutex file is deleted if it is more than 10 minutes old.
3428     * The mutex file should only be deleted by the preload process that created it.
3429     * If the mutex file is deleted by another process, another preload process may start.
3430     */
3431    $mutex = $cache_path . "preload_mutex.tmp";
3432    if ( @file_exists( $mutex ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
3433        sleep( 3 + wp_rand( 1, 5 ) );
3434        // check again just in case another preload process is still running.
3435        if ( @file_exists( $mutex ) && @filemtime( $mutex ) > ( time() - 600 ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
3436            wp_cache_debug( 'wp_cron_preload_cache: preload mutex found and less than 600 seconds old. Aborting preload.', 1 );
3437            return true;
3438        } else {
3439            wp_cache_debug( 'wp_cron_preload_cache: old preload mutex found and deleted. Preload continues.', 1 );
3440            @unlink( $mutex );
3441        }
3442    }
3443    $fp = @fopen( $mutex, 'w' );
3444    @fclose( $fp );
3445
3446    $counter = get_option( 'preload_cache_counter' );
3447    $c = $counter[ 'c' ];
3448
3449    if ( $wp_cache_preload_email_volume == 'none' && $wp_cache_preload_email_me == 1 ) {
3450        $wp_cache_preload_email_me = 0;
3451        wp_cache_setting( 'wp_cache_preload_email_me', 0 );
3452    }
3453
3454    $just_started_preloading = false;
3455
3456    /*
3457     * Preload taxonomies first.
3458     *
3459     */
3460    if ( isset( $wp_cache_preload_taxonomies ) && $wp_cache_preload_taxonomies ) {
3461        wp_cache_debug( 'wp_cron_preload_cache: doing taxonomy preload.', 5 );
3462        $taxonomies = apply_filters(
3463            'wp_cache_preload_taxonomies',
3464            array(
3465                'post_tag' => 'tag',
3466                'category' => 'category',
3467            )
3468        );
3469
3470        $preload_more_taxonomies = false;
3471
3472        foreach ( $taxonomies as $taxonomy => $path ) {
3473            $taxonomy_filename = $cache_path . 'taxonomy_' . $taxonomy . '.txt';
3474
3475            // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
3476            if ( false === @file_exists( $taxonomy_filename ) ) {
3477
3478                if ( ! $just_started_preloading && $wp_cache_preload_email_me ) {
3479                    // translators: 1: site url
3480                    wp_mail( get_option( 'admin_email' ), sprintf( __( '[%1$s] Cache Preload Started', 'wp-super-cache' ), home_url(), '' ), ' ' );
3481                }
3482
3483                $just_started_preloading = true;
3484                $out                     = '';
3485                $records                 = get_terms( $taxonomy );
3486                foreach ( $records as $term ) {
3487                    $out .= get_term_link( $term ) . "\n";
3488                }
3489                // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen
3490                $fp = fopen( $taxonomy_filename, 'w' );
3491                if ( $fp ) {
3492                    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite
3493                    fwrite( $fp, $out );
3494                    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
3495                    fclose( $fp );
3496                }
3497                $details = explode( "\n", $out );
3498            } else {
3499                // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
3500                $details = explode( "\n", file_get_contents( $taxonomy_filename ) );
3501            }
3502            if ( count( $details ) > 0 && $details[0] !== '' ) {
3503                $rows = array_splice( $details, 0, WPSC_PRELOAD_POST_COUNT );
3504                if ( $wp_cache_preload_email_me && $wp_cache_preload_email_volume === 'many' ) {
3505                    // translators: 1: Site URL, 2: Taxonomy name, 3: Number of posts done, 4: Number of posts to preload
3506                    wp_mail( get_option( 'admin_email' ), sprintf( __( '[%1$s] Refreshing %2$s taxonomy from %3$d to %4$d', 'wp-super-cache' ), home_url(), $taxonomy, $c, ( $c + WPSC_PRELOAD_POST_COUNT ) ), 'Refreshing: ' . print_r( $rows, 1 ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
3507                }
3508
3509                foreach ( $rows as $url ) {
3510                    set_time_limit( 60 );
3511                    if ( $url === '' ) {
3512                        continue;
3513                    }
3514
3515                    $url_info = wp_parse_url( $url );
3516                    $dir      = get_supercache_dir() . $url_info['path'];
3517                    wp_cache_debug( "wp_cron_preload_cache: delete $dir" );
3518                    wpsc_delete_files( $dir );
3519                    prune_super_cache( trailingslashit( $dir ) . 'feed/', true );
3520                    prune_super_cache( trailingslashit( $dir ) . 'page/', true );
3521
3522                    wpsc_update_active_preload( 'taxonomies', $taxonomy, $url );
3523
3524                    wp_remote_get(
3525                        $url,
3526                        array(
3527                            'timeout'  => 60,
3528                            'blocking' => true,
3529                        )
3530                    );
3531                    wp_cache_debug( "wp_cron_preload_cache: fetched $url" );
3532                    sleep( WPSC_PRELOAD_POST_INTERVAL );
3533
3534                    if ( ! wpsc_is_preload_active() ) {
3535                        wp_cache_debug( 'wp_cron_preload_cache: cancelling preload process.' );
3536                        wpsc_reset_preload_settings();
3537
3538                        if ( $wp_cache_preload_email_me ) {
3539                            // translators: Home URL of website
3540                            wp_mail( get_option( 'admin_email' ), sprintf( __( '[%1$s] Cache Preload Stopped', 'wp-super-cache' ), home_url(), '' ), ' ' );
3541                        }
3542                        wpsc_update_idle_preload( time() );
3543                        return true;
3544                    }
3545                }
3546                // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen
3547                $fp = fopen( $taxonomy_filename, 'w' );
3548                if ( $fp ) {
3549                    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fwrite
3550                    fwrite( $fp, implode( "\n", $details ) );
3551                    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
3552                    fclose( $fp );
3553                }
3554            }
3555
3556            if (
3557                $preload_more_taxonomies === false &&
3558                count( $details ) > 0 &&
3559                $details[0] !== ''
3560            ) {
3561                $preload_more_taxonomies = true;
3562            }
3563        }
3564
3565        if ( $preload_more_taxonomies === true ) {
3566            wpsc_schedule_next_preload();
3567            sleep( WPSC_PRELOAD_LOOP_INTERVAL );
3568            return true;
3569        }
3570    } elseif ( $c === 0 && $wp_cache_preload_email_me ) {
3571        // translators: Home URL of website
3572        wp_mail( get_option( 'admin_email' ), sprintf( __( '[%1$s] Cache Preload Started', 'wp-super-cache' ), home_url(), '' ), ' ' );
3573    }
3574
3575    /*
3576     *
3577     * Preload posts now.
3578     *
3579     * The preload_cache_counter has two values:
3580     * c = the number of posts we've preloaded after this loop.
3581     * t = the time we started preloading in the current loop.
3582     *
3583     * $c is set to the value of preload_cache_counter['c'] at the start of the function
3584     * before it is incremented by WPSC_PRELOAD_POST_COUNT here.
3585     * The time is used to check if preloading has stalled in check_up_on_preloading().
3586     */
3587
3588    update_option(
3589        'preload_cache_counter',
3590        array(
3591            'c' => ( $c + WPSC_PRELOAD_POST_COUNT ),
3592            't' => time(),
3593        )
3594    );
3595
3596    if ( $wp_cache_preload_posts == 'all' || $c < $wp_cache_preload_posts ) {
3597        $types = wpsc_get_post_types();
3598        $posts = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE ( post_type IN ( $types ) ) AND post_status = 'publish' ORDER BY ID DESC LIMIT %d," . WPSC_PRELOAD_POST_COUNT, $c ) ); // phpcs:ignore
3599        wp_cache_debug( 'wp_cron_preload_cache: got ' . WPSC_PRELOAD_POST_COUNT . ' posts from position ' . $c );
3600    } else {
3601        wp_cache_debug( "wp_cron_preload_cache: no more posts to get. Limit ($wp_cache_preload_posts) reached.", 5 );
3602        $posts = false;
3603    }
3604    if ( !isset( $wp_cache_preload_email_volume ) )
3605        $wp_cache_preload_email_volume = 'medium';
3606
3607    if ( $posts ) {
3608        if ( get_option( 'show_on_front' ) == 'page' ) {
3609            $page_on_front = get_option( 'page_on_front' );
3610            $page_for_posts = get_option( 'page_for_posts' );
3611        } else {
3612            $page_on_front = $page_for_posts = 0;
3613        }
3614        if ( $wp_cache_preload_email_me && $wp_cache_preload_email_volume === 'many' ) {
3615            /* translators: 1: home url, 2: start post id, 3: end post id */
3616            wp_mail( get_option( 'admin_email' ), sprintf( __( '[%1$s] Refreshing posts from %2$d to %3$d', 'wp-super-cache' ), home_url(), $c, ( $c + WPSC_PRELOAD_POST_COUNT ) ), ' ' );
3617        }
3618        $msg = '';
3619        $count = $c + 1;
3620
3621        foreach( $posts as $post_id ) {
3622            set_time_limit( 60 );
3623            if ( $page_on_front != 0 && ( $post_id == $page_on_front || $post_id == $page_for_posts ) )
3624                continue;
3625            $url = get_permalink( $post_id );
3626
3627            if ( ! is_string( $url ) ) {
3628                    wp_cache_debug( "wp_cron_preload_cache: skipped $post_id. Expected a URL, received: " . gettype( $url ) );
3629                    continue;
3630            }
3631
3632            if ( wp_cache_is_rejected( $url ) ) {
3633                wp_cache_debug( "wp_cron_preload_cache: skipped $url per rejected strings setting" );
3634                continue;
3635            }
3636            clear_post_supercache( $post_id );
3637
3638            wpsc_update_active_preload( 'posts', $count, $url );
3639
3640            if ( ! wpsc_is_preload_active() ) {
3641                wp_cache_debug( 'wp_cron_preload_cache: cancelling preload process.' );
3642                wpsc_reset_preload_settings();
3643
3644                if ( $wp_cache_preload_email_me ) {
3645                    // translators: Home URL of website
3646                    wp_mail( get_option( 'admin_email' ), sprintf( __( '[%1$s] Cache Preload Stopped', 'wp-super-cache' ), home_url(), '' ), ' ' );
3647                }
3648
3649                wpsc_update_idle_preload( time() );
3650                return true;
3651            }
3652
3653            $msg .= "$url\n";
3654            wp_remote_get( $url, array('timeout' => 60, 'blocking' => true ) );
3655            wp_cache_debug( "wp_cron_preload_cache: fetched $url", 5 );
3656            ++$count;
3657            sleep( WPSC_PRELOAD_POST_INTERVAL );
3658        }
3659
3660        if ( $wp_cache_preload_email_me && ( $wp_cache_preload_email_volume === 'medium' || $wp_cache_preload_email_volume === 'many' ) ) {
3661            // translators: 1: home url, 2: number of posts refreshed
3662            wp_mail( get_option( 'admin_email' ), sprintf( __( '[%1$s] %2$d posts refreshed', 'wp-super-cache' ), home_url(), ( $c + WPSC_PRELOAD_POST_COUNT ) ), __( 'Refreshed the following posts:', 'wp-super-cache' ) . "\n$msg" );
3663        }
3664
3665        wpsc_schedule_next_preload();
3666        wpsc_delete_files( get_supercache_dir() );
3667        sleep( WPSC_PRELOAD_LOOP_INTERVAL );
3668    } else {
3669        $msg = '';
3670        wpsc_reset_preload_counter();
3671        if ( (int)$wp_cache_preload_interval && defined( 'DOING_CRON' ) ) {
3672            if ( $wp_cache_preload_email_me )
3673                $msg = sprintf( __( 'Scheduling next preload refresh in %d minutes.', 'wp-super-cache' ), (int)$wp_cache_preload_interval );
3674            wp_cache_debug( "wp_cron_preload_cache: no more posts. scheduling next preload in $wp_cache_preload_interval minutes.", 5 );
3675            wp_schedule_single_event( time() + ( (int)$wp_cache_preload_interval * 60 ), 'wp_cache_full_preload_hook' );
3676        }
3677        global $file_prefix, $cache_max_time;
3678        if ( $wp_cache_preload_interval > 0 ) {
3679            $cache_max_time = (int)$wp_cache_preload_interval * 60; // fool the GC into expiring really old files
3680        } else {
3681            $cache_max_time = 86400; // fool the GC into expiring really old files
3682        }
3683        if ( $wp_cache_preload_email_me )
3684            wp_mail( get_option( 'admin_email' ), sprintf( __( '[%s] Cache Preload Completed', 'wp-super-cache' ), home_url() ), __( "Cleaning up old supercache files.", 'wp-super-cache' ) . "\n" . $msg );
3685        if ( $cache_max_time > 0 ) { // GC is NOT disabled
3686            wp_cache_debug( "wp_cron_preload_cache: clean expired cache files older than $cache_max_time seconds.", 5 );
3687            wp_cache_phase2_clean_expired( $file_prefix, true ); // force cleanup of old files.
3688        }
3689
3690        wpsc_reset_preload_settings();
3691        wpsc_update_idle_preload( time() );
3692    }
3693    @unlink( $mutex );
3694}
3695add_action( 'wp_cache_preload_hook', 'wp_cron_preload_cache' );
3696add_action( 'wp_cache_full_preload_hook', 'wp_cron_preload_cache' );
3697
3698/*
3699 * Schedule the next preload event without resetting the preload counter.
3700 * This happens when the next loop of an active preload is scheduled.
3701 */
3702function wpsc_schedule_next_preload() {
3703    global $cache_path;
3704
3705    /*
3706     * Edge case: If preload is not active, don't schedule the next preload.
3707     * This can happen if the preload is cancelled by the user right after a loop finishes.
3708     */
3709    if ( ! wpsc_is_preload_active() ) {
3710        wpsc_reset_preload_settings();
3711        wp_cache_debug( 'wpsc_schedule_next_preload: preload is not active. not scheduling next preload.' );
3712        return;
3713    }
3714
3715    if ( defined( 'DOING_CRON' ) ) {
3716        wp_cache_debug( 'wp_cron_preload_cache: scheduling the next preload in 3 seconds.' );
3717        wp_schedule_single_event( time() + 3, 'wp_cache_preload_hook' );
3718    }
3719
3720    // we always want to delete the mutex file, even if we're not using cron
3721    $mutex = $cache_path . 'preload_mutex.tmp';
3722    wp_delete_file( $mutex );
3723}
3724
3725function option_preload_cache_counter( $value ) {
3726    if ( false == is_array( $value ) ) {
3727        return array(
3728            'c' => 0,
3729            't' => time(),
3730        );
3731    } else {
3732        return $value;
3733    }
3734}
3735add_filter( 'option_preload_cache_counter', 'option_preload_cache_counter' );
3736
3737function check_up_on_preloading() {
3738    $value = get_option( 'preload_cache_counter' );
3739    if ( is_array( $value ) && $value['c'] > 0 && ( time() - $value['t'] ) > 3600 && false === wp_next_scheduled( 'wp_cache_preload_hook' ) ) {
3740        wp_schedule_single_event( time() + 5, 'wp_cache_preload_hook' );
3741    }
3742}
3743add_action( 'init', 'check_up_on_preloading' ); // sometimes preloading stops working. Kickstart it.
3744
3745function wp_cache_disable_plugin( $delete_config_file = true ) {
3746    global $wp_rewrite;
3747    if ( file_exists( ABSPATH . 'wp-config.php') ) {
3748        $global_config_file = ABSPATH . 'wp-config.php';
3749    } else {
3750        $global_config_file = dirname(ABSPATH) . '/wp-config.php';
3751    }
3752
3753    if ( apply_filters( 'wpsc_enable_wp_config_edit', true ) ) {
3754        $line = 'define(\'WP_CACHE\', true);';
3755        if (
3756            strpos( file_get_contents( $global_config_file ), $line ) &&
3757            (
3758                ! is_writeable_ACLSafe( $global_config_file ) ||
3759                ! wp_cache_replace_line( 'define*\(*\'WP_CACHE\'', '', $global_config_file )
3760            )
3761        ) {
3762            wp_die( "Could not remove WP_CACHE define from $global_config_file. Please edit that file and remove the line containing the text 'WP_CACHE'. Then refresh this page." );
3763        }
3764        $line = 'define( \'WPCACHEHOME\',';
3765        if (
3766            strpos( file_get_contents( $global_config_file ), $line ) &&
3767            (
3768                ! is_writeable_ACLSafe( $global_config_file ) ||
3769                ! wp_cache_replace_line( 'define *\( *\'WPCACHEHOME\'', '', $global_config_file )
3770            )
3771        ) {
3772            wp_die( "Could not remove WPCACHEHOME define from $global_config_file. Please edit that file and remove the line containing the text 'WPCACHEHOME'. Then refresh this page." );
3773        }
3774    } elseif ( function_exists( 'wp_cache_debug' ) ) {
3775        wp_cache_debug( 'wp_cache_disable_plugin: not allowed to edit wp-config.php per configuration.' );
3776    }
3777
3778    uninstall_supercache( WP_CONTENT_DIR . '/cache' );
3779    $file_not_deleted = array();
3780    wpsc_remove_advanced_cache();
3781    if ( @file_exists( WP_CONTENT_DIR . "/advanced-cache.php" ) ) {
3782        $file_not_deleted[] = WP_CONTENT_DIR . '/advanced-cache.php';
3783    }
3784    if ( $delete_config_file && @file_exists( WPCACHECONFIGPATH . "/wp-cache-config.php" ) ) {
3785        if ( false == unlink( WPCACHECONFIGPATH . "/wp-cache-config.php" ) )
3786            $file_not_deleted[] = WPCACHECONFIGPATH . '/wp-cache-config.php';
3787    }
3788    if ( ! empty( $file_not_deleted ) ) {
3789        $msg = __( "Dear User,\n\nWP Super Cache was removed from your blog or deactivated but some files could\nnot be deleted.\n\n", 'wp-super-cache' );
3790        foreach ( $file_not_deleted as $path ) {
3791            $msg .=  "{$path}\n";
3792        }
3793        $msg .= "\n";
3794        $msg .= sprintf( __( "You should delete these files manually.\nYou may need to change the permissions of the files or parent directory.\nYou can read more about this in the Codex at\n%s\n\nThank you.", 'wp-super-cache' ), 'https://codex.wordpress.org/Changing_File_Permissions#About_Chmod' );
3795
3796        if ( apply_filters( 'wpsc_send_uninstall_errors', 1 ) ) {
3797            wp_mail( get_option( 'admin_email' ), __( 'WP Super Cache: could not delete files', 'wp-super-cache' ), $msg );
3798        }
3799    }
3800    extract( wpsc_get_htaccess_info() ); // $document_root, $apache_root, $home_path, $home_root, $home_root_lc, $inst_root, $wprules, $scrules, $condition_rules, $rules, $gziprules
3801    // @phan-suppress-next-line PhanTypeSuspiciousStringExpression -- $home_path is set via extract()
3802    if ( $scrules != '' && insert_with_markers( $home_path.'.htaccess', 'WPSuperCache', array() ) ) {
3803        $wp_rewrite->flush_rules();
3804    } elseif( $scrules != '' ) {
3805        wp_mail( get_option( 'admin_email' ), __( 'Supercache Uninstall Problems', 'wp-super-cache' ), sprintf( __( "Dear User,\n\nWP Super Cache was removed from your blog but the mod_rewrite rules\nin your .htaccess were not.\n\nPlease edit the following file and remove the code\nbetween 'BEGIN WPSuperCache' and 'END WPSuperCache'. Please backup the file first!\n\n%s\n\nRegards,\nWP Super Cache Plugin\nhttps://wordpress.org/plugins/wp-super-cache/", 'wp-super-cache' ), ABSPATH . '/.htaccess' ) );
3806    }
3807}
3808
3809function uninstall_supercache( $folderPath ) { // from http://www.php.net/manual/en/function.rmdir.php
3810    if ( trailingslashit( constant( 'ABSPATH' ) ) == trailingslashit( $folderPath ) )
3811        return false;
3812    if ( @is_dir ( $folderPath ) ) {
3813        $dh  = @opendir($folderPath);
3814        while( false !== ( $value = @readdir( $dh ) ) ) {
3815            if ( $value != "." && $value != ".." ) {
3816                $value = $folderPath . "/" . $value;
3817                if ( @is_dir ( $value ) ) {
3818                    uninstall_supercache( $value );
3819                } else {
3820                    @unlink( $value );
3821                }
3822            }
3823        }
3824        return @rmdir( $folderPath );
3825    } else {
3826        return false;
3827    }
3828}
3829
3830function supercache_admin_bar_render() {
3831    global $wp_admin_bar;
3832
3833    if ( function_exists( '_deprecated_function' ) ) {
3834        _deprecated_function( __FUNCTION__, 'WP Super Cache 1.6.4' );
3835    }
3836
3837    wpsc_admin_bar_render( $wp_admin_bar );
3838}
3839
3840/*
3841 * returns true if preload is active
3842 */
3843function wpsc_is_preload_active() {
3844    global $cache_path;
3845
3846    // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
3847    if ( @file_exists( $cache_path . 'stop_preload.txt' ) ) {
3848        return false;
3849    }
3850
3851    if ( file_exists( $cache_path . 'preload_mutex.tmp' ) ) {
3852        return true;
3853    }
3854
3855    // check taxonomy preload loop
3856    $taxonomies = apply_filters(
3857        'wp_cache_preload_taxonomies',
3858        array(
3859            'post_tag' => 'tag',
3860            'category' => 'category',
3861        )
3862    );
3863
3864    foreach ( $taxonomies as $taxonomy => $path ) {
3865        $taxonomy_filename = $cache_path . 'taxonomy_' . $taxonomy . '.txt';
3866        if ( file_exists( $taxonomy_filename ) ) {
3867            return true;
3868        }
3869    }
3870
3871    // check post preload loop
3872    $preload_cache_counter = get_option( 'preload_cache_counter' );
3873    if (
3874        is_array( $preload_cache_counter )
3875        && isset( $preload_cache_counter['c'] )
3876        && $preload_cache_counter['c'] > 0
3877    ) {
3878        return true;
3879    }
3880
3881    return false;
3882}
3883
3884/*
3885 * This function will reset the preload cache counter
3886 */
3887function wpsc_reset_preload_counter() {
3888    update_option(
3889        'preload_cache_counter',
3890        array(
3891            'c' => 0,
3892            't' => time(),
3893        )
3894    );
3895}
3896
3897/*
3898 * This function will reset all preload settings
3899 */
3900function wpsc_reset_preload_settings() {
3901    global $cache_path;
3902
3903    $mutex = $cache_path . 'preload_mutex.tmp';
3904    wp_delete_file( $mutex );
3905    wp_delete_file( $cache_path . 'stop_preload.txt' );
3906    wpsc_reset_preload_counter();
3907
3908    $taxonomies = apply_filters(
3909        'wp_cache_preload_taxonomies',
3910        array(
3911            'post_tag' => 'tag',
3912            'category' => 'category',
3913        )
3914    );
3915
3916    foreach ( $taxonomies as $taxonomy => $path ) {
3917        $taxonomy_filename = $cache_path . 'taxonomy_' . $taxonomy . '.txt';
3918        wp_delete_file( $taxonomy_filename );
3919    }
3920}
3921
3922function wpsc_cancel_preload() {
3923    $next_preload      = wp_next_scheduled( 'wp_cache_preload_hook' );
3924    $next_full_preload = wp_next_scheduled( 'wp_cache_full_preload_hook' );
3925
3926    if ( $next_preload || $next_full_preload ) {
3927        wp_cache_debug( 'wpsc_cancel_preload: reset preload settings' );
3928        wpsc_reset_preload_settings();
3929    }
3930
3931    if ( $next_preload ) {
3932        wp_cache_debug( 'wpsc_cancel_preload: unscheduling wp_cache_preload_hook' );
3933        wp_unschedule_event( $next_preload, 'wp_cache_preload_hook' );
3934    }
3935    if ( $next_full_preload ) {
3936        wp_cache_debug( 'wpsc_cancel_preload: unscheduling wp_cache_full_preload_hook' );
3937        wp_unschedule_event( $next_full_preload, 'wp_cache_full_preload_hook' );
3938    }
3939    wp_cache_debug( 'wpsc_cancel_preload: creating stop_preload.txt' );
3940
3941    /*
3942    * Reset the preload settings, but also create the stop_preload.txt file to
3943    * prevent the preload from starting again.
3944    * By creating the stop_preload.txt file, we can be sure the preload will cancel.
3945    */
3946    wpsc_reset_preload_settings();
3947    wpsc_create_stop_preload_flag();
3948    wpsc_update_idle_preload( time() );
3949}
3950
3951/*
3952 * The preload process checks for a file called stop_preload.txt and will stop if found.
3953 * This function creates that file.
3954 */
3955function wpsc_create_stop_preload_flag() {
3956    global $cache_path;
3957    // phpcs:ignore -- WordPress.WP.AlternativeFunctions.file_system_read_fopen WordPress.PHP.NoSilencedErrors.Discouraged
3958    $fp = @fopen( $cache_path . 'stop_preload.txt', 'w' );
3959    // phpcs:ignore -- WordPress.WP.AlternativeFunctions.file_system_operations_fclose WordPress.PHP.NoSilencedErrors.Discouraged
3960    @fclose( $fp );
3961}
3962
3963function wpsc_enable_preload() {
3964
3965    wpsc_reset_preload_settings();
3966    wp_schedule_single_event( time() + 10, 'wp_cache_full_preload_hook' );
3967}
3968
3969function wpsc_get_post_types() {
3970
3971    $preload_type_args = apply_filters( 'wpsc_preload_post_types_args', array(
3972        'public'             => true,
3973        'publicly_queryable' => true
3974    ) );
3975
3976    $post_types = (array) apply_filters( 'wpsc_preload_post_types', get_post_types( $preload_type_args, 'names', 'or' ));
3977
3978    return "'" . implode( "', '", array_map( 'esc_sql', $post_types ) ) . "'";
3979}
3980function wpsc_post_count() {
3981    global $wpdb;
3982    static $count;
3983
3984    if ( isset( $count ) ) {
3985        return $count;
3986    }
3987
3988    $post_type_list = wpsc_get_post_types();
3989    $count = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type IN ( $post_type_list ) AND post_status = 'publish'" );
3990
3991    return $count;
3992}
3993
3994/**
3995 * Get the minimum interval in minutes between preload refreshes.
3996 * Filter the default value of 10 minutes using the `wpsc_minimum_preload_interval` filter.
3997 *
3998 * @return int
3999 */
4000function wpsc_get_minimum_preload_interval() {
4001    return apply_filters( 'wpsc_minimum_preload_interval', 10 );
4002}
4003
4004function wpsc_preload_settings() {
4005    global $wp_cache_preload_interval, $wp_cache_preload_on, $wp_cache_preload_taxonomies, $wp_cache_preload_email_me, $wp_cache_preload_email_volume, $wp_cache_preload_posts, $wpdb;
4006
4007    if ( isset( $_POST[ 'action' ] ) == false || $_POST[ 'action' ] != 'preload' )
4008        return;
4009
4010    if ( isset( $_POST[ 'preload_off' ] ) ) {
4011        wpsc_cancel_preload();
4012        return;
4013    } elseif ( isset( $_POST[ 'preload_now' ] ) ) {
4014        wpsc_enable_preload();
4015        wpsc_update_idle_preload();
4016        ?>
4017        <div class="notice notice-warning">
4018            <h4><?php esc_html_e( 'Preload has been activated', 'wp-super-cache' ); ?></h4>
4019        </div>
4020        <?php
4021        return;
4022    }
4023
4024    $min_refresh_interval = wpsc_get_minimum_preload_interval();
4025
4026    // Set to true if the preload interval is changed, and a reschedule is required.
4027    $force_preload_reschedule = false;
4028
4029    if ( isset( $_POST[ 'wp_cache_preload_interval' ] ) && ( $_POST[ 'wp_cache_preload_interval' ] == 0 || $_POST[ 'wp_cache_preload_interval' ] >= $min_refresh_interval ) ) {
4030        $_POST[ 'wp_cache_preload_interval' ] = (int)$_POST[ 'wp_cache_preload_interval' ];
4031        if ( $wp_cache_preload_interval != $_POST[ 'wp_cache_preload_interval' ] ) {
4032            $force_preload_reschedule = true;
4033        }
4034
4035        // phpcs:ignore WordPress.Security.NonceVerification.Missing
4036        $wp_cache_preload_interval = (int) $_POST['wp_cache_preload_interval'];
4037        wp_cache_setting( 'wp_cache_preload_interval', $wp_cache_preload_interval );
4038    }
4039
4040    if ( $_POST[ 'wp_cache_preload_posts' ] == 'all' ) {
4041        $wp_cache_preload_posts = 'all';
4042    } else {
4043        $wp_cache_preload_posts = (int)$_POST[ 'wp_cache_preload_posts' ];
4044    }
4045    wp_cache_setting( 'wp_cache_preload_posts', $wp_cache_preload_posts );
4046
4047    if ( isset( $_POST[ 'wp_cache_preload_email_volume' ] ) && in_array( $_POST[ 'wp_cache_preload_email_volume' ], array( 'none', 'less', 'medium', 'many' ) ) ) {
4048        $wp_cache_preload_email_volume = $_POST[ 'wp_cache_preload_email_volume' ];
4049    } else {
4050        $wp_cache_preload_email_volume = 'none';
4051    }
4052    wp_cache_setting( 'wp_cache_preload_email_volume', $wp_cache_preload_email_volume );
4053
4054    if ( $wp_cache_preload_email_volume == 'none' )
4055        wp_cache_setting( 'wp_cache_preload_email_me', 0 );
4056    else
4057        wp_cache_setting( 'wp_cache_preload_email_me', 1 );
4058
4059    if ( isset( $_POST[ 'wp_cache_preload_taxonomies' ] ) ) {
4060        $wp_cache_preload_taxonomies = 1;
4061    } else {
4062        $wp_cache_preload_taxonomies = 0;
4063    }
4064    wp_cache_setting( 'wp_cache_preload_taxonomies', $wp_cache_preload_taxonomies );
4065
4066    if ( isset( $_POST[ 'wp_cache_preload_on' ] ) ) {
4067        $wp_cache_preload_on = 1;
4068    } else {
4069        $wp_cache_preload_on = 0;
4070    }
4071    wp_cache_setting( 'wp_cache_preload_on', $wp_cache_preload_on );
4072
4073    // Ensure that preload settings are applied to scheduled cron.
4074    $next_preload    = wp_next_scheduled( 'wp_cache_full_preload_hook' );
4075    $should_schedule = ( $wp_cache_preload_on === 1 && $wp_cache_preload_interval > 0 );
4076
4077    // If forcing a reschedule, or preload is disabled, clear the next scheduled event.
4078    if ( $next_preload && ( ! $should_schedule || $force_preload_reschedule ) ) {
4079        wp_cache_debug( 'Clearing old preload event' );
4080        wpsc_reset_preload_counter();
4081        wpsc_create_stop_preload_flag();
4082        wp_unschedule_event( $next_preload, 'wp_cache_full_preload_hook' );
4083
4084        $next_preload = 0;
4085    }
4086
4087    // Ensure a preload is scheduled if it should be.
4088    if ( ! $next_preload && $should_schedule ) {
4089        wp_cache_debug( 'Scheduling new preload event' );
4090        wp_schedule_single_event( time() + ( $wp_cache_preload_interval * 60 ), 'wp_cache_full_preload_hook' );
4091    }
4092}
4093
4094function wpsc_is_preloading() {
4095    if ( wp_next_scheduled( 'wp_cache_preload_hook' ) || wp_next_scheduled( 'wp_cache_full_preload_hook' ) ) {
4096        return true;
4097    } else {
4098        return false;
4099    }
4100}
4101
4102function wpsc_set_default_gc( $force = false ) {
4103    global $cache_path, $wp_cache_shutdown_gc, $cache_schedule_type;
4104
4105    if ( isset( $wp_cache_shutdown_gc ) && $wp_cache_shutdown_gc == 1 ) {
4106        return false;
4107    }
4108
4109    if ( $force ) {
4110        unset( $cache_schedule_type );
4111        $timestamp = wp_next_scheduled( 'wp_cache_gc' );
4112        if ( $timestamp ) {
4113            wp_unschedule_event( $timestamp, 'wp_cache_gc' );
4114        }
4115    }
4116
4117    // set up garbage collection with some default settings
4118    if ( false == isset( $cache_schedule_type ) && false == wp_next_scheduled( 'wp_cache_gc' ) ) {
4119        $cache_schedule_type     = 'interval';
4120        $cache_time_interval     = 600;
4121        $cache_max_time          = 1800;
4122        $cache_schedule_interval = 'hourly';
4123        $cache_gc_email_me       = 0;
4124        wp_cache_setting( 'cache_schedule_type', $cache_schedule_type );
4125        wp_cache_setting( 'cache_time_interval', $cache_time_interval );
4126        wp_cache_setting( 'cache_max_time', $cache_max_time );
4127        wp_cache_setting( 'cache_schedule_interval', $cache_schedule_interval );
4128        wp_cache_setting( 'cache_gc_email_me', $cache_gc_email_me );
4129
4130        wp_schedule_single_event( time() + 600, 'wp_cache_gc' );
4131    }
4132
4133    return true;
4134}
4135
4136function add_mod_rewrite_rules() {
4137    return update_mod_rewrite_rules();
4138}
4139
4140function remove_mod_rewrite_rules() {
4141    return update_mod_rewrite_rules( false );
4142}
4143
4144function update_mod_rewrite_rules( $add_rules = true ) {
4145    global $cache_path, $update_mod_rewrite_rules_error;
4146
4147    $update_mod_rewrite_rules_error = false;
4148
4149    if ( defined( "DO_NOT_UPDATE_HTACCESS" ) ) {
4150        $update_mod_rewrite_rules_error = ".htaccess update disabled by admin: DO_NOT_UPDATE_HTACCESS defined";
4151        return false;
4152    }
4153
4154    if ( ! function_exists( 'get_home_path' ) ) {
4155        include_once( ABSPATH . 'wp-admin/includes/file.php' ); // get_home_path()
4156        include_once( ABSPATH . 'wp-admin/includes/misc.php' ); // extract_from_markers()
4157    }
4158    $home_path = trailingslashit( get_home_path() );
4159    $home_root = parse_url( get_bloginfo( 'url' ) );
4160    $home_root = isset( $home_root[ 'path' ] ) ? trailingslashit( $home_root[ 'path' ] ) : '/';
4161    if (
4162        $home_root == '/' &&
4163        $home_path != $_SERVER[ 'DOCUMENT_ROOT' ]
4164    ) {
4165        $home_path = $_SERVER[ 'DOCUMENT_ROOT' ];
4166    } elseif (
4167        $home_root != '/' &&
4168        $home_path != str_replace( '//', '/', $_SERVER[ 'DOCUMENT_ROOT' ] . $home_root ) &&
4169        is_dir( $_SERVER[ 'DOCUMENT_ROOT' ] . $home_root )
4170    ) {
4171        $home_path = str_replace( '//', '/', $_SERVER[ 'DOCUMENT_ROOT' ] . $home_root );
4172    }
4173    $home_path = trailingslashit( $home_path );
4174
4175    if ( ! file_exists( $home_path . ".htaccess" ) ) {
4176        $update_mod_rewrite_rules_error = ".htaccess not found: {$home_path}.htaccess";
4177        return false;
4178    }
4179
4180    $generated_rules = wpsc_get_htaccess_info();
4181    $existing_rules  = implode( "\n", extract_from_markers( $home_path . '.htaccess', 'WPSuperCache' ) );
4182
4183    $rules = $add_rules ? $generated_rules[ 'rules' ] : '';
4184
4185    if ( $existing_rules == $rules ) {
4186        $update_mod_rewrite_rules_error = "rules have not changed";
4187        return true;
4188    }
4189
4190    if ( $generated_rules[ 'wprules' ] == '' ) {
4191        $update_mod_rewrite_rules_error = "WordPress rules empty";
4192        return false;
4193    }
4194
4195    if ( empty( $rules ) ) {
4196        return insert_with_markers( $home_path . '.htaccess', 'WPSuperCache', array() );
4197    }
4198
4199    $url = trailingslashit( get_bloginfo( 'url' ) );
4200    $original_page = wp_remote_get( $url, array( 'timeout' => 60, 'blocking' => true ) );
4201    if ( is_wp_error( $original_page ) ) {
4202        $update_mod_rewrite_rules_error = "Problem loading page";
4203        return false;
4204    }
4205
4206    $backup_filename      = $cache_path . 'htaccess.' . wp_rand() . '.php';
4207    $backup_file_contents = file_get_contents( $home_path . '.htaccess' );
4208    file_put_contents( $backup_filename, "<" . "?php die(); ?" . ">" . $backup_file_contents );
4209    $existing_gzip_rules = implode( "\n", extract_from_markers( $cache_path . '.htaccess', 'supercache' ) );
4210    if ( $existing_gzip_rules != $generated_rules[ 'gziprules' ] ) {
4211        insert_with_markers( $cache_path . '.htaccess', 'supercache', explode( "\n", $generated_rules[ 'gziprules' ] ) );
4212    }
4213    $wprules = extract_from_markers( $home_path . '.htaccess', 'WordPress' );
4214    wpsc_remove_marker( $home_path . '.htaccess', 'WordPress' ); // remove original WP rules so SuperCache rules go on top
4215    if ( insert_with_markers( $home_path . '.htaccess', 'WPSuperCache', explode( "\n", $rules ) ) && insert_with_markers( $home_path . '.htaccess', 'WordPress', $wprules ) ) {
4216        $new_page = wp_remote_get( $url, array( 'timeout' => 60, 'blocking' => true ) );
4217        $restore_backup = false;
4218        if ( is_wp_error( $new_page ) ) {
4219            $restore_backup = true;
4220            $update_mod_rewrite_rules_error = "Error testing page with new .htaccess rules: " . $new_page->get_error_message() . ".";
4221            wp_cache_debug( 'update_mod_rewrite_rules: failed to update rules. error fetching second page: ' . $new_page->get_error_message() );
4222        } elseif ( $new_page[ 'body' ] != $original_page[ 'body' ] ) {
4223            $restore_backup = true;
4224            $update_mod_rewrite_rules_error = "Page test failed as pages did not match with new .htaccess rules.";
4225            wp_cache_debug( 'update_mod_rewrite_rules: failed to update rules. page test failed as pages did not match. Files dumped in ' . $cache_path . ' for inspection.' );
4226            wp_cache_debug( 'update_mod_rewrite_rules: original page: 1-' . md5( $original_page[ 'body' ] ) . '.txt' );
4227            wp_cache_debug( 'update_mod_rewrite_rules: new page: 1-' . md5( $new_page[ 'body' ] ) . '.txt' );
4228            file_put_contents( $cache_path . '1-' . md5( $original_page[ 'body' ] ) . '.txt', $original_page[ 'body' ] );
4229            file_put_contents( $cache_path . '2-' . md5( $new_page[ 'body' ] ) . '.txt', $new_page[ 'body' ] );
4230        }
4231
4232        if ( $restore_backup ) {
4233            global $wp_cache_debug;
4234            file_put_contents( $home_path . '.htaccess', $backup_file_contents );
4235            unlink( $backup_filename );
4236            if ( $wp_cache_debug ) {
4237                $update_mod_rewrite_rules_error .= "<br />See debug log for further details";
4238            } else {
4239                $update_mod_rewrite_rules_error .= "<br />Enable debug log on Debugging page for further details and try again";
4240            }
4241
4242            return false;
4243        }
4244    } else {
4245        file_put_contents( $home_path . '.htaccess', $backup_file_contents );
4246        unlink( $backup_filename );
4247        $update_mod_rewrite_rules_error = "problem inserting rules in .htaccess and original .htaccess restored";
4248        return false;
4249    }
4250
4251    return true;
4252}
4253
4254// Delete feeds when the site is updated so that feed files are always fresh
4255function wpsc_feed_update( $type, $permalink ) {
4256    $wpsc_feed_list = get_option( 'wpsc_feed_list' );
4257
4258    update_option( 'wpsc_feed_list', array() );
4259    if ( is_array( $wpsc_feed_list ) && ! empty( $wpsc_feed_list ) ) {
4260        foreach( $wpsc_feed_list as $file ) {
4261            wp_cache_debug( "wpsc_feed_update: deleting feed: $file" );
4262            prune_super_cache( $file, true );
4263            prune_super_cache( dirname( $file ) . '/meta-' . basename( $file ), true );
4264        }
4265    }
4266}
4267add_action( 'gc_cache', 'wpsc_feed_update', 10, 2 );
4268
4269function wpsc_get_plugin_list() {
4270    $list = do_cacheaction( 'wpsc_filter_list' );
4271    foreach( $list as $t => $details ) {
4272        $key = "cache_" . $details[ 'key' ];
4273        if ( isset( $GLOBALS[ $key ] ) && $GLOBALS[ $key ] == 1 ) {
4274            $list[ $t ][ 'enabled' ] = true;
4275        } else {
4276            $list[ $t ][ 'enabled' ] = false;
4277        }
4278
4279        $list[ $t ]['desc']  = strip_tags( $list[ $t ]['desc'] ?? '' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags
4280        $list[ $t ]['title'] = strip_tags( $list[ $t ]['title'] ?? '' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags
4281    }
4282    return $list;
4283}
4284
4285function wpsc_update_plugin_list( $update ) {
4286    $list = do_cacheaction( 'wpsc_filter_list' );
4287    foreach( $update as $key => $enabled ) {
4288        $plugin_toggle = "cache_{$key}";
4289        if ( isset( $GLOBALS[ $plugin_toggle ] ) || isset( $list[ $key ] ) ) {
4290            wp_cache_setting( $plugin_toggle, (int)$enabled );
4291        }
4292    }
4293}
4294
4295function wpsc_add_plugin( $file ) {
4296    global $wpsc_plugins;
4297    if ( substr( $file, 0, strlen( ABSPATH ) ) == ABSPATH ) {
4298        $file = substr( $file, strlen( ABSPATH ) ); // remove ABSPATH
4299    }
4300    if (
4301        ! isset( $wpsc_plugins ) ||
4302        ! is_array( $wpsc_plugins ) ||
4303        ! in_array( $file, $wpsc_plugins )
4304    ) {
4305        $wpsc_plugins[] = $file;
4306        wp_cache_setting( 'wpsc_plugins', $wpsc_plugins );
4307    }
4308    return $file;
4309}
4310add_action( 'wpsc_add_plugin', 'wpsc_add_plugin' );
4311
4312function wpsc_delete_plugin( $file ) {
4313    global $wpsc_plugins;
4314    if ( substr( $file, 0, strlen( ABSPATH ) ) == ABSPATH ) {
4315        $file = substr( $file, strlen( ABSPATH ) ); // remove ABSPATH
4316    }
4317    if (
4318        isset( $wpsc_plugins ) &&
4319        is_array( $wpsc_plugins ) &&
4320        in_array( $file, $wpsc_plugins )
4321    ) {
4322        unset( $wpsc_plugins[ array_search( $file, $wpsc_plugins ) ] );
4323        wp_cache_setting( 'wpsc_plugins', $wpsc_plugins );
4324    }
4325    return $file;
4326}
4327add_action( 'wpsc_delete_plugin', 'wpsc_delete_plugin' );
4328
4329function wpsc_get_plugins() {
4330    global $wpsc_plugins;
4331    return $wpsc_plugins;
4332}
4333
4334function wpsc_add_cookie( $name ) {
4335    global $wpsc_cookies;
4336    if (
4337        ! isset( $wpsc_cookies ) ||
4338        ! is_array( $wpsc_cookies ) ||
4339        ! in_array( $name, $wpsc_cookies )
4340    ) {
4341        $wpsc_cookies[] = $name;
4342        wp_cache_setting( 'wpsc_cookies', $wpsc_cookies );
4343    }
4344    return $name;
4345}
4346add_action( 'wpsc_add_cookie', 'wpsc_add_cookie' );
4347
4348function wpsc_delete_cookie( $name ) {
4349    global $wpsc_cookies;
4350    if (
4351        isset( $wpsc_cookies ) &&
4352        is_array( $wpsc_cookies ) &&
4353        in_array( $name, $wpsc_cookies )
4354    ) {
4355        unset( $wpsc_cookies[ array_search( $name, $wpsc_cookies ) ] );
4356        wp_cache_setting( 'wpsc_cookies', $wpsc_cookies );
4357    }
4358    return $name;
4359}
4360add_action( 'wpsc_delete_cookie', 'wpsc_delete_cookie' );
4361
4362function wpsc_get_cookies() {
4363    global $wpsc_cookies;
4364    return $wpsc_cookies;
4365}
4366
4367function wpsc_get_extra_cookies() {
4368    global $wpsc_cookies;
4369    if (
4370        is_array( $wpsc_cookies ) &&
4371        ! empty( $wpsc_cookies )
4372    ) {
4373        return '|' . implode( '|', $wpsc_cookies );
4374    } else {
4375        return '';
4376    }
4377}
4378
4379function wpsc_update_check() {
4380    global $wpsc_version;
4381
4382    if (
4383        ! isset( $wpsc_version ) ||
4384        $wpsc_version != 169
4385    ) {
4386        wp_cache_setting( 'wpsc_version', 169 );
4387        global $wp_cache_debug_log, $cache_path;
4388        $log_file = $cache_path . str_replace('/', '', str_replace('..', '', $wp_cache_debug_log));
4389        if ( ! file_exists( $log_file ) ) {
4390            return false;
4391        }
4392        @unlink( $log_file );
4393        wp_cache_debug( 'wpsc_update_check: Deleted old log file on plugin update.' );
4394    }
4395}
4396add_action( 'admin_init', 'wpsc_update_check' );
4397
4398/**
4399 * Renders a partial/template.
4400 *
4401 * The global $current_user is made available for any rendered template.
4402 *
4403 * @param string $partial  - Filename under ./partials directory, with or without .php (appended if absent).
4404 * @param array  $page_vars - Variables made available for the template.
4405 */
4406function wpsc_render_partial( $partial, array $page_vars = array() ) {
4407    if ( ! str_ends_with( $partial, '.php' ) ) {
4408        $partial .= '.php';
4409    }
4410
4411    if ( strpos( $partial, 'partials/' ) !== 0 ) {
4412        $partial = 'partials/' . $partial;
4413    }
4414
4415    $path = __DIR__ . '/' . $partial;
4416    if ( ! file_exists( $path ) ) {
4417        return;
4418    }
4419
4420    foreach ( $page_vars as $key => $val ) {
4421        $$key = $val;
4422    }
4423    global $current_user;
4424    include $path;
4425}
4426
4427/**
4428 * Render common header
4429 */
4430function wpsc_render_header() {
4431    ?>
4432        <div class="header">
4433            <img class="wpsc-icon" src="<?php echo esc_url( plugin_dir_url( __FILE__ ) . '/assets/super-cache-icon.png' ); ?>" />
4434            <span class="wpsc-name"><?php echo esc_html( 'WP Super Cache' ); ?></span>
4435        </div>
4436    <?php
4437}
4438
4439/**
4440 * Render common footer
4441 */
4442function wpsc_render_footer() {
4443    ?>
4444    <div class="footer">
4445        <div class="wp-super-cache-version">
4446            <img class="wpsc-icon" src="<?php echo esc_url( plugin_dir_url( __FILE__ ) . '/assets/super-cache-icon.png' ); ?>" />
4447            <span class="wpsc-name"><?php echo esc_html( 'WP Super Cache' ); ?></span>
4448        </div>
4449        <div class="automattic-airline">
4450            <img class="wpsc-icon" src="<?php echo esc_url( plugin_dir_url( __FILE__ ) . '/assets/automattic-airline.svg' ); ?>" />
4451        </div>
4452    </div>
4453    <?php
4454}