PluginProbe
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript / 1.9.3
BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript v1.9.3
4.1.16 4.1.15 4.1.14 4.1.13 4.1.12 4.1.11 4.1.10 4.0.30 4.0.29 4.0.28 4.0.27 4.0.26 4.0.24 4.0.25 4.0.23 4.0.22 4.0.21 4.0.19 4.0.18 4.0.17 4.0.16 1.9.3 1.9.4 1.9.5 1.9.6 All 170 releases
searchpro / inc / class-berqcache.php

class-berqcache.php in BerqWP – All-In-One Optimization for Core Web Vitals, Cache, CDN, Images, CSS & JavaScript 1.9.3, at inc/class-berqcache.php

835 lines 30.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 if (!defined('ABSPATH'))
3 exit;
4
5 if (!class_exists('berqCache')) {
6 class berqCache
7 {
8 public $cache_file;
9 public $max_page_per_batch = 5;
10
11 function __construct()
12 {
13 $this->max_page_per_batch = apply_filters( 'berqwp_max_pages_per_batch', 5 );
14
15 add_filter( 'berqwp_ignored_urls_params', [$this, 'ingore_tracking_params'] );
16
17 // $this->cache_file = berqwp_current_page_cache_file();
18
19 // clear cache after migration
20 if (get_option('berqwp_site_url', home_url()) !== home_url()) {
21
22 if (get_option('berqwp_site_url', home_url()) !== null) {
23 global $berq_log;
24 $berq_log->info('Home url change detected, flushing all cache');
25 }
26
27 $this->delete_cache_files();
28 update_option('berqwp_site_url', home_url());
29 delete_transient( 'berq_lic_response_cache' );
30 }
31
32 global $berqwp_is_dropin;
33 if (empty($berqwp_is_dropin)) {
34 add_action('wp', [$this, 'html_cache'], 2);
35 }
36
37 // Add clear cache link to admin bar
38 add_action('admin_bar_menu', [$this, 'add_clear_cache_link_to_admin_bar'], 999);
39
40 // Flush cache
41 add_action('admin_post_clear_cache', [$this, 'handle_clear_cache_action']);
42
43 // Purge a page cache
44 add_action('admin_post_berq_purge_page', [$this, 'handle_berq_purge_page_action']);
45
46 // Request page cache
47 add_action('admin_post_berq_request_cache', [$this, 'handle_berq_request_cache_action']);
48
49 // Clear page cache on update
50 add_action('save_post', [$this, 'clear_cache_on_post_udpate'], 10, 3);
51
52 // Automatic cache warmup
53 add_action('init', [$this, 'warmup_queue']);
54 add_action('warmup_cache_by_slug', [$this, 'handle_warmup_cache_by_slug']);
55 add_action('warmup_cache_quickly', 'warmup_cache_by_slug');
56 add_action('admin_notices', [$this, 'cache_warmup_admin_notice']);
57
58
59 // add_action('wp_loaded', [$this, 'berqwp_warmup_cache_all_pages']);
60
61 add_action('berqwp_before_update_optimization_mode', [$this, 'delete_cache_files']);
62
63 // Reverse proxy cache support
64 add_action('berqwp_stored_page_cache', [$this, 'flush_reverse_proxy_cache']);
65 add_action('berqwp_flush_all_cache', [$this, 'flush_reverse_proxy_cache']);
66 add_action('berqwp_flush_page_cache', [$this, 'flush_reverse_proxy_cache']);
67
68 // Clear cache warmup lock after storing the cache
69 add_action('berqwp_stored_page_cache', 'bwp_clear_warmup_lock');
70
71 add_action('init', [$this, 'bypass_cache']);
72
73
74 }
75
76 function bypass_cache() {
77 if (isset($_GET['generating_critical_css'])
78 || isset($_GET['nocache'])
79 || isset($_GET['creating_cache']) ||
80 (get_option('berqwp_enable_sandbox') == 1 && !isset($_GET['berqwp']) && !is_admin() && !isset($_POST))) {
81
82 add_filter( 'berqwp_bypass_cache', function () { return true; } );
83
84 // if (berqReverseProxyCache::is_reverse_proxy_cache_enabled()) {
85 berqReverseProxyCache::bypass();
86 // }
87
88 }
89 }
90
91 function flush_reverse_proxy_cache($slug = '/.*') {
92
93 if (empty($slug)) {
94 $slug = '/.*'; // Purge all cache
95 }
96
97 if ($slug == '/') {
98 $slug = '';
99 }
100
101 $page_url = home_url() . $slug;
102 berqReverseProxyCache::purge_cache($page_url);
103 }
104
105 function ingore_tracking_params($tracking_params) {
106 $tracking_params = array_merge($tracking_params, ignoreParams::$query_params);
107 return $tracking_params;
108 }
109
110 function berqwp_warmup_cache_all_pages()
111 {
112
113 if (isset($_GET['run_warmup'])) {
114
115 global $berq_log;
116 $berq_log->info('* * * * * * * * * * * * *');
117 $berq_log->info('* Manual Cache Warmup');
118 $berq_log->info('* * * * * * * * * * * * *');
119
120 // Get all published pages and posts
121 $args = array(
122 'post_type' => array('page'),
123 'post_status' => 'publish',
124 'posts_per_page' => -1, // Get all posts
125 );
126 $query = new WP_Query($args);
127
128 // API endpoint URL
129 $api_endpoint = 'https://boost.berqwp.com/photon/';
130
131 if (get_site_url() == 'http://berq-test.local') {
132 $api_endpoint = 'http://dev-berqwp.local/photon/';
133 }
134
135 $httpMulti = new bwp_multi_http();
136
137
138 // Loop through each post/page and warm up the cache
139 if ($query->have_posts()) {
140 while ($query->have_posts()) {
141 $query->the_post();
142 $url = trailingslashit(get_permalink()); // Get the permalink of the post/page
143
144 // $httpMulti->addRequest('GET', $url);
145 $slug = str_replace(home_url(), '', $url);
146 $post_data = berqwp_get_page_params($slug, true);
147
148 $httpMulti->addRequest('POST', $api_endpoint, $post_data);
149
150 $berq_log->info("Requesting cache for $slug");
151 }
152 }
153
154 $responses = $httpMulti->execute();
155 wp_reset_postdata();
156
157 }
158
159 }
160
161 function warmup_queue()
162 {
163 $wp_content_adv_cache = ABSPATH . 'wp-content/advanced-cache.php';
164 $bwp_adv_cache = optifer_PATH . 'advanced-cache.php';
165
166 if (
167 (!file_exists($wp_content_adv_cache) && get_option('berqwp_enable_sandbox') !== 1)
168 || (file_exists($wp_content_adv_cache) && md5_file($wp_content_adv_cache) !== md5_file($bwp_adv_cache))
169 ) {
170 // Specify the drop-in file path
171 $dropin_file = ABSPATH . 'wp-content/advanced-cache.php';
172
173 // Dynamically create the drop-in file
174 $dropin_content = file_get_contents(optifer_PATH . 'advanced-cache.php');
175
176 // Write the drop-in content to the file, replacing any existing file
177 file_put_contents($dropin_file, $dropin_content);
178
179 // Enable object cache in wp-config.php
180 berqwp_enable_object_cache(true);
181
182 if (function_exists('wp_cache_flush')) {
183 wp_cache_flush(); // Clear the entire object cache.
184 }
185 }
186
187 if (get_option('berqwp_enable_sandbox') == 1 && file_exists($wp_content_adv_cache)) {
188 unlink($wp_content_adv_cache);
189 }
190
191 if (false === as_has_scheduled_action('warmup_cache_by_slug')) {
192 $post_types = get_option('berqwp_optimize_post_types');
193
194 $args = array(
195 'post_type' => $post_types,
196 'posts_per_page' => -1,
197 'fields' => 'ids',
198 'post_status' => 'publish',
199 );
200
201 $query = new WP_Query($args);
202
203 // Calculate the total number of pages
204 $total_posts = count($query->posts);
205
206 $posts_per_batch = $this->max_page_per_batch;
207 $total_pages = ceil($total_posts / $posts_per_batch);
208
209
210 // Schedule the events
211 for ($page = 1; $page <= $total_pages; $page++) {
212 as_schedule_single_action(time() + (80 * $page), 'warmup_cache_by_slug', array($page));
213 }
214
215 wp_reset_postdata();
216 }
217
218 if (false === as_has_scheduled_action('warmup_cache_quickly') && (bwp_is_home_cached() === false || bwp_is_partial_cache('/')) && function_exists('as_enqueue_async_action')) {
219 as_enqueue_async_action('warmup_cache_quickly', ['/', true]);
220 }
221
222
223
224 }
225
226 function can_send_warmup_request()
227 {
228 $requests_sent = get_transient('berqwp_warmup_requests_count');
229
230 // If we haven't set the rate limiting transient yet, or if we're still below our rate, return true.
231 if (false === $requests_sent || $requests_sent < BERQWP_MAX_WARMUP_REQUESTS) {
232 return true;
233 }
234
235 return false;
236 }
237
238 function update_warmup_request_count()
239 {
240 $requests_sent = get_transient('berqwp_warmup_requests_count');
241
242 if (false === $requests_sent) {
243 // If this is the first request in our window, set the transient with a timeout.
244 set_transient('berqwp_warmup_requests_count', 1, BERQWP_WARMUP_RATE_LIMIT_WINDOW);
245 } else {
246 // Otherwise, just increment the counter.
247 set_transient('berqwp_warmup_requests_count', ++$requests_sent, BERQWP_WARMUP_RATE_LIMIT_WINDOW);
248 }
249 }
250
251
252
253 function handle_warmup_cache_by_slug($page)
254 {
255 global $berq_log;
256 $berq_log->info("handle_warmup_cache_by_slug triggered");
257
258 // error_log('-page-' . $page);
259 if ($this->can_send_warmup_request()) {
260 // error_log('page-' . $page);
261 $this->warmup_cache($page);
262 $this->update_warmup_request_count();
263 } else {
264 $berq_log->info("handle_warmup_cache_by_slug cache skipped");
265 // You've hit the rate limit.
266 $retry_after_seconds = 200; // Retry after 10 minutes. You can adjust this time as needed.
267 // as_schedule_single_action(time() + $retry_after_seconds, 'warmup_cache_by_slug', array($page));
268 }
269 }
270
271
272
273 function clear_cache_on_post_udpate($post_id, $post, $update)
274 {
275 // If this is just a revision, don't run the function.
276 if (wp_is_post_revision($post_id)) {
277 return;
278 }
279
280 $post_url = get_permalink($post_id);
281 $slug = str_replace(home_url(), '', $post_url);
282 $cache_key = md5($slug);
283 $cache_directory = optifer_cache . '/html/';
284 $cache_file = $cache_directory . $cache_key . '.html';
285
286 global $berq_log;
287 $berq_log->info("Post updated, deleting cache for $post_url");
288
289 if (file_exists($cache_file)) {
290 unlink($cache_file);
291 }
292
293 }
294
295 function flatten_array($array)
296 {
297 $result = array();
298 foreach ($array as $item) {
299 if (is_array($item)) {
300 $result = array_merge($result, $this->flatten_array($item));
301 } else {
302 $result[] = $item;
303 }
304 }
305 return $result;
306 }
307
308 function handle_berq_purge_page_action()
309 {
310 // Check if the user has the necessary nonce and the action matches
311 if (isset($_GET['action']) && $_GET['action'] === 'berq_purge_page' && wp_verify_nonce($_GET['_wpnonce'], 'berq_purge_page_action')) {
312
313 $slug = sanitize_text_field($_GET['uri']);
314 $cache_file = optifer_cache . '/html/' . md5($slug) . '.html';
315
316 if (is_file($cache_file)) {
317 unlink($cache_file);
318 }
319
320 $cache_file = optifer_cache . '/html/' . md5($slug) . '.gz';
321
322 if (is_file($cache_file)) {
323 unlink($cache_file);
324 }
325
326
327 if (function_exists('wp_cache_flush')) {
328 wp_cache_flush(); // Clear the entire object cache.
329 }
330
331 do_action('berqwp_flush_page_cache', $slug);
332
333 // Redirect back to the referring page after clearing the cache
334 wp_safe_redirect(wp_get_referer());
335 exit;
336 }
337 }
338
339 function handle_berq_request_cache_action()
340 {
341 // Check if the user has the necessary nonce and the action matches
342 if (isset($_GET['action']) && $_GET['action'] === 'berq_request_cache' && wp_verify_nonce($_GET['_wpnonce'], 'berq_request_cache_action')) {
343
344 $slug = sanitize_text_field($_GET['uri']);
345
346 as_enqueue_async_action('warmup_cache_quickly', [$slug, true]);
347
348 // Redirect back to the referring page after clearing the cache
349 wp_safe_redirect(wp_get_referer());
350 exit;
351 }
352 }
353
354 function handle_clear_cache_action()
355 {
356 // Check if the user has the necessary nonce and the action matches
357 if (isset($_GET['action']) && $_GET['action'] === 'clear_cache' && wp_verify_nonce($_GET['_wpnonce'], 'clear_cache_action')) {
358 // Call your custom cache clearing function here
359 $this->delete_cache_files();
360
361 if (function_exists('wp_cache_flush')) {
362 wp_cache_flush(); // Clear the entire object cache.
363 }
364
365 set_transient('berq_cache_cleared_notice', 'true', 60);
366
367 $redirect_url = add_query_arg('berq_clear_cache', '', wp_get_referer());
368
369 // Redirect back to the referring page after clearing the cache
370 wp_safe_redirect($redirect_url);
371 exit;
372 }
373 }
374
375 function delete_cache_files()
376 {
377 global $berq_log;
378 $berq_log->info("Flushing all cache.");
379
380 // Define the cache directory
381 $cache_directory = optifer_cache . '/html/';
382
383 // Delete all cache files within the directory
384 berqwp_unlink_recursive($cache_directory);
385
386 // $files = glob($cache_directory . '*.html');
387 // foreach ($files as $file) {
388 // if (is_file($file)) {
389 // unlink($file);
390 // }
391 // }
392
393 delete_transient('berqwp_warmup_running');
394 delete_transient('cache_warmup_in_progress');
395 delete_transient('berqwp_doing_cache_warmup');
396
397 do_action('berqwp_flush_all_cache');
398 // do_action('rt_nginx_helper_purge_all');
399 }
400
401 function add_clear_cache_link_to_admin_bar()
402 {
403 global $wp_admin_bar;
404
405 // Check if the user has the capability to clear the cache (adjust the capability as needed)
406 if (current_user_can('manage_options')) {
407 $wp_admin_bar->add_menu(
408 array(
409 'id' => 'berqWP',
410 'title' => 'BerqWP',
411 'href' => get_admin_url() . '/admin.php?page=berqwp',
412 )
413 );
414
415 // Add the sub-menu item
416 $wp_admin_bar->add_menu(
417 array(
418 'parent' => 'berqWP',
419 // ID of the parent menu item
420 'id' => 'flush-cache',
421 'title' => 'Flush cache',
422 'href' => wp_nonce_url(admin_url('admin-post.php?action=clear_cache'), 'clear_cache_action'),
423 'meta' => array(
424 'class' => 'clear-cache-link',
425 'title' => 'Clear BerqWP cache',
426 ),
427 )
428 );
429
430 if (!is_admin()) {
431 // Add the sub-menu item
432 $wp_admin_bar->add_menu(
433 array(
434 'parent' => 'berqWP',
435 // ID of the parent menu item
436 'id' => 'purge-page',
437 'title' => 'Purge this page',
438 'href' => wp_nonce_url(admin_url('admin-post.php?action=berq_purge_page&uri=' . urlencode($_SERVER['REQUEST_URI'])), 'berq_purge_page_action'),
439 'meta' => array(
440 'class' => 'purge-page-link',
441 'title' => 'Clear this page cache',
442 ),
443 )
444 );
445
446 // Add the request cache
447 $wp_admin_bar->add_menu(
448 array(
449 'parent' => 'berqWP',
450 // ID of the parent menu item
451 'id' => 'request-page-cache',
452 'title' => 'Request cache',
453 'href' => wp_nonce_url(admin_url('admin-post.php?action=berq_request_cache&uri=' . urlencode($_SERVER['REQUEST_URI'])), 'berq_request_cache_action'),
454 'meta' => array(
455 'class' => 'request-page-cache-link',
456 'title' => 'Request cache for this page',
457 ),
458 )
459 );
460
461 }
462 }
463 }
464
465 static function is_cache_file_expired($cache_file) {
466 $cache_max_life = filemtime($cache_file) + (18 * 60 * 60);
467
468 // is still valide
469 if ($cache_max_life > time()) {
470 return false;
471 }
472
473 return true;
474 }
475
476
477 function html_cache()
478 {
479 // Check if the current user is logged in or if it's a POST request
480 if (is_user_logged_in() || $_SERVER['REQUEST_METHOD'] === 'POST') {
481 return;
482 }
483
484 if (is_admin()) {
485 return;
486 }
487
488 if (defined('DOING_CRON') && DOING_CRON) {
489 return;
490 }
491
492 if (defined('DOING_AJAX') && DOING_AJAX) {
493 return;
494 }
495
496 if (defined('REST_REQUEST') && REST_REQUEST) {
497 return;
498 }
499
500 if (php_sapi_name() === 'cli' || defined('WP_CLI')) {
501 return;
502 }
503
504 $bypass_cache = apply_filters( 'berqwp_bypass_cache', false );
505
506 if ($bypass_cache) {
507 return;
508 }
509
510 $slug_uri = $_SERVER['REQUEST_URI'];
511
512 // if wordpress is installed in a sub directory
513 if (berqwp_is_sub_dir_wp()) {
514 // Parse strings to extract paths
515 $path1 = explode('/', parse_url(home_url(), PHP_URL_PATH));
516 $path2 = explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
517
518 // Find the common part of the paths
519 $commonPath = implode('/', array_intersect($path1, $path2));
520
521 // Subtract the common part from the first string
522 $slug_uri = str_replace($commonPath, '', $_SERVER['REQUEST_URI']);
523 }
524
525 // Return if page is excluded from cache
526 $pages_to_exclude = get_option('berq_exclude_urls', []);
527
528 if (in_array(home_url() . $slug_uri, $pages_to_exclude)) {
529 return;
530 }
531
532 // Remove ignored params from the slug
533 $slug = berqwp_remove_ignore_params($slug_uri);
534
535 if (isset($_GET['creating_cache'])) {
536 return;
537 }
538
539 if (get_option('berqwp_enable_sandbox') == 1 && isset($_GET['berqwp'])) {
540 $slug = explode('?berqwp', $slug_uri)[0];
541 } elseif (get_option('berqwp_enable_sandbox') == 1 && !isset($_GET['creating_cache'])) {
542 return;
543 }
544
545 if (is_singular()) {
546 $post_type = get_post_type();
547
548 if (empty($post_type) || !in_array($post_type, get_option('berqwp_optimize_post_types'))) {
549 return;
550 }
551 } elseif (is_archive()) {
552 $queried_object = get_queried_object();
553
554 if ($queried_object instanceof WP_Term && !empty($queried_object->taxonomy)) {
555 $current_taxonomy = $queried_object->taxonomy;
556
557 if (!in_array($current_taxonomy, get_option('berqwp_optimize_taxonomies'))) {
558 return;
559 }
560 }
561 }
562
563
564 // Attempt to retrieve the cached HTML from the cache directory
565 $cache_directory = optifer_cache . '/html/';
566
567 // Generate a unique cache key based on the current page URL
568 $cache_key = md5($slug);
569 $cache_file = $cache_directory . $cache_key . '.html';
570
571
572 $status_code = http_response_code();
573
574 if ($status_code !== 200) {
575 return;
576 }
577
578 if (berqwp_is_slug_excludable($slug)) {
579 return;
580 }
581
582 $berqPageOptimizer = new berqPageOptimizer();
583 $berqPageOptimizer->set_slug($slug);
584 $berqPageOptimizer->start_cache();
585 unset($berqPageOptimizer);
586
587
588 if (!isset($_GET['creating_cache'])) {
589 if (strpos($slug, '?creating_cache') === false) {
590 // $page_modified_time = berqwp_get_last_modified_timestamp();
591 $cache_life_span = time() - (18 * 60 * 60);
592
593 // Hook to modify cache lifespan
594 $cache_life_span = apply_filters('berqwp_cache_lifespan', $cache_life_span);
595
596 if (bwp_is_gzip_supported() && file_exists($cache_directory . $cache_key . '.gz')) {
597 $cache_file = $cache_directory . $cache_key . '.gz';
598 header('Content-Encoding: gzip');
599 header('Content-Type: text/html; charset=UTF-8');
600 }
601
602 if (
603 (!file_exists($cache_file) ||
604 (file_exists($cache_file) && $this->is_cache_file_expired($cache_file)) ) ||
605 (file_exists($cache_file) && bwp_is_partial_cache($slug) === true)
606 && bwp_can_warmup_cache($slug)
607 ) {
608
609 global $berq_log;
610 $startTime = microtime(true);
611
612 $args = array(
613 'blocking' => false,
614 'timeout' => 0.01,
615 'body' => array(
616 'slug' => $slug,
617 ),
618 );
619
620 wp_remote_post(get_site_url() . '/wp-json/optifer/v1/warmup-cache', $args);
621
622 // Get end time
623 $endTime = microtime(true);
624
625 // Calculate runtime in milliseconds
626 $runtime = ($endTime - $startTime) * 1000;
627
628 $berq_log->info("Requesting cache for $slug took $runtime ms from frontend.");
629
630 }
631
632 }
633 }
634
635 // If the cached HTML file exists, serve it and stop further execution
636 if (!isset($_GET['creating_cache']) && file_exists($cache_file)) {
637 $lastModified = filemtime($cache_file);
638 $etag = md5_file($cache_file);
639 header('ETag: ' . $etag);
640 header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
641
642 // Check if the client has a cached copy and if it's still valid using Last-Modified
643 if ((isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified) || (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] === $etag)) {
644 // The client's cache is still valid based on Last-Modified, respond with a 304 Not Modified
645 header('HTTP/1.1 304 Not Modified');
646 header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
647 header('Cache-Control: no-cache, must-revalidate');
648 exit();
649
650 } else {
651
652 header('Cache-Control: public, max-age=86400');
653
654 if (file_exists($cache_file)) {
655 readfile($cache_file);
656 exit();
657 }
658
659 }
660 }
661
662 if (berqReverseProxyCache::is_reverse_proxy_cache_enabled()) {
663 berqReverseProxyCache::handle_bypass();
664 }
665
666 return;
667
668 }
669
670 function warmup_cache($page)
671 {
672 global $berq_log;
673 $berq_log->info("* * * * * * * * *");
674 $berq_log->info("* Cache Warmup");
675 $berq_log->info("* * * * * * * * *");
676
677 $posts_per_batch = $this->max_page_per_batch;
678
679 // if (get_transient('berqwp_doing_cache_warmup')) {
680 // return;
681 // }
682
683 // set_transient('berqwp_doing_cache_warmup', true, 120);
684
685 // Set a transient to indicate that the cache warmup is in progress
686 set_transient('cache_warmup_in_progress', true, 120);
687
688 // warmup_cache_by_slug('/');
689
690 // $post_types = get_post_types(array('publicly_queryable' => true), 'names');
691 $post_types = get_option('berqwp_optimize_post_types');
692
693 // API endpoint URL
694 $api_endpoint = 'https://boost.berqwp.com/photon/';
695
696 if (get_site_url() == 'http://berq-test.local') {
697 $api_endpoint = 'http://dev-berqwp.local/photon/';
698 }
699
700 // Modify photon engine endpoint for testing purposes
701 $api_endpoint = apply_filters( 'berqwp_photon_endpoint', $api_endpoint );
702
703 // $post_types[] = 'product';
704 $args = array(
705 'post_type' => $post_types,
706 'posts_per_page' => $posts_per_batch,
707 'paged' => $page,
708 );
709
710 $check_rest = bwp_check_rest_api(true);
711 if ( $check_rest['status'] == 'error' ) {
712 global $berq_log;
713 $berq_log->error('Exiting cron cache warmup, rest api not working.');
714 return;
715 }
716
717 $query = new WP_Query($args);
718
719 $httpMulti = new bwp_multi_http();
720
721 $post_data = berqwp_get_page_params('/');
722 $httpMulti->addRequest('POST', $api_endpoint, $post_data);
723
724 // Loop through all posts and make a GET request
725 while ($query->have_posts()) {
726 $query->the_post();
727
728 // Get the post URL and make a GET request
729 $url = trailingslashit(get_permalink());
730 $slug = str_replace(home_url(), '', $url);
731 $post_data = berqwp_get_page_params($slug);
732
733 // Skip if page is excluded from cache
734 $pages_to_exclude = get_option('berq_exclude_urls', []);
735
736 // Attempt to retrieve the cached HTML from the cache directory
737 $cache_directory = optifer_cache . '/html/';
738
739 // Generate a unique cache key based on the current page URL
740 $cache_key = md5($slug);
741 $cache_file = $cache_directory . $cache_key . '.html';
742 $page_modified_time = berqwp_get_last_modified_timestamp();
743 $cache_life_span = time() - (18 * 60 * 60);
744
745 if (!file_exists($cache_file) && bwp_pass_account_requirement() === false) {
746 $berq_log->info("Exiting cache $slug");
747 continue;
748 }
749
750 if (in_array($url, $pages_to_exclude)) {
751
752 if (file_exists($cache_file)) {
753 unlink($cache_file);
754 }
755
756 continue;
757 }
758
759 if (berqwp_is_slug_excludable($slug)) {
760 continue;
761 }
762
763 // Hook to modify cache lifespan
764 $cache_life_span = apply_filters('berqwp_cache_lifespan', $cache_life_span);
765
766 if (
767 !file_exists($cache_file) ||
768 ($this->is_cache_file_expired($cache_file)) ||
769 (file_exists($cache_file) && bwp_is_partial_cache($slug) === true) ||
770 (file_exists($cache_file) && !empty($page_modified_time) && $page_modified_time > filemtime($cache_file))
771 ) {
772 $httpMulti->addRequest('POST', $api_endpoint, $post_data);
773
774 $berq_log->info("Requesting cache for $slug");
775
776 }
777
778
779 }
780
781 $responses = $httpMulti->execute();
782
783 wp_reset_postdata();
784
785 delete_transient('cache_warmup_in_progress');
786 delete_transient('berqwp_doing_cache_warmup');
787
788 }
789
790
791 function cache_warmup_admin_notice()
792 {
793
794
795 if (get_transient('cache_warmup_in_progress')) {
796 ?>
797 <div class="notice notice-info is-dismissible">
798 <p>
799 <?php
800 esc_html_e('Cache warmup is in progress... This process could take some time depending on the number of pages on your website.', 'searchpro');
801 ?>
802 </p>
803 </div>
804 <?php
805 }
806
807 if (!get_transient('cache_warmup_in_progress') && isset($_GET['berq_warmingup'])) {
808 ?>
809 <div class="notice notice-info is-dismissible">
810 <p>
811 <?php esc_html_e('BerqWP is starting cache warmup. Please wait.', 'searchpro'); ?>
812 </p>
813 </div>
814 <?php
815 }
816
817 if (get_transient('berq_cache_cleared_notice')) {
818 delete_transient('berq_cache_cleared_notice');
819 ?>
820 <div class="notice notice-success is-dismissible">
821 <p>
822 <?php esc_html_e('The cache has been cleared. Our automatic cache warm-up system will generate the cache. Alternatively, you can
823 visit any page to create its cache immediately.', 'searchpro'); ?>
824 </p>
825 </div>
826 <?php
827 }
828 }
829
830 }
831
832 $cache = new berqCache();
833
834 }
835