first commit

This commit is contained in:
2024-11-10 21:08:49 +01:00
commit 0d932ce5ee
14455 changed files with 2567501 additions and 0 deletions

View File

@@ -0,0 +1,292 @@
<?php
if (!defined('ABSPATH')) die('No direct access allowed');
/**
* All cache commands that are intended to be available for calling from any sort of control interface (e.g. wp-admin, UpdraftCentral) go in here. All public methods should either return the data to be returned, or a WP_Error with associated error code, message and error data.
*/
class WP_Optimize_Cache_Commands {
private $optimizer;
private $options;
/**
* WP_Optimize_Cache_Commands constructor.
*/
public function __construct() {
$this->optimizer = WP_Optimize()->get_optimizer();
$this->options = WP_Optimize()->get_options();
}
/**
* Save cache settings
*
* @param array $data
*
* @return array
*/
public function save_cache_settings($data) {
if (!class_exists('WPO_Cache_Config')) return array(
'result' => false,
'message' => "WPO_Cache_Config class doesn't exist",
);
// filter for validate cache settings before save it.
$validation = apply_filters('wpo_save_cache_settings_validation', $data['cache-settings']);
if (!empty($validation) && isset($validation['result']) && false === $validation['result']) {
return $validation;
}
$enabled = false;
$disabled = false;
$return = !empty($validation) ? $validation : array();
$previous_settings = WPO_Cache_Config::instance()->get();
// Attempt to change current status if required
if (isset($previous_settings['enable_page_caching']) && $previous_settings['enable_page_caching'] != $data['cache-settings']['enable_page_caching']) {
// Disable cache.
if (empty($data['cache-settings']['enable_page_caching'])) {
$disabled = WPO_Page_Cache::instance()->disable();
// Disabling failed
if ($disabled && is_wp_error($disabled)) {
// If disabling failed, we re-enable whatever was disabled, to make sure nothing breaks.
if ($previous_settings['enable_page_caching']) WPO_Page_Cache::instance()->enable(true);
$return['error'] = array(
'code' => $disabled->get_error_code(),
'message' => $disabled->get_error_message()
);
} elseif (WPO_Page_Cache::instance()->has_warnings()) {
$return['warnings_label'] = __('Page caching was disabled, but with some warnings:', 'wp-optimize');
$return['warnings'] = WPO_Page_Cache::instance()->get_errors('warning');
}
} else {
// we need to rebuild advanced-cache.php and add WP_CACHE to wp-config.
$enabled = WPO_Page_Cache::instance()->enable(true);
// Enabling failed
if (is_wp_error($enabled)) {
// disable everything, to avoid half enabled things
WPO_Page_Cache::instance()->disable();
$return['error'] = array(
'code' => $enabled->get_error_code(),
'message' => $enabled->get_error_message()
);
if (WPO_Page_Cache::instance()->advanced_cache_file_writing_error) {
$return['advanced_cache_file_writing_error'] = true;
$return['advanced_cache_file_content'] = WPO_Page_Cache::instance()->advanced_cache_file_content;
}
} elseif (WPO_Page_Cache::instance()->has_warnings()) {
$return['warnings_label'] = __('Page caching was enabled, but with some warnings:', 'wp-optimize');
$return['warnings'] = WPO_Page_Cache::instance()->get_errors('warning');
}
}
// Override enabled setting value
$data['cache-settings']['enable_page_caching'] = ($enabled && !is_wp_error($enabled)) || ($previous_settings['enable_page_caching'] && is_wp_error($disabled));
} else {
$data['cache-settings']['enable_page_caching'] = $previous_settings['enable_page_caching'];
$enabled = $previous_settings['enable_page_caching'];
}
$skip_if_no_file_yet = !$enabled || is_wp_error($enabled);
$save_settings_result = WPO_Cache_Config::instance()->update($data['cache-settings'], $skip_if_no_file_yet);
if ($save_settings_result && !is_wp_error($save_settings_result)) {
WP_Optimize_Page_Cache_Preloader::instance()->cache_settings_updated($data['cache-settings'], $previous_settings);
$return['result'] = $save_settings_result;
} else {
// Saving the settings returned an error
if (is_wp_error($save_settings_result)) {
if (isset($return['error'])) {
$return['error']['message'] .= "\n\n".$save_settings_result->get_error_message();
} else {
$return['error'] = array(
'code' => $save_settings_result->get_error_code(),
'message' => $save_settings_result->get_error_message()
);
}
}
$return['result'] = false;
}
$return['enabled'] = ($enabled && !is_wp_error($enabled)) || ($previous_settings['enable_page_caching'] && is_wp_error($disabled));
return $return;
}
/**
* Get information about current cache status. Used in cli commands.
*
* @return array
*/
public function get_status_info() {
$status = array();
$status[] = WPO_Page_Cache::instance()->is_enabled() ? __('Caching is enabled', 'wp-optimize') : __('Caching is disabled', 'wp-optimize');
$preloader_status = WP_Optimize_Page_Cache_Preloader::instance()->get_status_info();
$status[] = sprintf(__('Current cache size: %s', 'wp-optimize'), $preloader_status['size']);
$status[] = sprintf(__('Number of files: %s', 'wp-optimize'), $preloader_status['file_count']);
if (array_key_exists('message', $preloader_status)) $status[] = $preloader_status['message'];
$status['message'] = join(PHP_EOL, $status);
return $status;
}
/**
* Enable cache.
*/
public function enable() {
$settings = WPO_Cache_Config::instance()->get();
$settings['enable_page_caching'] = true;
return $this->format_save_cache_settings_response($this->save_cache_settings(array('cache-settings' => $settings)));
}
/**
* Disable cache.
*/
public function disable() {
$settings = WPO_Cache_Config::instance()->get();
$settings['enable_page_caching'] = false;
return $this->format_save_cache_settings_response($this->save_cache_settings(array('cache-settings' => $settings)));
}
/**
* Purge WP-Optimize page cache.
*
* @return array
*/
public function purge_page_cache() {
if (!WP_Optimize()->get_page_cache()->can_purge_cache()) {
return array(
'success' => false,
'message' => __('You do not have permission to purge the cache', 'wp-optimize'),
);
}
$purged = WP_Optimize()->get_page_cache()->purge();
$cache_size = WP_Optimize()->get_page_cache()->get_cache_size();
$wpo_page_cache_preloader = WP_Optimize_Page_Cache_Preloader::instance();
$response = array(
'success' => $purged,
'size' => WP_Optimize()->format_size($cache_size['size']),
'file_count' => $cache_size['file_count'],
);
// if scheduled preload enabled then reschedule and run preloader.
if ($wpo_page_cache_preloader->is_scheduled_preload_enabled()) {
// cancel preload and reschedule preload action.
$wpo_page_cache_preloader->cancel_preload();
$wpo_page_cache_preloader->reschedule_preload();
// run preloader.
$wpo_page_cache_preloader->run('scheduled', $response);
}
if ($response['success']) {
$response['message'] = __('Page cache purged successfully', 'wp-optimize');
}
return $response;
}
/**
* Run cache preload (for wp-cli).
*
* @return array|bool
*/
public function run_cache_preload_cli() {
if (!(defined('WP_CLI') && WP_CLI)) return false;
// define WPO_ADVANCED_CACHE constant as WP-CLI doesn't load advanced-cache.php file
// but we check this constant value wen detecting status of cache
if (!defined('WPO_ADVANCED_CACHE')) define('WPO_ADVANCED_CACHE', true);
// don't interrupt queue processing
add_filter('updraft_interrupt_tasks_queue_load-url-task', '__return_false', 99);
// if preloading is running then exit.
if (WP_Optimize_Page_Cache_Preloader::instance()->is_busy()) {
return array(
'success' => false,
'error' => __('Preloading is currently running in another process.', 'wp-optimize'),
);
}
// set default response.
$response = array(
'success' => true,
'message' => __('All URLs were preloaded into cache successfully', 'wp-optimize'),
);
WP_CLI::log(__('Preloading URLs into cache...', 'wp-optimize'));
return WP_Optimize_Page_Cache_Preloader::instance()->run('manual', $response);
}
/**
* Run cache preload action.
*
* @return void|array - Doesn't return anything if run() is successfull (Run() prints a JSON object and closed browser connection) or an array if failed.
*/
public function run_cache_preload() {
return WP_Optimize_Page_Cache_Preloader::instance()->run('manual');
}
/**
* Cancel cache preload action.
*
* @return array
*/
public function cancel_cache_preload() {
WP_Optimize_Page_Cache_Preloader::instance()->cancel_preload();
return WP_Optimize_Page_Cache_Preloader::instance()->get_status_info();
}
/**
* Get status of cache preload.
*
* @return array
*/
public function get_cache_preload_status() {
return WP_Optimize_Page_Cache_Preloader::instance()->get_status_info();
}
/**
* Enable or disable browser cache.
*
* @param array $params - ['browser_cache_expire' => '1 month 15 days 2 hours' || '' - for disable cache]
* @return array
*/
public function enable_browser_cache($params) {
return WP_Optimize()->get_browser_cache()->enable_browser_cache_command_handler($params);
}
/**
* Format save_cache_settings() result for displaying in WP-CLI console
*
* @param array $response
* @return array
*/
private function format_save_cache_settings_response($response) {
$result = array(
'success' => $response['result'],
);
if (isset($response['error'])) {
$result['success'] = false;
$result['error'] = $response['error']['message'];
}
if ($result['success']) {
$result['message'] = __('Page cache settings updated successfully.', 'wp-optimize');
}
return $result;
}
}

