PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 4.5.3
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v4.5.3
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.5.3, at cache/class-wp-optimize-page-cache-preloader.php

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