PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 4.7.0
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v4.7.0
4.7.0 4.6.1 4.6.0 4.5.5 4.5.4 4.5.3 4.5.2 3.2.20 3.2.21 3.2.22 3.2.3 3.2.5 3.2.6 3.2.7 3.2.9 3.3.0 3.3.1 3.3.2 3.4.0 3.4.1 3.4.2 3.5.0 3.6.0 3.7.0 3.7.1 All 111 releases
wp-optimize / cache / class-wp-optimize-page-cache-preloader.php

class-wp-optimize-page-cache-preloader.php in WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance 4.7.0, at cache/class-wp-optimize-page-cache-preloader.php

830 lines 24.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 if (!defined('ABSPATH')) die('No direct access allowed');
4
5 if (!class_exists('WP_Optimize_Load_Url_Task')) {
6 require_once(WPO_PLUGIN_MAIN_PATH . 'cache/class-wpo-load-url-task.php');
7 }
8
9 class WP_Optimize_Page_Cache_Preloader extends WP_Optimize_Preloader {
10
11 /**
12 * @var string
13 */
14 protected $preload_type = 'page_cache';
15
16 /**
17 * @var string
18 */
19 protected $task_type = 'load-url-task';
20
21 /**
22 * @var null | WP_Optimize_Page_Cache_Preloader
23 */
24 static protected $_instance = null;
25
26 /**
27 * List of URLs for which a task will be created to preload them into cache
28 *
29 * @var array
30 */
31 private $url_preload_list = array();
32
33 /**
34 * WP_Optimize_Page_Cache_Preloader constructor.
35 */
36 public function __construct() {
37 parent::__construct();
38
39 add_action('wpo_page_cache_schedule_preload', array($this, 'run_scheduled_cache_preload'));
40 add_action('wpo_page_cache_run_preload', array($this, 'run_preload_cron_job'));
41 add_filter('wpo_preload_headers', array($this, 'preload_headers'));
42 }
43
44 /**
45 * Check if cache is active.
46 *
47 * @return bool
48 */
49 public function is_option_active() {
50 return WP_Optimize()->get_page_cache()->is_enabled();
51 }
52
53 /**
54 * Schedule or delete automatic preload action on cache settings update.
55 *
56 * @param array $new_settings The new settings
57 * @param array $previous_settings Settings before saving
58 */
59 public function cache_settings_updated($new_settings, $previous_settings) {
60 if (!$new_settings['enable_page_caching']) {
61 wp_clear_scheduled_hook('wpo_page_cache_schedule_preload');
62 wp_clear_scheduled_hook('wpo_page_cache_run_preload');
63 $this->delete_preload_continue_action();
64 return;
65 }
66
67 if (!empty($new_settings['enable_schedule_preload'])) {
68
69 $last_schedule_type = $previous_settings['preload_schedule_type'];
70
71 $last_use_nighttime = (int) $this->options->get_option('page_cache_schedule_preload_nighttime');
72 // By default, we schedule preload events to the nighttime.
73 $use_nighttime = apply_filters('wpo_page_cache_schedule_preload_use_nighttime', 1);
74
75 $this->options->update_option('page_cache_schedule_preload_nighttime', $use_nighttime);
76
77 if (wp_next_scheduled('wpo_page_cache_schedule_preload')) {
78 // if already scheduled this schedule type
79 if ($new_settings['preload_schedule_type'] === $last_schedule_type && ($last_use_nighttime === $use_nighttime)) {
80 // If the schedule type is cache lifespan, check if the cache lifespan changed.
81 if ('wpo_use_cache_lifespan' === $new_settings['preload_schedule_type']) {
82 // Else, if the settings cache lifespan settings haven't changed, returns
83 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']) {
84 return;
85 }
86 } else {
87 return;
88 }
89 }
90 // clear currently scheduled preload action.
91 wp_clear_scheduled_hook('wpo_page_cache_schedule_preload');
92 }
93
94 // schedule preload action.
95 $timestamp = time() + $this->get_schedule_interval($new_settings['preload_schedule_type']);
96
97 if ($use_nighttime) {
98 $timestamp = $this->make_nighttime($timestamp);
99 }
100
101 wp_schedule_event($timestamp, $new_settings['preload_schedule_type'], 'wpo_page_cache_schedule_preload');
102 } else {
103 wp_clear_scheduled_hook('wpo_page_cache_schedule_preload');
104 }
105
106 }
107
108 /**
109 * Clear active preload tasks, reschedule preload action.
110 */
111 public function reschedule_preload() {
112 // clear scheduled action.
113 if (wp_next_scheduled('wpo_page_cache_schedule_preload')) {
114 wp_clear_scheduled_hook('wpo_page_cache_schedule_preload');
115 }
116
117 // schedule preload action if need.
118 if ($this->is_scheduled_preload_enabled()) {
119 $preload_schedule_type = $this->get_cache_config('preload_schedule_type');
120 // By default, we schedule preload events to the nighttime.
121 $use_nighttime = apply_filters('wpo_page_cache_schedule_preload_use_nighttime', 1);
122
123 $timestamp = time() + $this->get_schedule_interval($preload_schedule_type);
124 if ($use_nighttime) {
125 $timestamp = $this->make_nighttime($timestamp);
126 }
127
128 wp_schedule_event($timestamp, $preload_schedule_type, 'wpo_page_cache_schedule_preload');
129 }
130 }
131
132 /**
133 * Reschedule preload action on plugin activation if page cache enabled.
134 *
135 * @return void
136 */
137 public function maybe_reschedule_preload_on_activation() {
138 if ($this->get_cache_config('enable_page_caching')) {
139 $this->reschedule_preload();
140 }
141 }
142
143 /**
144 * Check if scheduled preload enabled.
145 *
146 * @return bool
147 */
148 public function is_scheduled_preload_enabled() {
149 $enable_schedule_preload = $this->get_cache_config('enable_schedule_preload');
150 return !empty($enable_schedule_preload);
151 }
152
153 /**
154 * Check if we need run cache preload and run it.
155 */
156 public function run_scheduled_cache_preload() {
157
158 $schedule_type = WPO_Cache_Config::instance()->get_option('preload_schedule_type');
159 if (!$schedule_type) return;
160
161 // Don't run preload if cache lifespan option enabled and cache not expired yet.
162 if ('wpo_use_cache_lifespan' === $schedule_type) {
163
164 /**
165 * Filters the allowed time difference between the cache exiry and the current time, in seconds.
166 * If the cache expires in less than $allowed_time_difference, preload. Otherwise leave it.
167 *
168 * @param integer $allowed_time_difference The time difference, in seconds (default is same as changed time limit)
169 */
170 $time_limit = (defined('WP_OPTIMIZE_SET_TIME_LIMIT') && WP_OPTIMIZE_SET_TIME_LIMIT > 15) ? WP_OPTIMIZE_SET_TIME_LIMIT : 1800;
171
172 $allowed_time_difference = apply_filters('wpo_preload_allowed_time_difference', $time_limit);
173 $page_cache_lifespan = WPO_Cache_Config::instance()->get_option('page_cache_length', 0);
174 $last_preload_time = $this->options->get_option('wpo_last_page_cache_preload', 0);
175 $time_since_last_preload = time() - $last_preload_time;
176 $minimum_time_to_next_schedule_preload = $page_cache_lifespan - $allowed_time_difference;
177 // Skip this if the last preload is not as old as the cache lifespan minus $allowed_time_difference
178 if ($page_cache_lifespan > 0 && $time_since_last_preload < $minimum_time_to_next_schedule_preload) return;
179 }
180
181 $this->run();
182 }
183
184 /**
185 * Runs manual cache preload and reschedules if scheduled preload is enabled
186 *
187 * @return void
188 */
189 public function run_preload_cron_job() {
190 $wpo_page_cache = WP_Optimize()->get_page_cache();
191
192 if ($this->is_scheduled_preload_enabled()) {
193 $this->cancel_preload();
194 $this->reschedule_preload();
195 $this->run('scheduled', null, true);
196 } elseif ($wpo_page_cache->should_auto_preload_purged_contents()) {
197 $this->run('manual', null, true);
198 }
199 }
200
201 /**
202 * Get cache config option value.
203 *
204 * @param string $option
205 *
206 * @return mixed
207 */
208 public function get_cache_config($option) {
209 static $config = null;
210
211 if (null === $config) $config = WPO_Page_Cache::instance()->config->get();
212
213 if (is_array($config) && array_key_exists($option, $config)) {
214 return $config[$option];
215 }
216
217 return false;
218 }
219
220 /**
221 * Create tasks (WP_Optimize_Load_Url_Task) for preload all urls from site.
222 *
223 * @param string $type The preload type (currently: scheduled, manual)
224 * @return void
225 */
226 public function create_tasks_for_preload_site_urls($type) {
227 $urls = $this->get_site_urls();
228
229 if (!empty($urls)) {
230
231 $this->log(__('Creating tasks for preload site urls.', 'wp-optimize'));
232
233 $wpo_cache_specific_urls_only = wpo_cache_specific_urls_only();
234
235 foreach ($urls as $url) {
236 if (!$wpo_cache_specific_urls_only && wpo_url_in_exceptions($url)) continue;
237
238 if ($this->url_is_already_cached($url, $type)) {
239 continue;
240 }
241
242 // this description is being used for internal purposes.
243 $description = 'Preload - '.$url;
244 $options = array('url' => $url, 'preload_type' => $type, 'anonymous_user_allowed' => (defined('DOING_CRON') && DOING_CRON) || (defined('WP_CLI') && WP_CLI));
245
246 WP_Optimize_Load_Url_Task::create_task($this->task_type, $description, $options, 'WP_Optimize_Load_Url_Task');
247 }
248
249 $this->log(__('Tasks for preload site urls created.', 'wp-optimize'));
250 }
251 }
252
253 /**
254 * Preload mobile version from $url.
255 *
256 * @param string $url
257 *
258 * @return void
259 */
260 public function preload_mobile($url) {
261 static $is_mobile_caching_enabled;
262 if (!isset($is_mobile_caching_enabled)) {
263 $is_mobile_caching_enabled = $this->get_cache_config('enable_mobile_caching');
264 }
265
266 // Only run if option is active
267 if (!$is_mobile_caching_enabled) return;
268
269 $mobile_args = array(
270 'httpversion' => '1.1',
271 'user-agent' => WP_Optimize_Utils::get_user_agent('mobile'),
272 'timeout' => 10,
273 'headers' => apply_filters('wpo_preload_headers', array()),
274 );
275
276 $mobile_args = apply_filters('wpo_page_cache_preloader_mobile_args', $mobile_args, $url);
277
278 $this->log('preload_mobile - ' . $url);
279
280 wp_remote_get($url, $mobile_args);
281 }
282
283 /**
284 * Preload amp version from $url.
285 *
286 * @param string $url
287 *
288 * @return void
289 */
290 public function preload_amp($url) {
291 if (!apply_filters('wpo_should_preload_amp', false, $url)) return;
292
293 $amp_args = array(
294 'httpversion' => '1.1',
295 'user-agent' => WP_Optimize_Utils::get_user_agent(),
296 'timeout' => 10,
297 'headers' => array(
298 'X-WP-Optimize-Cache-Preload' => 'Yes',
299 ),
300 );
301
302 $url = untrailingslashit($url) . '/amp/';
303
304 $amp_args = apply_filters('wpo_page_cache_preloader_amp_args', $amp_args, $url);
305
306 $this->log('preload_amp - ' . $url);
307
308 wp_remote_get($url, $amp_args);
309 }
310
311 /**
312 * Check if sitemap exists then returns list of urls from sitemap file otherwise returns all posts urls.
313 *
314 * @return array
315 */
316 public function get_site_urls() {
317
318 $urls = $this->get_sitemap_urls();
319
320 if (!empty($urls)) {
321 $this->options->update_option('wpo_last_page_cache_preload_type', 'sitemap');
322 } else {
323 $urls = $this->get_post_urls();
324 $this->options->update_option('wpo_last_page_cache_preload_type', 'posts');
325 }
326
327 // translators: %d: Number of URLs found
328 $this->log(sprintf(_n('%d url found.', '%d urls found.', count($urls), 'wp-optimize'), count($urls)));
329
330 /**
331 * Filter the URLs which will be preloaded
332 *
333 * @param array $urls
334 * @return array
335 */
336 $filtered_urls = apply_filters('wpo_preload_get_site_urls', $urls);
337 return is_array($filtered_urls) ? $filtered_urls : $urls;
338 }
339
340 /**
341 * Loads sitemap file and returns list of urls.
342 *
343 * @param string $sitemap_url
344 *
345 * @return array|bool
346 */
347 public function get_sitemap_urls($sitemap_url = '') {
348
349 $urls = array();
350
351 // if sitemap url is empty then use main sitemap file name.
352 $sitemap_url = ('' === $sitemap_url) ? site_url('/'.$this->get_sitemap_filename()) : $sitemap_url;
353
354 // if simplexml_load_string not available then we don't load sitemap.
355 if (!function_exists('simplexml_load_string')) {
356 return $urls;
357 }
358
359 // load sitemap file.
360 $response = wp_remote_get($sitemap_url, array('timeout' => 30));
361
362 // if we get error then
363 // sometimes returns error due to timeout
364 if (is_wp_error($response)) {
365 $response = @file_get_contents($sitemap_url); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- suppress warnings when there is network error
366
367 // if response is empty then try load from file.
368 if (empty($response)) {
369 $sitemap_file = $this->get_local_sitemap_file();
370
371 if (is_file($sitemap_file)) {
372 $response = file_get_contents($sitemap_file);
373 }
374 }
375
376 if (empty($response)) return $urls;
377
378 $xml = @simplexml_load_string($response); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- suppress warnings when error found in XML data
379 } else {
380 // parse xml answer.
381 $xml = @simplexml_load_string(wp_remote_retrieve_body($response)); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- suppress warnings when error found in XML data
382 }
383
384 // xml file has not valid xml content then return false.
385 if (false === $xml) return false;
386
387 // if exists urls then return them.
388 if (isset($xml->url)) {
389 foreach ($xml->url as $element) {
390 if (!isset($element->loc)) continue;
391 $urls[] = (string) $element->loc;
392 }
393 } elseif (isset($xml->sitemap)) {
394 // if has links to other sitemap files then get urls from them.
395 foreach ($xml->sitemap as $element) {
396 if (!isset($element->loc)) continue;
397
398 $sitemap_urls = $this->get_sitemap_urls($element->loc);
399
400 if (is_array($sitemap_urls)) {
401 $urls = array_merge($urls, $sitemap_urls);
402 }
403 }
404 }
405
406 return $urls;
407 }
408
409 /**
410 * Get all posts of any post type and returns urls for them.
411 *
412 * @return array
413 */
414 public function get_post_urls() {
415 global $post;
416
417 $offset = 0;
418 $posts_per_page = 1000;
419 $urls = array();
420
421 $urls[] = site_url('/');
422
423 do {
424 $query = new WP_Query(array(
425 'post_type' => 'any',
426 'post_status' => 'publish',
427 'posts_per_page' => $posts_per_page,
428 'offset' => $offset,
429 'orderby' => 'ID',
430 'order' => 'ASC',
431 'cache_results' => false, // disable cache to avoid memory error.
432 ));
433
434 $posts_loaded = $query->post_count;
435
436 while ($query->have_posts()) {
437 $query->the_post();
438 $permalink = get_permalink();
439 $urls[] = $permalink;
440
441 // check page separators in the post content
442 preg_match_all('/\<\!--nextpage--\>/', $post->post_content, $matches);
443 // if there any separators add urls for each page
444 if (count($matches[0])) {
445 $prefix = strpos($permalink, '?') ? '&page=' : '';
446 for ($page = 0; $page < count($matches[0]); $page++) {
447 if ('' !== $prefix) {
448 $urls[] = $permalink . $prefix . ($page+2);
449 } else {
450 $urls[] = trailingslashit($permalink) . ($page+2);
451 }
452 }
453 }
454 }
455
456 $offset += $posts_loaded;
457 } while ($posts_loaded > 0);
458
459 /**
460 * If domain mapping enabled then replace domains in urls.
461 */
462 if ($this->is_domain_mapping_enabled()) {
463 $blog_id = get_current_blog_id();
464
465 $mapped_domain = $this->get_mapped_domain($blog_id);
466 $blog_details = get_blog_details($blog_id);
467
468 if ($mapped_domain) {
469 foreach ($urls as $i => $url) {
470 $urls[$i] = preg_replace('/'.$blog_details->domain.'/i', $mapped_domain, $url, 1);
471 }
472 }
473 }
474
475 wp_reset_postdata();
476
477 return $urls;
478 }
479
480 /**
481 * Check if domain mapping enabled.
482 *
483 * @return bool
484 */
485 public function is_domain_mapping_enabled() {
486 // SUNRISE constant is defined with installation WordPress MU Domain Mapping plugin.
487 $enabled = is_multisite() && defined('SUNRISE') && 'on' === strtolower(SUNRISE);
488
489 /**
490 * Filters if Multisite Domain mapping is enabled.
491 * Currently, we can only detect if the WordPress MU Domain Mapping plugin is in use.
492 * Using the WP Core functionality should not require this, unless if the domain name is set somewhere else but in the site url option.
493 */
494 return apply_filters('wpo_is_domain_mapping_enabled', $enabled);
495 }
496
497 /**
498 * Return mapped domain by $blog_id.
499 *
500 * @param int $blog_id
501 *
502 * @return string
503 */
504 public function get_mapped_domain($blog_id) {
505 global $wpdb;
506
507 $domain = '';
508 $multisite_plugin_table_name = $wpdb->base_prefix.'domain_mapping';
509 // Check if table exists
510 if ($wpdb->get_var("SHOW TABLES LIKE '" . esc_sql($multisite_plugin_table_name) . "'") !== $multisite_plugin_table_name) {
511 // This table created in WordPress MU Domain Mapping plugin.
512 $row = $wpdb->get_row($wpdb->prepare("SELECT `domain` FROM " .esc_sql($multisite_plugin_table_name) . " WHERE `blog_id` = %d AND `active` = %d", $blog_id, 1), ARRAY_A);
513 if (!empty($row)) {
514 $domain = $row['domain'];
515 }
516 } else {
517 // When using the WP Core method, the site url option contains the mapped domain.
518 $domain = get_site_url($blog_id);
519 }
520
521 /**
522 * Filters the mapped domain name
523 *
524 * @param string $domain The domain name
525 * @param integer $blog_id The blog ID
526 */
527 return apply_filters('wpo_get_mapped_domain', $domain, $blog_id);
528 }
529
530 /**
531 * Actually add the URLs to be preloaded into cache during `shutdown` hook
532 *
533 * @return void
534 */
535 public function create_tasks_for_auto_preload_urls() {
536 $wpo_cache_specific_urls_only = wpo_cache_specific_urls_only();
537 foreach ($this->url_preload_list as $url) {
538 if (!$wpo_cache_specific_urls_only && wpo_url_in_exceptions($url)) continue;
539
540 $description = 'Preload - '.$url;
541 $options = array('url' => $url, 'preload_type' => 'manual', 'anonymous_user_allowed' => (defined('DOING_CRON') && DOING_CRON) || (defined('WP_CLI') && WP_CLI));
542
543 WP_Optimize_Load_Url_Task::create_task($this->task_type, $description, $options, 'WP_Optimize_Load_Url_Task');
544 }
545
546 $this->run('manual', null, true);
547 }
548
549 /**
550 * Prepare the URL list that will need to be tasked to be preloaded
551 *
552 * @param string $url The URL to be preloaded
553 * @return void
554 */
555 public function add_url_to_preload_list($url) {
556 $this->url_preload_list[] = $url;
557 }
558
559 /**
560 * Captures and logs any interesting messages
561 *
562 * @param string $message - the error message
563 * @param string $error_type - the error type
564 */
565 public function log($message, $error_type = 'info') {
566
567 if (isset($this->loggers)) {
568 foreach ($this->loggers as $logger) {
569 $logger->log($message, $error_type);
570 }
571 }
572 }
573
574 /**
575 * Instance of WP_Optimize_Page_Cache_Preloader.
576 *
577 * @return WP_Optimize_Page_Cache_Preloader
578 */
579 public static function instance() {
580 if (empty(self::$_instance)) {
581 self::$_instance = new WP_Optimize_Page_Cache_Preloader();
582 }
583
584 return self::$_instance;
585 }
586
587 /**
588 * Check if the URL is already cached, or needs to be preloaded
589 *
590 * @param string $url The preloaded url
591 * @param string $preload_type The preload type (manual | scheduled)
592 * @return boolean
593 */
594 private function url_is_already_cached($url, $preload_type) {
595 static $files = array();
596 $regenerate_count = 0;
597 $folder = trailingslashit(WPO_CACHE_FILES_DIR) . wpo_get_url_path($url);
598 // If the folder does not exist, consider the URL as cleared
599 if (!is_dir($folder)) return false;
600
601 if (empty($files)) {
602 // Check only the base files
603 $files[] = 'index.html';
604
605 if (WPO_Cache_Config::instance()->get_option('enable_mobile_caching')) {
606 $files[] = 'mobile.index.html';
607 }
608 $files = apply_filters('wpo_maybe_clear_files_list', $files);
609 }
610
611 foreach ($files as $file) {
612 $file_path = trailingslashit($folder).$file;
613 if (!file_exists($file_path)) {
614 // The file does not exist, count it as "deleted"
615 $regenerate_count++;
616 continue;
617 }
618
619 if ($this->should_regenerate_file($file_path, $preload_type)) {
620 // delete the expired cache file
621 wp_delete_file($file_path);
622 $regenerate_count++;
623 }
624 }
625
626 // if 0 == $regenerate_count, nothing all the expected files exist, and none were deleted.
627 return 0 === $regenerate_count;
628 }
629
630 /**
631 * Determine if a file should be regenerated
632 *
633 * @param string $path The file to check
634 * @param string $preload_type The preload type (manual | scheduled)
635 *
636 * @return boolean
637 */
638 private function should_regenerate_file($path, $preload_type) {
639 // Store the variables, as they'll be used for each file and each file
640 static $is_preloader_scheduled = null;
641 static $lifespan = null;
642 static $schedule_type = null;
643 static $schedule_interval = null;
644 static $lifespan_expiry_threshold = null;
645 static $always_regenerate_file_if_preload_is_manual = null;
646 static $always_regenerate_file_if_preload_is_scheduled = null;
647 static $regenerate_file_when_no_expiry_date = null;
648
649 // Sets the variables once per request:
650 if (null === $is_preloader_scheduled) {
651 $is_preloader_scheduled = WPO_Cache_Config::instance()->get_option('enable_schedule_preload');
652 $schedule_type = WPO_Cache_Config::instance()->get_option('preload_schedule_type');
653 $lifespan = (int) WPO_Cache_Config::instance()->get_option('page_cache_length');
654 $schedule_interval = $this->get_schedule_interval($schedule_type);
655
656 /**
657 * Expiry threshold: the current file will be considered stale if within the threshold. Default: 600s (10min)
658 */
659 $lifespan_expiry_threshold = apply_filters('wpo_lifespan_expiry_threshold', 600);
660
661 /**
662 * Filters if a cache should systematically be regenerated when running a manual preload. Default: false
663 */
664 $always_regenerate_file_if_preload_is_manual = apply_filters('wpo_always_regenerate_file_if_preload_is_manual', false);
665
666 /**
667 * Filters if a cache should systematically be regenerated when running a scheduled preload. Default: false
668 */
669 $always_regenerate_file_if_preload_is_scheduled = apply_filters('wpo_always_regenerate_file_if_preload_is_scheduled', false);
670
671 /**
672 * Filters if a cache should systematically be regenerated when running a preload and no schedule is set, and cache does not expire. Default: true
673 */
674 $regenerate_file_when_no_expiry_date = apply_filters('wpo_regenerate_file_when_no_expiry_date', true);
675 }
676
677 if (($always_regenerate_file_if_preload_is_manual && 'manual' === $preload_type) || ($always_regenerate_file_if_preload_is_scheduled && 'scheduled' === $preload_type)) {
678 $result = true;
679 } else {
680
681 $modified_time = (int) filemtime($path);
682
683 // cache lifespan is set.
684 if (0 !== $lifespan) {
685 $expiry_time = $modified_time + $lifespan - $lifespan_expiry_threshold;
686 $result = time() > $expiry_time;
687 } elseif ($is_preloader_scheduled) {
688 $expiry_time = $modified_time + $schedule_interval - $lifespan_expiry_threshold;
689 $result = time() > $expiry_time;
690 } else {
691 $result = $regenerate_file_when_no_expiry_date;
692 }
693
694 }
695
696 return apply_filters('wpo_preloader_should_regenerate_file', $result, $path, $preload_type);
697 }
698
699 /**
700 * Add preloader headers
701 *
702 * @param array $headers Preload headers
703 */
704 public function preload_headers($headers) {
705 $headers['X-WP-Optimize-Cache-Preload'] = 'Yes';
706 return $headers;
707 }
708
709 /**
710 * Option disabled error message
711 *
712 * @return array
713 */
714 protected function get_option_disabled_error() {
715 return array(
716 'success' => false,
717 'error' => __('Page cache is disabled.', 'wp-optimize')
718 );
719 }
720
721 /**
722 * Get preload already running error message
723 *
724 * @return array
725 */
726 protected function get_preload_already_running_error() {
727 return array(
728 'success' => false,
729 'error' => __('Probably page cache preload is running already.', 'wp-optimize')
730 );
731 }
732
733 /**
734 * Returns preload data
735 *
736 * @return array
737 */
738 protected function get_preload_data() {
739 return WP_Optimize()->get_page_cache()->get_cache_size();
740 }
741
742 /**
743 * Returns preloading message
744 *
745 * @param array $cache_size
746 *
747 * @return array
748 */
749 protected function get_preloading_message($cache_size) {
750 return array(
751 'done' => false,
752 'message' => __('Loading URLs...', 'wp-optimize'),
753 'size' => WP_Optimize()->format_size($cache_size['size']),
754 'file_count' => $cache_size['file_count']
755 );
756 }
757
758 /**
759 * Returns last preload message
760 *
761 * @param array $cache_size
762 * @param string $last_preload_time_str
763 *
764 * @return array
765 */
766 protected function get_last_preload_message($cache_size, $last_preload_time_str) {
767 return array(
768 'done' => true,
769 // translators: %s is the last preload time
770 'message' => sprintf(__('Last preload finished at %s', 'wp-optimize'), $last_preload_time_str),
771 'size' => WP_Optimize()->format_size($cache_size['size']),
772 'file_count' => $cache_size['file_count']
773 );
774 }
775
776 /**
777 * Returns preload success message
778 *
779 * @param array $cache_size
780 *
781 * @return array
782 */
783 protected function get_preload_success_message($cache_size) {
784 return array(
785 'done' => true,
786 'size' => WP_Optimize()->format_size($cache_size['size']),
787 'file_count' => $cache_size['file_count']
788 );
789 }
790
791 /**
792 * Returns preload progress message
793 *
794 * @param array $cache_size
795 * @param string $preloaded_message
796 * @param int $preload_resuming_in
797 *
798 * @return array
799 */
800 protected function get_preload_progress_message($cache_size, $preloaded_message, $preload_resuming_in) {
801 return array(
802 'done' => false,
803 'message' => $preloaded_message,
804 'size' => WP_Optimize()->format_size($cache_size['size']),
805 'file_count' => $cache_size['file_count'],
806 'resume_in' => $preload_resuming_in
807 );
808 }
809
810 /**
811 * Shifts the given timestamp to nighttime.
812 *
813 * @param int $time
814 *
815 * @return int
816 */
817 private function make_nighttime($time) {
818
819 $gmt_offset = WP_Optimize_Utils::get_gmt_offset();
820
821 // Set time to random time from 1 a.m. to 4:59 a.m.
822 $random_time = sprintf('%02d:%02d', wp_rand(1, 4), wp_rand(0, 59));
823 $nighttime = strtotime(gmdate("Y-m-d {$random_time}:00", $time)) - $gmt_offset;
824
825 if ($nighttime < time()) $nighttime += 24 * 3600;
826
827 return $nighttime;
828 }
829 }
830