View File

@@ -0,0 +1,106 @@
<?php
if (!defined('ABSPATH')) die('No direct access allowed');
class WP_Optimize_Detect_Cache_Plugins {
private static $instance;
/**
* WP_Optimize_Detect_Cache_Plugins constructor.
*/
protected function __construct() {
}
/**
* Detect list of active most popular WordPress cache plugins.
*
* @return array
*/
public function get_active_cache_plugins() {
// The index is the plugin's slug
$active_cache_plugins = array();
foreach ($this->get_plugins() as $plugin_slug => $plugin_title) {
$function_name = 'is_'.str_replace('-', '_', $plugin_slug).'_plugin_active';
if (is_callable(array($this, $function_name))) {
if (call_user_func(array($this, $function_name))) {
$active_cache_plugins[$plugin_slug] = $plugin_title;
}
} else {
if ($this->is_plugin_active($plugin_slug)) {
$active_cache_plugins[$plugin_slug] = $plugin_title;
}
}
}
return $active_cache_plugins;
}
/**
* Get the plugins list
*
* @return array
*/
protected function get_plugins() {
return array(
'w3-total-cache' => 'W3 Total Cache',
'wp-super-cache' => 'WP Super Cache',
'wp-rocket' => 'WP Rocket',
'wp-fastest-cache' => 'WP Fastest Cache',
'litespeed-cache' => 'LiteSpeed Cache',
'cache-enabler' => 'Cache Enabler',
'comet-cache' => 'Comet Cache',
'hummingbird-performance' => 'Hummingbird',
'hyper-cache' => 'Hyper Cache',
);
}
/**
* Check if W3 Total Cache active.
*
* @return bool
*/
public function is_w3_total_cache_plugin_active() {
return defined('W3TC_VERSION') || $this->is_plugin_active('w3-total-cache');
}
/**
* Check if WP Rocket active.
*
* @return bool
*/
public function is_wp_rocket_plugin_active() {
return defined('WP_ROCKET_VERSION') || $this->is_plugin_active('wp-rocket');
}
/**
* Check if $plugin is active.
*
* @param string $plugin - plugin slug
*
* @return bool
*/
private function is_plugin_active($plugin) {
$status = WP_Optimize()->get_db_info()->get_plugin_status($plugin);
return $status['active'];
}
/**
* Instance of WP_Optimize_Detect_Cache_Plugins.
*
* @return WP_Optimize_Detect_Cache_Plugins
*/
static public function instance() {
static $instance;
if (empty($instance)) {
$instance = new self();
}
return $instance;
}
}

View File

@@ -0,0 +1,671 @@
<?php
if (!defined('ABSPATH')) die('No direct access allowed');
if (!class_exists('WP_Optimize_Load_Url_Task')) {
require_once(WPO_PLUGIN_MAIN_PATH . 'cache/class-wpo-load-url-task.php');
}
class WP_Optimize_Page_Cache_Preloader extends WP_Optimize_Preloader {
protected $preload_type = 'page_cache';
protected $task_type = 'load-url-task';
static protected $_instance = null;
/**
* WP_Optimize_Page_Cache_Preloader constructor.
*/
public function __construct() {
parent::__construct();
add_action('wpo_page_cache_schedule_preload', array($this, 'run_scheduled_cache_preload'));
add_filter('wpo_preload_headers', array($this, 'preload_headers'));
}
/**
* Check if cache is active.
*
* @return bool
*/
public function is_option_active() {
return WP_Optimize()->get_page_cache()->is_enabled();
}
/**
* Schedule or delete automatic preload action on cache settings update.
*
* @param array $new_settings The new settings
* @param array $previous_settings Settings before saving
*/
public function cache_settings_updated($new_settings, $previous_settings) {
if (!$new_settings['enable_page_caching']) {
wp_clear_scheduled_hook('wpo_page_cache_schedule_preload');
$this->delete_preload_continue_action();
return;
}
if (!empty($new_settings['enable_schedule_preload'])) {
$last_schedule_type = $previous_settings['preload_schedule_type'];
if (wp_next_scheduled('wpo_page_cache_schedule_preload')) {
// if already scheduled this schedule type
if ($new_settings['preload_schedule_type'] == $last_schedule_type) {
// If the schedule type is cache lifespan, check if the cache lifespan changed.
if ('wpo_use_cache_lifespan' == $new_settings['preload_schedule_type']) {
// Else, if the settings cache lifespan settings haven't changed, returns
if ($new_settings['page_cache_length_value'] == $previous_settings['page_cache_length_value'] && $new_settings['page_cache_length_unit'] == $previous_settings['page_cache_length_unit']) {
return;
}
} else {
return;
}
}
// clear currently scheduled preload action.
wp_clear_scheduled_hook('wpo_page_cache_schedule_preload');
}
// schedule preload action.
wp_schedule_event((time() + $this->get_schedule_interval($new_settings['preload_schedule_type'])), $new_settings['preload_schedule_type'], 'wpo_page_cache_schedule_preload');
} else {
wp_clear_scheduled_hook('wpo_page_cache_schedule_preload');
}
}
/**
* Clear active preload tasks, reschedule preload action.
*/
public function reschedule_preload() {
// clear scheduled action.
if (wp_next_scheduled('wpo_page_cache_schedule_preload')) {
wp_clear_scheduled_hook('wpo_page_cache_schedule_preload');
}
// schedule preload action if need.
if ($this->is_scheduled_preload_enabled()) {
$preload_schedule_type = $this->get_cache_config('preload_schedule_type');
wp_schedule_event(time() + $this->get_schedule_interval($preload_schedule_type), $preload_schedule_type, 'wpo_page_cache_schedule_preload');
}
}
/**
* Check if scheduled preload enabled.
*
* @return bool
*/
public function is_scheduled_preload_enabled() {
$enable_schedule_preload = $this->get_cache_config('enable_schedule_preload');
return !empty($enable_schedule_preload);
}
/**
* Check if we need run cache preload and run it.
*/
public function run_scheduled_cache_preload() {
$schedule_type = WPO_Cache_Config::instance()->get_option('preload_schedule_type');
if (!$schedule_type) return;
// Don't run preload if cache lifespan option enabled and cache not expired yet.
if ('wpo_use_cache_lifespan' == $schedule_type) {
/**
* Filters the allowed time difference between the cache exiry and the current time, in seconds.
* If the cache expires in less than $allowed_time_difference, preload. Otherwise leave it.
*
* @param integer $allowed_time_difference The time difference, in seconds (default is same as changed time limit)
*/
$time_limit = (defined('WP_OPTIMIZE_SET_TIME_LIMIT') && WP_OPTIMIZE_SET_TIME_LIMIT > 15) ? WP_OPTIMIZE_SET_TIME_LIMIT : 1800;
$allowed_time_difference = apply_filters('wpo_preload_allowed_time_difference', $time_limit);
$page_cache_lifespan = WPO_Cache_Config::instance()->get_option('page_cache_length', 0);
$last_preload_time = $this->options->get_option('wpo_last_page_cache_preload', 0);
$time_since_last_preload = time() - $last_preload_time;
$minimum_time_to_next_schedule_preload = $page_cache_lifespan - $allowed_time_difference;
// Skip this if the last preload is not as old as the cache lifespan minus $allowed_time_difference
if ($page_cache_lifespan > 0 && $time_since_last_preload < $minimum_time_to_next_schedule_preload) return;
}
$this->run();
}
/**
* Get cache config option value.
*
* @return mixed
*/
public function get_cache_config($option) {
static $config = null;
if (null === $config) $config = WPO_Page_Cache::instance()->config->get();
if (is_array($config) && array_key_exists($option, $config)) {
return $config[$option];
}
return false;
}
/**
* Create tasks (WP_Optimize_Load_Url_Task) for preload all urls from site.
*
* @param string $type The preload type (currently: scheduled, manual)
* @return void
*/
public function create_tasks_for_preload_site_urls($type) {
$urls = $this->get_site_urls();
if (!empty($urls)) {
$this->log(__('Creating tasks for preload site urls.', 'wp-optimize'));
foreach ($urls as $url) {
if (wpo_url_in_exceptions($url)) continue;
if ($this->url_is_already_cached($url, $type)) {
continue;
}
// this description is being used for internal purposes.
$description = 'Preload - '.$url;
$options = array('url' => $url, 'preload_type' => $type, 'anonymous_user_allowed' => (defined('DOING_CRON') && DOING_CRON) || (defined('WP_CLI') && WP_CLI));
if (!class_exists('WP_Optimize_Load_Url_Task')) {
require_once WPO_PLUGIN_MAIN_PATH . 'cache/class-wpo-load-url-task.php';
}
WP_Optimize_Load_Url_Task::create_task($this->task_type, $description, $options, 'WP_Optimize_Load_Url_Task');
}
$this->log(__('Tasks for preload site urls created.', 'wp-optimize'));
}
}
/**
* Preload mobile version from $url.
*
* @param string $url
*
* @return void
*/
public function preload_mobile($url) {
static $is_mobile_caching_enabled;
if (!isset($is_mobile_caching_enabled)) {
$is_mobile_caching_enabled = $this->get_cache_config('enable_mobile_caching');
}
// Only run if option is active
if (!$is_mobile_caching_enabled) return;
$mobile_args = array(
'httpversion' => '1.1',
'user-agent' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1',
'timeout' => 10,
'headers' => apply_filters('wpo_preload_headers', array()),
);
$mobile_args = apply_filters('wpo_page_cache_preloader_mobile_args', $mobile_args, $url);
$this->log('preload_mobile - ' . $url);
wp_remote_get($url, $mobile_args);
}
/**
* Preload amp version from $url.
*
* @param string $url
*
* @return void
*/
public function preload_amp($url) {
if (!apply_filters('wpo_should_preload_amp', false, $url)) return;
$amp_args = array(
'httpversion' => '1.1',
'user-agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36',
'timeout' => 10,
'headers' => array(
'X-WP-Optimize-Cache-Preload' => 'Yes',
),
);
$url = untrailingslashit($url) . '/amp/';
$amp_args = apply_filters('wpo_page_cache_preloader_amp_args', $amp_args, $url);
$this->log('preload_amp - ' . $url);
wp_remote_get($url, $amp_args);
}
/**
* Check if sitemap exists then returns list of urls from sitemap file otherwise returns all posts urls.
*
* @return array
*/
public function get_site_urls() {
$urls = $this->get_sitemap_urls();
if (!empty($urls)) {
$this->options->update_option('wpo_last_page_cache_preload_type', 'sitemap');
} else {
$urls = $this->get_post_urls();
$this->options->update_option('wpo_last_page_cache_preload_type', 'posts');
}
$this->log(sprintf(_n('%d url found.', '%d urls found.', count($urls), 'wp-optimize'), count($urls)));
/**
* Filter the URLs which will be preloaded
*
* @param array $urls
* @return array
*/
return apply_filters('wpo_preload_get_site_urls', $urls);
}
/**
* Loads sitemap file and returns list of urls.
*
* @param string $sitemap_url
*
* @return array|bool
*/
public function get_sitemap_urls($sitemap_url = '') {
$urls = array();
// if sitemap url is empty then use main sitemap file name.
$sitemap_url = ('' === $sitemap_url) ? site_url('/'.$this->get_sitemap_filename()) : $sitemap_url;
// if simplexml_load_string not available then we don't load sitemap.
if (!function_exists('simplexml_load_string')) {
return $urls;
}
// load sitemap file.
$response = wp_remote_get($sitemap_url, array('timeout' => 30));
// if we get error then
if (is_wp_error($response)) {
$response = file_get_contents($sitemap_url);
// if response is empty then try load from file.
if (empty($response) && '' == $sitemap_url) {
$sitemap_file = $this->get_local_sitemap_file();
$response = file_get_contents($sitemap_file);
}
if (empty($response)) return $urls;
$xml = @simplexml_load_string($response); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
} else {
// parse xml answer.
$xml = @simplexml_load_string(wp_remote_retrieve_body($response)); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
}
// xml file has not valid xml content then return false.
if (false === $xml) return false;
// if exists urls then return them.
if (isset($xml->url)) {
foreach ($xml->url as $element) {
if (!isset($element->loc)) continue;
$urls[] = (string) $element->loc;
}
} elseif (isset($xml->sitemap)) {
// if has links to other sitemap files then get urls from them.
foreach ($xml->sitemap as $element) {
if (!isset($element->loc)) continue;
$sitemap_urls = $this->get_sitemap_urls($element->loc);
if (is_array($sitemap_urls)) {
$urls = array_merge($urls, $sitemap_urls);
}
}
}
return $urls;
}
/**
* Get all posts of any post type and returns urls for them.
*
* @return array
*/
public function get_post_urls() {
global $post;
$offset = 0;
$posts_per_page = 1000;
$urls = array();
$urls[] = site_url('/');
do {
$query = new WP_Query(array(
'post_type' => 'any',
'post_status' => 'publish',
'posts_per_page' => $posts_per_page,
'offset' => $offset,
'orderby' => 'ID',
'order' => 'ASC',
'cache_results' => false, // disable cache to avoid memory error.
));
$posts_loaded = $query->post_count;
while ($query->have_posts()) {
$query->the_post();
$permalink = get_permalink();
$urls[] = $permalink;
// check page separators in the post content
preg_match_all('/\<\!--nextpage--\>/', $post->post_content, $matches);
// if there any separators add urls for each page
if (count($matches[0])) {
$prefix = strpos($permalink, '?') ? '&page=' : '';
for ($page = 0; $page < count($matches[0]); $page++) {
if ('' != $prefix) {
$urls[] = $permalink . $prefix . ($page+2);
} else {
$urls[] = trailingslashit($permalink) . ($page+2);
}
}
}
}
$offset += $posts_loaded;
} while ($posts_loaded > 0);
/**
* If domain mapping enabled then replace domains in urls.
*/
if ($this->is_domain_mapping_enabled()) {
$blog_id = get_current_blog_id();
$mapped_domain = $this->get_mapped_domain($blog_id);
$blog_details = get_blog_details($blog_id);
if ($mapped_domain) {
foreach ($urls as $i => $url) {
$urls[$i] = preg_replace('/'.$blog_details->domain.'/i', $mapped_domain, $url, 1);
}
}
}
wp_reset_postdata();
return $urls;
}
/**
* Check if domain mapping enabled.
*
* @return bool
*/
public function is_domain_mapping_enabled() {
// SUNRISE constant is defined with installation WordPress MU Domain Mapping plugin.
$enabled = is_multisite() && defined('SUNRISE') && 'on' == strtolower(SUNRISE);
/**
* Filters if Multisite Domain mapping is enabled.
* Currently, we can only detect if the WordPress MU Domain Mapping plugin is in use.
* Using the WP Core functionality should not require this, unless if the domain name is set somewhere else but in the site url option.
*/
return apply_filters('wpo_is_domain_mapping_enabled', $enabled);
}
/**
* Return mapped domain by $blog_id.
*
* @param int $blog_id
*
* @return string
*/
public function get_mapped_domain($blog_id) {
global $wpdb;
$domain = '';
$multisite_plugin_table_name = $wpdb->base_prefix.'domain_mapping';
// Check if table exists
if ($wpdb->get_var("SHOW TABLES LIKE '$multisite_plugin_table_name'") != $multisite_plugin_table_name) {
// This table created in WordPress MU Domain Mapping plugin.
$row = $wpdb->get_row("SELECT `domain` FROM {$multisite_plugin_table_name} WHERE `blog_id` = {$blog_id} AND `active` = 1", ARRAY_A);
if (!empty($row)) {
$domain = $row['domain'];
}
} else {
// When using the WP Core method, the site url option contains the mapped domain.
$domain = get_site_url($blog_id);
}
/**
* Filters the mapped domain name
*
* @param string $domain The domain name
* @param integer $blog_id The blog ID
*/
return apply_filters('wpo_get_mapped_domain', $domain, $blog_id);
}
/**
* Captures and logs any interesting messages
*
* @param String $message - the error message
* @param String $error_type - the error type
*/
public function log($message, $error_type = 'info') {
if (isset($this->loggers)) {
foreach ($this->loggers as $logger) {
$logger->log($message, $error_type);
}
}
}
/**
* Instance of WP_Optimize_Page_Cache_Preloader.
*
* @return WP_Optimize_Page_Cache_Preloader
*/
public static function instance() {
if (empty(self::$_instance)) {
self::$_instance = new WP_Optimize_Page_Cache_Preloader();
}
return self::$_instance;
}
/**
* Check if the URL is already cached, or needs to be preloaded
*
* @param string $url The preloaded url
* @param string $preload_type The preload type (manual | scheduled)
* @return boolean
*/
private function url_is_already_cached($url, $preload_type) {
static $files = array();
$regenerate_count = 0;
$folder = trailingslashit(WPO_CACHE_FILES_DIR) . wpo_get_url_path($url);
// If the folder does not exist, consider the URL as cleared
if (!is_dir($folder)) return false;
if (empty($files)) {
// Check only the base files
$files[] = 'index.html';
if (WPO_Cache_Config::instance()->get_option('enable_mobile_caching')) {
$files[] = 'mobile.index.html';
}
$files = apply_filters('wpo_maybe_clear_files_list', $files);
}
foreach ($files as $file) {
$file_path = trailingslashit($folder).$file;
if (!file_exists($file_path)) {
// The file does not exist, count it as "deleted"
$regenerate_count++;
continue;
}
if ($this->should_regenerate_file($file_path, $preload_type)) {
// delefe the expired cache file
unlink($file_path);
$regenerate_count++;
}
}
// if 0 == $regenerate_count, nothing all the expected files exist, and none were deleted.
return 0 == $regenerate_count;
}
/**
* Determine if a file should be regenerated
*
* @param string $path The file to check
* @param string $preload_type The preload type (manual | scheduled)
*
* @return boolean
*/
private function should_regenerate_file($path, $preload_type) {
// Store the variables, as they'll be used for each file and each file
static $is_preloader_scheduled = null;
static $lifespan = null;
static $schedule_type = null;
static $schedule_interval = null;
static $lifespan_expiry_threshold = null;
static $always_regenerate_file_if_preload_is_manual = null;
static $always_regenerate_file_if_preload_is_scheduled = null;
static $regenerate_file_when_no_expiry_date = null;
// Sets the variables once per request:
if (null === $is_preloader_scheduled) {
$is_preloader_scheduled = WPO_Cache_Config::instance()->get_option('enable_schedule_preload');
$schedule_type = WPO_Cache_Config::instance()->get_option('preload_schedule_type');
$lifespan = WPO_Cache_Config::instance()->get_option('page_cache_length');
$schedule_interval = $this->get_schedule_interval($schedule_type);
/**
* Expiry threshold: the current file will be considered stale if within the threshold. Default: 600s (10min)
*/
$lifespan_expiry_threshold = apply_filters('wpo_lifespan_expiry_threshold', 600);
/**
* Filters if a cache should systematically be regenerated when running a manual preload. Default: false
*/
$always_regenerate_file_if_preload_is_manual = apply_filters('wpo_always_regenerate_file_if_preload_is_manual', false);
/**
* Filters if a cache should systematically be regenerated when running a scheduled preload. Default: false
*/
$always_regenerate_file_if_preload_is_scheduled = apply_filters('wpo_always_regenerate_file_if_preload_is_scheduled', false);
/**
* Filters if a cache should systematically be regenerated when running a preload and no schedule is set, and cache does not expire. Default: true
*/
$regenerate_file_when_no_expiry_date = apply_filters('wpo_regenerate_file_when_no_expiry_date', true);
}
if (($always_regenerate_file_if_preload_is_manual && 'manual' == $preload_type) || ($always_regenerate_file_if_preload_is_scheduled && 'scheduled' == $preload_type)) {
$result = true;
} else {
$modified_time = (int) filemtime($path);
// cache lifespan is set.
if (0 != $lifespan) {
$expiry_time = $modified_time + $lifespan - $lifespan_expiry_threshold;
$result = time() > $expiry_time;
} elseif ($is_preloader_scheduled) {
$expiry_time = $modified_time + $schedule_interval - $lifespan_expiry_threshold;
$result = time() > $expiry_time;
} else {
$result = $regenerate_file_when_no_expiry_date;
}
}
return apply_filters('wpo_preloader_should_regenerate_file', $result, $path, $preload_type);
}
/**
* Add preloader headers
*/
public function preload_headers($headers) {
$headers['X-WP-Optimize-Cache-Preload'] = 'Yes';
return $headers;
}
/**
* Option disabled error message
*
* @return array
*/
protected function get_option_disabled_error() {
return array(
'success' => false,
'error' => __('Page cache is disabled.', 'wp-optimize')
);
}
/**
* Get preload already running error message
*
* @return array
*/
protected function get_preload_already_running_error() {
return array(
'success' => false,
'error' => __('Probably page cache preload is running already.', 'wp-optimize')
);
}
protected function get_preload_data() {
return WP_Optimize()->get_page_cache()->get_cache_size();
}
protected function get_preloading_message($cache_size) {
return array(
'done' => false,
'message' => __('Loading URLs...', 'wp-optimize'),
'size' => WP_Optimize()->format_size($cache_size['size']),
'file_count' => $cache_size['file_count']
);
}
protected function get_last_preload_message($cache_size, $last_preload_time_str) {
return array(
'done' => true,
'message' => sprintf(__('Last preload finished at %s', 'wp-optimize'), $last_preload_time_str),
'size' => WP_Optimize()->format_size($cache_size['size']),
'file_count' => $cache_size['file_count']
);
}
protected function get_preload_success_message($cache_size) {
return array(
'done' => true,
'size' => WP_Optimize()->format_size($cache_size['size']),
'file_count' => $cache_size['file_count']
);
}
protected function get_preload_progress_message($cache_size, $preloaded_message, $preload_resuming_in) {
return array(
'done' => false,
'message' => $preloaded_message,
'size' => WP_Optimize()->format_size($cache_size['size']),
'file_count' => $cache_size['file_count'],
'resume_in' => $preload_resuming_in
);
}
}
WP_Optimize_Page_Cache_Preloader::instance();

View File

@@ -0,0 +1,289 @@
<?php
if (!defined('ABSPATH')) die('No direct access allowed');
/**
* Handles cache configuration and related I/O
*/
if (!class_exists('WPO_Cache_Config')) :
class WPO_Cache_Config {
/**
* Defaults
*
* @var array
*/
public $defaults;
/**
* Instance of this class
*
* @var mixed
*/
public static $instance;
/**
* @var array
*/
public $config;
/**
* Set config defaults
*/
public function __construct() {
$this->defaults = $this->get_defaults();
}
/**
* Get config from file or cache
*
* @return array
*/
public function get() {
if (is_multisite()) {
$config = get_site_option('wpo_cache_config', $this->get_defaults());
} else {
$config = get_option('wpo_cache_config', $this->get_defaults());
}
return wp_parse_args($config, $this->get_defaults());
}
/**
* Get a specific configuration option
*
* @param string $option_key The option identifier
* @param boolean $default Default value if the option doesn't exist (Default to false)
* @return mixed
*/
public function get_option($option_key, $default = false) {
$options = $this->get();
return apply_filters("wpo_option_key_{$option_key}", (isset($options[$option_key]) ? $options[$option_key] : $default));
}
/**
* Updates the given config object in file and DB
*
* @param array $config - the cache configuration
* @param boolean $skip_disk_if_not_yet_present - only write the configuration file to disk if it already exists. This presents PHP notices if the cache has never been on, and settings are saved.
*
* @return bool
*/
public function update($config, $skip_disk_if_not_yet_present = false) {
$config = wp_parse_args($config, $this->get_defaults());
$config['page_cache_length_value'] = intval($config['page_cache_length_value']);
$config['page_cache_length'] = $this->calculate_page_cache_length($config['page_cache_length_value'], $config['page_cache_length_unit']);
/**
* Filters the cookies used to set cache file names
*
* @param array $cookies - The cookies
* @param array $config - The new config
*/
$wpo_cache_cookies = apply_filters('wpo_cache_cookies', array(), $config);
sort($wpo_cache_cookies);
/**
* Filters the query variables used to set cache file names
*
* @param array $wpo_query_variables - The variables
* @param array $config - The new config
*/
$wpo_query_variables = apply_filters('wpo_cache_query_variables', array(), $config);
sort($wpo_query_variables);
$config['wpo_cache_cookies'] = $wpo_cache_cookies;
$config['wpo_cache_query_variables'] = $wpo_query_variables;
$config = apply_filters('wpo_cache_update_config', $config);
if (is_multisite()) {
update_site_option('wpo_cache_config', $config);
} else {
update_option('wpo_cache_config', $config);
}
do_action('wpo_cache_config_updated', $config);
return $this->write($config, $skip_disk_if_not_yet_present);
}
/**
* Calculate cache expiration value in seconds.
*
* @param int $value
* @param string $unit ( hours | days | months )
*
* @return int
*/
private function calculate_page_cache_length($value, $unit) {
$cache_length_units = array(
'hours' => 3600,
'days' => 86400,
'months' => 2629800, // 365.25 * 86400 / 12
);
return $value * $cache_length_units[$unit];
}
/**
* Deletes config files and options
*
* @return bool
*/
public function delete() {
if (is_multisite()) {
delete_site_option('wpo_cache_config');
} else {
delete_option('wpo_cache_config');
}
if (!WPO_Page_Cache::delete(WPO_CACHE_CONFIG_DIR)) {
return false;
}
return true;
}
/**
* Writes config to file
*
* @param array $config - Configuration array.
* @param boolean $only_if_present - only writes to the disk if the configuration file already exists
*
* @return boolean - returns false if an attempt to write failed
*/
public function write($config, $only_if_present = false) {
$config_file = WPO_CACHE_CONFIG_DIR.'/'.$this->get_cache_config_filename();
$this->config = wp_parse_args($config, $this->get_defaults());
// from 3.0.17 we use more secure way to store cache config files.
$advanced_cache_version = WPO_Page_Cache::instance()->get_advanced_cache_version();
// if advanced-cache.php exists and has at least 3.0.17 version or
// advanced-cache.php doesn't exist then
// we write the cache config in a new format.
if (($advanced_cache_version && (version_compare($advanced_cache_version, '3.0.17', '>='))) || !$advanced_cache_version) {
$config_content = '<?php' . "\n"
. 'if (!defined(\'ABSPATH\')) die(\'No direct access allowed\');' . "\n\n"
. '$GLOBALS[\'wpo_cache_config\'] = json_decode(\'' . json_encode($this->config) . '\', true);' . "\n";
} else {
$config_content = json_encode($this->config);
}
if ((!$only_if_present || file_exists($config_file)) && !file_put_contents($config_file, $config_content)) {
return new WP_Error('write_cache_config', sprintf(__('The cache configuration file could not be saved to the disk; please check the file/folder permissions of %s .', 'wp-optimize'), $config_file));
}
return true;
}
/**
* Verify we can write to the file system
*
* @since 1.0
* @return boolean
*/
public function verify_file_access() {
if (function_exists('clearstatcache')) {
clearstatcache();
}
// First check wp-config.php.
if (!is_writable(ABSPATH . 'wp-config.php') && !is_writable(ABSPATH . '../wp-config.php')) {
return false;
}
// Now check wp-content. We need to be able to create files of the same user as this file.
if (!$this->_is_dir_writable(untrailingslashit(WP_CONTENT_DIR))) {
return false;
}
// If the cache and config directories exist, make sure they're writeable
if (file_exists(untrailingslashit(WP_CONTENT_DIR) . '/wpo-cache')) {
if (file_exists(WPO_CACHE_DIR)) {
if (!$this->_is_dir_writable(WPO_CACHE_DIR)) {
return false;
}
}
if (file_exists(WPO_CACHE_CONFIG_DIR)) {
if (!$this->_is_dir_writable(WPO_CACHE_CONFIG_DIR)) {
return false;
}
}
}
return true;
}
/**
* Return defaults
*
* @return array
*/
public function get_defaults() {
$defaults = array(
'enable_page_caching' => false,
'page_cache_length_value' => 24,
'page_cache_length_unit' => 'hours',
'page_cache_length' => 86400,
'cache_exception_conditional_tags' => array(),
'cache_exception_urls' => array(),
'cache_exception_cookies' => array(),
'cache_exception_browser_agents' => array(),
'enable_sitemap_preload' => false,
'enable_schedule_preload' => false,
'preload_schedule_type' => '',
'enable_mobile_caching' => false,
'enable_user_caching' => false,
'site_url' => network_home_url('/'),
'enable_cache_per_country' => false,
'permalink_structure' => get_option('permalink_structure'),
'uploads' => wp_normalize_path(wp_upload_dir()['basedir']),
'gmt_offset' => get_option('gmt_offset'),
);
return apply_filters('wpo_cache_defaults', $defaults);
}
/**
* Get advanced-cache.php file name with full path.
*
* @return string
*/
public function get_cache_config_filename() {
$url = parse_url(network_site_url());
if (isset($url['port']) && '' != $url['port'] && 80 != $url['port']) {
return 'config-'.strtolower($url['host']).'-port'.$url['port'].'.php';
} else {
return 'config-'.strtolower($url['host']).'.php';
}
}
/**
* Return an instance of the current class, create one if it doesn't exist
*
* @since 1.0
* @return WPO_Cache_Config
*/
public static function instance() {
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
}
endif;

View File

@@ -0,0 +1,373 @@
<?php
if (!defined('ABSPATH')) die('No direct access allowed');
/**
* Page caching rules and exceptions
*/
require_once dirname(__FILE__) . '/file-based-page-cache-functions.php';
if (!class_exists('WPO_Cache_Rules')) :
class WPO_Cache_Rules {
/**
* Cache config object
*
* @var mixed
*/
public $config;
/**
* Instance of this class
*
* @var mixed
*/
public static $instance;
public function __construct() {
$this->config = WPO_Cache_Config::instance()->get();
$this->setup_hooks();
}
/**
* Setup hooks/filters
*/
public function setup_hooks() {
add_action('save_post', array($this, 'purge_post_on_update'), 10, 1);
add_action('save_post', array($this, 'purge_archive_pages_on_post_update'), 10, 1);
add_action('wp_trash_post', array($this, 'purge_post_on_update'), 10, 1);
add_action('comment_post', array($this, 'purge_post_on_comment'), 10, 3);
add_action('wp_set_comment_status', array($this, 'purge_post_on_comment_status_change'), 10, 1);
add_action('edit_terms', array($this, 'purge_related_elements_on_term_updated'), 10, 2);
add_action('set_object_terms', array($this, 'purge_related_elements_on_post_terms_change'), 10, 6);
add_action('wpo_cache_config_updated', array($this, 'cache_config_updated'), 10, 1);
add_action('wp_insert_comment', array($this, 'comment_inserted'), 10, 2);
add_action('import_start', array($this, 'remove_wp_insert_comment'));
add_action('woocommerce_variation_set_stock', array($this, 'purge_product_page'), 10, 1);
add_action('woocommerce_product_set_stock', array($this, 'purge_product_page'), 10, 1);
/**
* List of hooks for which when executed, the cache will be purged
*
* @param array $actions The actions
*/
$actions = array(
'after_switch_theme',
'wp_update_nav_menu',
'customize_save_after',
array('wp_ajax_save-widget', 0),
array('wp_ajax_update-widget', 0),
'autoptimize_action_cachepurged',
'upgrader_overwrote_package',
'wpo_active_plugin_or_theme_updated',
'fusion_cache_reset_after',
'update_option_permalink_structure',
'wpml_st_add_string_translation',
);
$purge_on_action = apply_filters('wpo_purge_cache_hooks', $actions);
foreach ($purge_on_action as $action) {
if (is_array($action)) {
add_action($action[0], array($this, 'purge_cache'), $action[1]);
} else {
add_action($action, array($this, 'purge_cache'));
}
}
}
/**
* Purge post cache when there is a new approved comment
*
* @param int $comment_id Comment ID.
* @param int|string $approved Comment approved status. can be 0, 1 or 'spam'.
* @param array $commentdata Comment data array. Always sent be WP core, but a plugin was found that does not send it - https://wordpress.org/support/topic/critical-problems-with-version-3-0-10/
*/
public function purge_post_on_comment($comment_id, $approved, $commentdata = array()) {
if (1 !== $approved) {
return;
}
if (!empty($this->config['enable_page_caching']) && !empty($commentdata['comment_post_ID'])) {
$post_id = $commentdata['comment_post_ID'];
WPO_Page_Cache::delete_single_post_cache($post_id);
WPO_Page_Cache::delete_comments_feed();
}
}
/**
* Every time a comment's status changes, purge it's parent posts cache
*
* @param int $comment_id Comment ID.
*/
public function purge_post_on_comment_status_change($comment_id) {
if (!empty($this->config['enable_page_caching'])) {
$comment = get_comment($comment_id);
if (is_object($comment) && !empty($comment->comment_post_ID)) {
WPO_Page_Cache::delete_single_post_cache($comment->comment_post_ID);
WPO_Page_Cache::delete_comments_feed();
}
}
}
/**
* Action when a comment is inserted
*
* @param integer $comment_id - The comment ID
* @param boolean|WP_Comment $comment - The comment object (from WP 4.4)
* @return void
*/
public function comment_inserted($comment_id, $comment = false) {
if ($comment && is_a($comment, 'WP_Comment')) {
/**
* Filters whether to add a cookie when a comment is posted, in order to exclude the page from caching.
* Regular comments have the property comment_type set to '' or 'comment'. So by default, only add the cookie in those cases.
*
* @param boolean $add_cookie
* @param WP_Comment $comment
* @return boolean
*/
$add_cookie = apply_filters('wpo_add_commented_post_cookie', '' == $comment->comment_type || 'comment' == $comment->comment_type, $comment);
if (!$add_cookie) return;
$url = get_permalink($comment->comment_post_ID);
$url_info = parse_url($url);
setcookie('wpo_commented_post', 1, time() + WEEK_IN_SECONDS, isset($url_info['path']) ? $url_info['path'] : '/');
}
}
/**
* Comment posted cookie is not needed for imports. So remove the action
*/
public function remove_wp_insert_comment() {
remove_action('wp_insert_comment', array($this, 'comment_inserted'), 10);
}
/**
* Automatically purge all file based page cache on post changes
* We want the whole cache purged here as different parts
* of the site could potentially change on post updates
*
* @param Integer $post_id - WP post id
*/
public function purge_post_on_update($post_id) {
$post_type = get_post_type($post_id);
$post_type_object = get_post_type_object($post_type);
if ((defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) || 'revision' === $post_type || null === $post_type_object || !$post_type_object->public) {
return;
}
/**
* Purge the whole cache if set to true, only the edited post otherwise. Default is false.
*
* @param boolean $purge_all_cache The default filter value
* @param integer $post_id The saved post ID
*/
if (apply_filters('wpo_purge_all_cache_on_update', false, $post_id)) {
$this->purge_cache();
return;
} else {
if (apply_filters('wpo_delete_cached_homepage_on_post_update', true, $post_id)) WPO_Page_Cache::delete_homepage_cache();
WPO_Page_Cache::delete_feed_cache();
WPO_Page_Cache::delete_single_post_cache($post_id);
WPO_Page_Cache::delete_sitemap_cache();
WPO_Page_Cache::delete_post_feed_cache($post_id);
}
}
/**
* Purge archive pages on post update.
*
* @param integer $post_id
*/
public function purge_archive_pages_on_post_update($post_id) {
$post_type = get_post_type($post_id);
if (false === $post_type) return;
if ((defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) || 'revision' === $post_type) {
return;
}
$post_obj = get_post_type_object($post_type);
if (null === $post_obj) return;
if ('post' == $post_type) {
// delete blog page cache
$blog_post_id = get_option('page_for_posts');
if ($blog_post_id) {
WPO_Page_Cache::delete_cache_by_url(get_permalink($blog_post_id), true);
}
// delete next and previus posts cache.
$globals_post = isset($GLOBALS['post']) ? $GLOBALS['post'] : false;
$GLOBALS['post'] = get_post($post_id);
$previous_post = function_exists('get_previous_post') ? get_previous_post() : false;
$next_post = function_exists('get_next_post') ? get_next_post() : false;
if ($globals_post) $GLOBALS['post'] = $globals_post;
if ($previous_post) WPO_Page_Cache::delete_cache_by_url(get_permalink($previous_post), true);
if ($next_post) WPO_Page_Cache::delete_cache_by_url(get_permalink($next_post), true);
// delete all archive pages for post.
$post_date = get_post_time('Y-m-j', false, $post_id);
list($year, $month, $day) = $post_date;
$archive_links = array(
get_year_link($year),
get_month_link($year, $month),
get_day_link($year, $month, $day),
);
foreach ($archive_links as $link) {
WPO_Page_Cache::delete_cache_by_url($link, true);
}
} elseif ($post_obj->has_archive) {
// delete archive page for custom post type.
WPO_Page_Cache::delete_cache_by_url(get_post_type_archive_link($post_type), true);
}
}
/**
* We use it with edit_terms action filter to purge cached elements related
* to updated term when term updated.
*
* @param int $term_id Term taxonomy ID.
* @param string $taxonomy Taxonomy slug.
*/
public function purge_related_elements_on_term_updated($term_id, $taxonomy) {
if ('nav_menu' === $taxonomy) return;
// purge cached page for term.
$term = get_term($term_id, $taxonomy, ARRAY_A);
if (is_array($term)) {
$term_permalink = get_term_link($term['term_id']);
if (!is_wp_error($term_permalink)) {
WPO_Page_Cache::delete_cache_by_url($term_permalink, true);
}
}
// get posts which belongs to updated term.
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'any',
'fields' => 'ids',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $term_id,
)
),
));
if (!empty($posts)) {
foreach ($posts as $post_id) {
WPO_Page_Cache::delete_single_post_cache($post_id);
}
}
}
/**
* Triggered by set_object_terms action. Used to clear all the terms archives a post belongs to or belonged to before being saved.
*
* @param int $object_id Object ID.
* @param array $terms An array of object terms.
* @param array $tt_ids An array of term taxonomy IDs.
* @param string $taxonomy Taxonomy slug.
* @param bool $append Whether to append new terms to the old terms.
* @param array $old_tt_ids Old array of term taxonomy IDs.
*/
public function purge_related_elements_on_post_terms_change($object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids) {
$post_type = get_post_type($object_id);
if ((defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) || 'revision' === $post_type || 'product_type' === $taxonomy || 'action-group' === $taxonomy) {
return;
}
/**
* Adds a way to exit the purge of terms permalink using the provided parameters.
*
* @param bool $purge The value filtered, whether or not to purge the related elements
* @param int $object_id Object ID.
* @param array $terms An array of object terms.
* @param array $tt_ids An array of term taxonomy IDs.
* @param string $taxonomy Taxonomy slug.
* @param bool $append Whether to append new terms to the old terms.
* @param array $old_tt_ids Old array of term taxonomy IDs.
* @default true
* @return boolean
*/
if (!apply_filters('wpo_cache_purge_related_elements_on_post_terms_change', true, $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids)) return;
// get all affected terms.
$affected_terms_ids = array_unique(array_merge($tt_ids, $old_tt_ids));
if (!empty($affected_terms_ids)) {
// walk through all changed terms and purge cached pages for them.
foreach ($affected_terms_ids as $tt_id) {
$term = get_term($tt_id, $taxonomy, ARRAY_A);
if (!is_array($term)) continue;
$term_permalink = get_term_link($term['term_id']);
if (!is_wp_error($term_permalink)) {
$url = parse_url($term_permalink);
// Check if the permalink contains a valid path, to avoid deleting the whole cache.
if (!isset($url['path']) || '/' === $url['path']) return;
WPO_Page_Cache::delete_cache_by_url($term_permalink, true);
}
}
}
}
/**
* Purge product page upon stock update
*/
public function purge_product_page($product_with_stock) {
if (!empty($product_with_stock->get_id())) {
WPO_Page_Cache::delete_single_post_cache($product_with_stock->get_id());
}
}
/**
* Clears the cache.
*/
public function purge_cache() {
if (!empty($this->config['enable_page_caching'])) {
wpo_cache_flush();
}
}
/**
* Triggered by wpo_cache_config_updated.
*
* @param array $config
*/
public function cache_config_updated($config) {
// delete front page form cache if defined in the settings
if (is_array($config['cache_exception_urls']) && in_array('/', $config['cache_exception_urls'])) {
WPO_Page_Cache::delete_cache_by_url(home_url());
}
}
/**
* Returns an instance of the current class, creates one if it doesn't exist
*
* @return object
*/
public static function instance() {
if (empty(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
}
endif;

View File

@@ -0,0 +1,55 @@
<?php
if (!defined('ABSPATH')) die('Access denied.');
if (!class_exists('Updraft_Task_1_2')) require_once(WPO_PLUGIN_MAIN_PATH . 'vendor/team-updraft/common-libs/src/updraft-tasks/class-updraft-task.php');
class WP_Optimize_Load_Url_Task extends Updraft_Task_1_2 {
/**
* Default options.
*/
public function get_default_options() {
return array();
}
/**
* Run preload http requests with different user-agent values to cache pages for different devices.
*
* @return bool
*/
public function run() {
$url = $this->get_option('url');
if (empty($url)) return;
$cache_preloader = WP_Optimize_Page_Cache_Preloader::instance();
// load pages with different user-agents values.
$cache_preloader->preload_desktop($url);
$cache_preloader->preload_mobile($url);
$cache_preloader->preload_amp($url);
if (defined('WP_CLI') && WP_CLI) {
WP_CLI::log($url);
}
/**
* Action triggered after preloading a single url
*
* @param string $url The url to preload
* @param object $cache_preloader Cache preloader instance
*/
do_action('wpoptimize_after_preload_url', $url, $cache_preloader);
/**
* Allows to change the delay between each URL preload, to reduce server load.
*
* @param integer $preload_delay The delay between each request in microseconds (1000000 = 1 second).
*/
usleep(apply_filters('wpoptimize_preload_delay', 500000));
return true;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,137 @@
<?php
if (!defined('ABSPATH')) die('No direct access allowed');
/**
* File based page cache drop in
*/
require_once(dirname(__FILE__) . '/file-based-page-cache-functions.php');
if (!defined('WPO_CACHE_DIR')) define('WPO_CACHE_DIR', untrailingslashit(WP_CONTENT_DIR) . '/wpo-cache');
/**
* Load extensions.
*/
wpo_cache_load_extensions();
/**
* Action triggered when the cache extensions are all loaded. Allows to execute code depending on an other extension, without knowing the order in which the files are loaded.
*/
if (function_exists('do_action')) {
do_action('wpo_cache_extensions_loaded');
}
$no_cache_because = array();
// check if we want to cache current page.
if (function_exists('add_filter') && function_exists('apply_filters')) {
add_filter('wpo_restricted_cache_page_type', 'wpo_restricted_cache_page_type');
add_filter('wpo_url_in_conditional_tags_exceptions', 'wpo_url_in_conditional_tags_exceptions');
$restricted_cache_page_type = apply_filters('wpo_restricted_cache_page_type', false);
$conditional_tag_exceptions = wpo_url_in_conditional_tags_exceptions();
} else {
// On old WP versions, you can't filter the result
$restricted_cache_page_type = wpo_restricted_cache_page_type(false);
$conditional_tag_exceptions = wpo_url_in_conditional_tags_exceptions();
}
if ($restricted_cache_page_type) {
$no_cache_because[] = $restricted_cache_page_type;
}
if ($conditional_tag_exceptions) {
$no_cache_because[] = $conditional_tag_exceptions;
}
// Don't cache non-GET requests.
if (!isset($_SERVER['REQUEST_METHOD']) || 'GET' !== $_SERVER['REQUEST_METHOD']) {
$no_cache_because[] = 'The request method was not GET ('.(isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : '-').')';
}
$file_extension = $_SERVER['REQUEST_URI'];
$file_extension = preg_replace('#^(.*?)\?.*$#', '$1', $file_extension);
$file_extension = trim(preg_replace('#^.*\.(.*)$#', '$1', $file_extension));
// Don't cache disallowed extensions. Prevents wp-cron.php, xmlrpc.php, etc.
if (!preg_match('#index\.php$#i', $_SERVER['REQUEST_URI']) && !preg_match('#sitemap([a-zA-Z0-9_-]+)?\.xml$#i', $_SERVER['REQUEST_URI']) && in_array($file_extension, array('php', 'xml', 'xsl'))) {
$no_cache_because[] = 'The request extension is not suitable for caching';
}
// Don't cache if logged in.
if (!empty($_COOKIE)) {
$wp_cookies = array('wordpressuser_', 'wordpresspass_', 'wordpress_sec_', 'wordpress_logged_in_');
if (!wpo_cache_loggedin_users()) {
foreach ($_COOKIE as $key => $value) {
foreach ($wp_cookies as $cookie) {
if (false !== strpos($key, $cookie)) {
$no_cache_because[] = 'WordPress login cookies were detected';
break(2);
}
}
}
}
if (!empty($_COOKIE['wpo_commented_post'])) {
$no_cache_because[] = 'The user has commented on a post (comment cookie set)';
}
// get cookie exceptions from options.
$cache_exception_cookies = !empty($GLOBALS['wpo_cache_config']['cache_exception_cookies']) ? $GLOBALS['wpo_cache_config']['cache_exception_cookies'] : array();
// filter cookie exceptions, since WP 4.6
$cache_exception_cookies = function_exists('apply_filters') ? apply_filters('wpo_cache_exception_cookies', $cache_exception_cookies) : $cache_exception_cookies;
// check if any cookie exists from exception list.
if (!empty($cache_exception_cookies)) {
foreach ($_COOKIE as $key => $value) {
foreach ($cache_exception_cookies as $cookie) {
if ('' != trim($cookie) && false !== strpos($key, $cookie)) {
$no_cache_because[] = 'An excepted cookie was set ('.$key.')';
break 2;
}
}
}
}
}
// check in not disabled current user agent
if (!empty($_SERVER['HTTP_USER_AGENT']) && false === wpo_is_accepted_user_agent($_SERVER['HTTP_USER_AGENT'])) {
$no_cache_because[] = "In the settings, caching is disabled for matches for this request's user agent";
}
// Deal with optional cache exceptions.
if (wpo_url_in_exceptions(wpo_current_url())) {
$no_cache_because[] = 'In the settings, caching is disabled for matches for the current URL';
}
if (!empty($_GET)) {
// get variables used for building filename.
$get_variable_names = wpo_cache_query_variables();
$get_variables = wpo_cache_maybe_ignore_query_variables(array_keys($_GET));
// if GET variables include one or more undefined variable names then we don't cache.
$get_variables_diff = array_diff($get_variables, $get_variable_names);
if (!empty($get_variables_diff)) {
$no_cache_because[] = "In the settings, caching is disabled for matches for one of the current request's GET parameters";
}
}
if (!empty($no_cache_because)) {
$no_cache_because_message = implode(', ', $no_cache_because);
// Add http header
if (!defined('DOING_CRON') || !DOING_CRON) {
wpo_cache_add_nocache_http_header($no_cache_because_message);
}
// Only output if the user has turned on debugging output
if (((defined('WP_DEBUG') && WP_DEBUG) || isset($_GET['wpo_cache_debug'])) && (!defined('DOING_CRON') || !DOING_CRON)) {
wpo_cache_add_footer_output("Page not served from cache because: ".htmlspecialchars($no_cache_because_message));
}
return;
}
wpo_serve_cache();
ob_start('wpo_cache');

View File

@@ -0,0 +1,17 @@
<?php
/**
* Get path to wp-config.php when called from WP-CLI.
*
* @return string
*/
function wpo_wp_cli_locate_wp_config() {
$config_path = '';
if (is_callable('\WP_CLI\Utils\locate_wp_config')) {
// phpcs:ignore PHPCompatibility.LanguageConstructs.NewLanguageConstructs.t_ns_separatorFound
$config_path = \WP_CLI\Utils\locate_wp_config();
}
return $config_path;
}