1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
|
<?php
if (!defined('ABSPATH')) die('No direct access allowed');
/** * Extensions directory. */ if (!defined('WPO_CACHE_EXT_DIR')) define('WPO_CACHE_EXT_DIR', dirname(__FILE__).'/extensions');
/** * Holds utility functions used by file based cache */
/** * Cache output before it goes to the browser. If moving/renaming this function, then also change the check above. * * @param string $buffer Page HTML. * @param int $flags OB flags to be passed through. * @return string */ if (!function_exists('wpo_cache')) : function wpo_cache($buffer, $flags) { // This array records reasons why no cacheing took place. Be careful not to allow actions to proceed that should not - i.e. take note of its state appropriately. $no_cache_because = array();
if (strlen($buffer) < 255) { $no_cache_because[] = sprintf(__('Output is too small (less than %d bytes) to be worth caching', 'wp-optimize'), 255); }
// Don't cache pages for logged in users. if (!function_exists('is_user_logged_in') || is_user_logged_in()) { $no_cache_because[] = __('User is logged in', 'wp-optimize'); }
$restricted_page_type_cache = apply_filters('wpo_restricted_cache_page_type', false); if ($restricted_page_type_cache) { $no_cache_because[] = $restricted_page_type_cache; }
// No root cache folder, so short-circuit here if (!file_exists(WPO_CACHE_DIR)) { $no_cache_because[] = __('WP-O cache parent directory was not found', 'wp-optimize').' ('.WPO_CACHE_DIR.')'; } elseif (!file_exists(WPO_CACHE_FILES_DIR)) { // Try creating a folder for cached files, if it was flushed recently if (!mkdir(WPO_CACHE_FILES_DIR)) { $no_cache_because[] = __('WP-O cache directory was not found', 'wp-optimize').' ('.WPO_CACHE_FILES_DIR.')'; } else { wpo_disable_cache_directories_viewing(); } }
// If comments are opened and the user has saved his information. if (function_exists('comments_open') && function_exists('get_post') && get_post() && comments_open()) { $commenter = wp_get_current_commenter(); // if any of the fields contain something, do not save to cache if ('' != $commenter['comment_author'] || '' != $commenter['comment_author_email'] || '' != $commenter['comment_author_url']) { $no_cache_because[] = __('Comments are opened and the visitor saved his information.', 'wp-optimize'); } }
$can_cache_page = (defined('DONOTCACHEPAGE') && DONOTCACHEPAGE) ? false : true;
/** * Defines if the page can be cached or not * * @param boolean $can_cache_page */ $can_cache_page = apply_filters('wpo_can_cache_page', $can_cache_page);
if (!$can_cache_page) { $no_cache_because[] = __('DONOTCACHEPAGE constant or wpo_can_cache_page filter forbade it', 'wp-optimize'); }
if (defined('REST_REQUEST') && REST_REQUEST) { $no_cache_because[] = __('This is a REST API request (identified by REST_REQUEST constant)', 'wp-optimize'); }
// Don't cache with fatal error pages. $last_error = error_get_last(); if (is_array($last_error) && E_ERROR == $last_error['type']) { $no_cache_because[] = __('This page has a fatal error', 'wp-optimize'); }
if (empty($no_cache_because)) {
$buffer = apply_filters('wpo_pre_cache_buffer', $buffer, $flags);
$url_path = wpo_get_url_path();
$dirs = explode('/', $url_path);
$path = WPO_CACHE_FILES_DIR;
foreach ($dirs as $dir) { if (!empty($dir)) { $path .= '/' . $dir;
if (!file_exists($path)) { if (!mkdir($path)) { $no_cache_because[] = __('Attempt to create subfolder within cache directory failed', 'wp-optimize')." ($path)"; break; } } } } }
if (!empty($no_cache_because)) {
$message = implode(', ', $no_cache_because);
// Add http headers wpo_cache_add_nocache_http_header($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) && (!defined('REST_REQUEST') || !REST_REQUEST)) { $buffer .= "\n<!-- WP Optimize page cache - https://getwpo.com - page NOT cached because: ".htmlspecialchars($message)." -->\n"; } return $buffer; } else { // Prevent mixed content when there's an http request but the site URL uses https. $home_url = get_home_url();
if (!is_ssl() && 'https' === strtolower(parse_url($home_url, PHP_URL_SCHEME))) { $https_home_url = $home_url; $http_home_url = str_ireplace('https://', 'http://', $https_home_url); $buffer = str_replace(esc_url($http_home_url), esc_url($https_home_url), $buffer); }
$modified_time = time(); // Take this as soon before writing as possible
$add_to_footer = ''; /** * Filter wether to display the html comment <!-- Cached by WP-Optimize ... --> * * @param boolean $show - Wether to display the html comment * @return boolean */ if (preg_match('#</html>#i', $buffer) && (apply_filters('wpo_cache_show_cached_by_comment', true) || (defined('WP_DEBUG') && WP_DEBUG))) { if (!empty($GLOBALS['wpo_cache_config']['enable_mobile_caching']) && wpo_is_mobile()) { $add_to_footer .= "\n<!-- Cached by WP-Optimize - for mobile devices - https://getwpo.com - Last modified: " . gmdate('D, d M Y H:i:s', $modified_time) . " GMT -->\n"; } else { $add_to_footer .= "\n<!-- Cached by WP-Optimize - https://getwpo.com - Last modified: " . gmdate('D, d M Y H:i:s', $modified_time) . " GMT -->\n"; } }
// Create an empty index.php file in the cache directory for disable directory viewing. if (!is_file($path . '/index.php')) file_put_contents($path . '/index.php', '');
/** * Save $buffer into cache file. */ $cache_filename = wpo_cache_filename(); $cache_file = $path . '/' .$cache_filename;
// if we can then cache gzipped content in .gz file. if (function_exists('gzencode')) { // Only replace inside the addition, not inside the main buffer (e.g. post content) file_put_contents($cache_file . '.gz', gzencode($buffer.str_replace('by WP-Optimize', 'by WP-Optimize (gzip)', $add_to_footer), apply_filters('wpo_cache_gzip_level', 6))); }
file_put_contents($cache_file, $buffer.$add_to_footer);
// delete cached information about cache size. WP_Optimize()->get_page_cache()->delete_cache_size_information();
header('Cache-Control: no-cache'); // Check back every time to see if re-download is necessary. header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $modified_time) . ' GMT'); header('WPO-Cache-Status: saving to cache');
if (wpo_cache_can_output_gzip_content()) { if (!wpo_cache_is_in_response_headers_list('Content-Encoding', 'gzip')) { header('Content-Encoding: gzip'); } // disable php gzip to avoid double compression. ini_set('zlib.output_compression', 'Off'); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.runtime_configuration_ini_set
return ob_gzhandler($buffer, $flags); } else { return $buffer; } } } endif;
/** * Load files for support plugins. */ if (!function_exists('wpo_cache_load_extensions')) : function wpo_cache_load_extensions() { $extensions = glob(WPO_CACHE_EXT_DIR . '/*.php');
// Add external extensions if (defined('WPO_CACHE_CUSTOM_EXT_DIR') && is_dir(WPO_CACHE_CUSTOM_EXT_DIR)) { $extensions = array_merge($extensions, glob(WPO_CACHE_CUSTOM_EXT_DIR . '/*.php')); }
if (empty($extensions)) return;
foreach ($extensions as $extension) { if (is_file($extension)) require_once $extension; } } endif;
if (!function_exists('wpo_restricted_cache_page_type')) { function wpo_restricted_cache_page_type($restricted) { global $post;
// Don't cache search or password protected. if ((function_exists('is_search') && is_search()) || (function_exists('is_404') && is_404()) || !empty($post->post_password)) { $restricted = __('Page type is not cacheable (search, 404 or password-protected)', 'wp-optimize'); }
// Don't cache the front page if option is set. if (in_array('/', wpo_get_url_exceptions()) && function_exists('is_front_page') && is_front_page()) {
$restricted = __('In the settings, caching is disabled for the front page', 'wp-optimize'); }
// Don't cache htacesss. Remember to properly escape any output to prevent injection. if (strpos($_SERVER['REQUEST_URI'], '.htaccess') !== false) { $restricted = 'The file path is unsuitable for caching ('.$_SERVER['REQUEST_URI'].')'; }
// Don't cache feeds. if (function_exists('is_feed') && is_feed()) { $restricted = __('We don\'t cache RSS feeds', 'wp-optimize'); }
return $restricted; } }
/** * Get filename for store cache, depending on gzip, mobile and cookie settings. * * @param string $ext * @return string */ if (!function_exists('wpo_cache_filename')) : function wpo_cache_filename($ext = '.html') { $filename = 'index';
if (wpo_cache_mobile_caching_enabled() && wpo_is_mobile()) { $filename = 'mobile.' . $filename; }
$cookies = wpo_cache_cookies();
$cache_key = '';
/** * Add cookie values to filename if need. * This section was inspired by things learned from WP-Rocket. */ if (!empty($cookies)) { foreach ($cookies as $key => $cookie_name) { if (is_array($cookie_name) && isset($_COOKIE[$key])) { foreach ($cookie_name as $cookie_key) { if (isset($_COOKIE[$key][$cookie_key]) && '' !== $_COOKIE[$key][$cookie_key]) { $_cache_key = $cookie_key.'='.$_COOKIE[$key][$cookie_key]; $_cache_key = preg_replace('/[^a-z0-9_\-\=]/i', '-', $_cache_key); $cache_key .= '-' . $_cache_key; } } continue; }
if (isset($_COOKIE[$cookie_name]) && '' !== $_COOKIE[$cookie_name]) { $_cache_key = $cookie_name.'='.$_COOKIE[$cookie_name]; $_cache_key = preg_replace('/[^a-z0-9_\-\=]/i', '-', $_cache_key); $cache_key .= '-' . $_cache_key; } } }
$query_variables = wpo_cache_query_variables();
/** * Add GET variables to cache file name if need. */ if (!empty($query_variables)) { foreach ($query_variables as $variable) { if (isset($_GET[$variable]) && !empty($_GET[$variable])) { $_cache_key = $variable.'='.$_GET[$variable]; $_cache_key = preg_replace('/[^a-z0-9_\-\=]/i', '-', $_cache_key); $cache_key .= '-' . $_cache_key; } } }
// add hash of queried cookies and variables to cache file name. if ('' !== $cache_key) { $filename .= '-' . md5($cache_key); }
return $filename . $ext; } endif;
/** * Returns site url from site_url() function or if it is not available from cache configuration. */ if (!function_exists('wpo_site_url')) : function wpo_site_url() { if (is_callable('site_url')) return site_url('/');
$site_url = empty($GLOBALS['wpo_cache_config']['site_url']) ? '' : $GLOBALS['wpo_cache_config']['site_url']; return $site_url; } endif;
/** * Get cookie names which impact on cache file name. * * @return array */ if (!function_exists('wpo_cache_cookies')) : function wpo_cache_cookies() { $cookies = empty($GLOBALS['wpo_cache_config']['wpo_cache_cookies']) ? array() : $GLOBALS['wpo_cache_config']['wpo_cache_cookies']; return $cookies; } endif;
/** * Get GET variable names which impact on cache file name. * * @return array */ if (!function_exists('wpo_cache_query_variables')) : function wpo_cache_query_variables() { if (defined('WPO_CACHE_URL_PARAMS') && WPO_CACHE_URL_PARAMS) { $variables = array_keys($_GET); } else { $variables = empty($GLOBALS['wpo_cache_config']['wpo_cache_query_variables']) ? array() : $GLOBALS['wpo_cache_config']['wpo_cache_query_variables']; }
if (!empty($variables)) { sort($variables); }
return wpo_cache_maybe_ignore_query_variables($variables); } endif;
/** * Get list of all received HTTP headers. * * @return array */ if (!function_exists('wpo_get_http_headers')) : function wpo_get_http_headers() {
static $headers;
if (!empty($headers)) return $headers;
$headers = array();
// if is apache server then use get allheaders() function. if (function_exists('getallheaders')) { $headers = getallheaders(); } else { // https://www.php.net/manual/en/function.getallheaders.php foreach ($_SERVER as $key => $value) {
$key = strtolower($key);
if ('HTTP_' == substr($key, 0, 5)) { $headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', substr($key, 5))))] = $value; } elseif ('content_type' == $key) { $headers["Content-Type"] = $value; } elseif ('content_length' == $key) { $headers["Content-Length"] = $value; } } }
return $headers; } endif;
/** * Check if requested Accept-Encoding headers has gzip value. * * @return bool */ if (!function_exists('wpo_cache_gzip_accepted')) : function wpo_cache_gzip_accepted() { $headers = wpo_get_http_headers();
if (isset($headers['Accept-Encoding']) && preg_match('/gzip/i', $headers['Accept-Encoding'])) return true;
return false; } endif;
/** * Check if we can output gzip content in current answer, i.e. check Accept-Encoding headers has gzip value * and function ob_gzhandler is available. * * @return bool */ if (!function_exists('wpo_cache_can_output_gzip_content')) : function wpo_cache_can_output_gzip_content() { return wpo_cache_gzip_accepted() && function_exists('ob_gzhandler'); } endif;
/** * Check if header with certain name exists in already prepared headers and has value comparable with $header_value. * * @param string $header_name header name * @param string $header_value header value as regexp. * * @return bool */ if (!function_exists('wpo_cache_is_in_response_headers_list')) : function wpo_cache_is_in_response_headers_list($header_name, $header_value) { $headers_list = headers_list();
if (!empty($headers_list)) { $header_name = strtolower($header_name);
foreach ($headers_list as $value) { $value = explode(':', $value);
if (strtolower($value[0]) == $header_name) { if (preg_match('/'.$header_value.'/', $value[1])) { return true; } else { return false; } } } }
return false; } endif;
/** * Check if mobile cache is enabled and current request is from moblile device. * * @return bool */ if (!function_exists('wpo_cache_mobile_caching_enabled')) : function wpo_cache_mobile_caching_enabled() { if (!empty($GLOBALS['wpo_cache_config']['enable_mobile_caching'])) return true; return false; } endif;
/** * Serves the cache and exits */ if (!function_exists('wpo_serve_cache')) : function wpo_serve_cache() { $file_name = wpo_cache_filename();
$path = WPO_CACHE_FILES_DIR . '/' . wpo_get_url_path() . '/' . $file_name;
$use_gzip = false;
// if we can use gzip and gzipped file exist in cache we use it. // if headers already sent we don't use gzipped file content. if (!headers_sent() && wpo_cache_gzip_accepted() && file_exists($path . '.gz')) { $path .= '.gz'; $use_gzip = true; }
$modified_time = file_exists($path) ? (int) filemtime($path) : time();
// Cache has expired, purge and exit. if (!empty($GLOBALS['wpo_cache_config']['page_cache_length'])) { if (time() > ($GLOBALS['wpo_cache_config']['page_cache_length'] + $modified_time)) { wpo_delete_files($path); return; } }
// disable zlib output compression to avoid double content compression. if ($use_gzip) { ini_set('zlib.output_compression', 'Off'); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.runtime_configuration_ini_set }
$gzip_header_already_sent = wpo_cache_is_in_response_headers_list('Content-Encoding', 'gzip');
header('Cache-Control: no-cache'); // Check back later
if (!empty($modified_time) && !empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) === $modified_time) { if ($use_gzip && !$gzip_header_already_sent) { header('Content-Encoding: gzip'); }
header('WPO-Cache-Status: cached'); header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $modified_time) . ' GMT'); header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified', true, 304); exit; }
if (file_exists($path) && is_readable($path)) { if ($use_gzip && !$gzip_header_already_sent) { header('Content-Encoding: gzip'); }
// send correct headers for xml and txt files $filename = basename(dirname($path));
if (preg_match('/\.xml$/i', $filename)) { header('Content-type: text/xml'); }
if (preg_match('/\.txt$/i', $filename)) { header('Content-type: text/plain'); }
header('WPO-Cache-Status: cached'); if (!empty($modified_time)) { header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $modified_time) . ' GMT'); }
readfile($path);
exit; } } endif;
/** * Clears the cache */ if (!function_exists('wpo_cache_flush')) : function wpo_cache_flush() {
if (defined('WPO_CACHE_FILES_DIR') && '' != WPO_CACHE_FILES_DIR) wpo_delete_files(WPO_CACHE_FILES_DIR);
if (function_exists('wp_cache_flush')) { wp_cache_flush(); }
do_action('wpo_cache_flush'); } endif;
/** * Get URL path for caching * * @since 1.0 * @return string */ if (!function_exists('wpo_get_url_path')) : function wpo_get_url_path($url = '') { $url = '' == $url ? wpo_current_url() : $url; $url_parts = parse_url($url); if (isset($url_parts['path']) && 0 === stripos($url_parts['path'], '/index.php')) { $url_parts['path'] = str_replace('/index.php', '/index-php', $url_parts['path']); }
if (!isset($url_parts['host'])) $url_parts['host'] = ''; if (!isset($url_parts['path'])) $url_parts['path'] = '';
return $url_parts['host'].$url_parts['path']; } endif;
/** * Get requested url. * * @return string */ if (!function_exists('wpo_current_url')) : function wpo_current_url() { // Note: We use `static $url` to save the first value we retrieve, as some plugins change $_SERVER later on in the process (e.g. Weglot). // Otherwise this function would return a different URL at the begining and end of the cache process. static $url = ''; if ('' != $url) return $url; $http_host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''; $url = rtrim('http' . ((isset($_SERVER['HTTPS']) && ('on' == $_SERVER['HTTPS'] || 1 == $_SERVER['HTTPS']) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && 'https' == $_SERVER['HTTP_X_FORWARDED_PROTO']) ? 's' : '' ) . '://' . $http_host.$_SERVER['REQUEST_URI'], '/'); return $url; } endif;
/** * Return list of url exceptions. * * @return array */ if (!function_exists('wpo_get_url_exceptions')) : function wpo_get_url_exceptions() { static $exceptions = null;
if (null !== $exceptions) return $exceptions;
// if called from file-based-page-cache.php when WP loading // and cache settings exists then use it otherwise get settings from database. if (isset($GLOBALS['wpo_cache_config']['cache_exception_urls'])) { if (empty($GLOBALS['wpo_cache_config']['cache_exception_urls'])) { $exceptions = array(); } else { $exceptions = is_array($GLOBALS['wpo_cache_config']['cache_exception_urls']) ? $GLOBALS['wpo_cache_config']['cache_exception_urls'] : preg_split('#(\n|\r)#', $GLOBALS['wpo_cache_config']['cache_exception_urls']); } } else { $config = WPO_Page_Cache::instance()->config->get();
if (is_array($config) && array_key_exists('cache_exception_urls', $config)) { $exceptions = $config['cache_exception_urls']; } else { $exceptions = array(); }
$exceptions = is_array($exceptions) ? $exceptions : preg_split('#(\n|\r)#', $exceptions); $exceptions = array_filter($exceptions, 'trim'); }
return $exceptions; } endif;
/** * Return true of exception url matches current url * * @param string $exception Exceptions to check URL against. * @param bool $regex Whether to check with regex or not. * @return bool true if matched, false otherwise */ if (!function_exists('wpo_current_url_exception_match')) : function wpo_current_url_exception_match($exception) {
return wpo_url_exception_match(wpo_current_url(), $exception); } endif;
/** * Check if url in exceptions list. * * @param string $url * * @return bool */ if (!function_exists('wpo_url_in_exceptions')) : function wpo_url_in_exceptions($url) { $exceptions = wpo_get_url_exceptions();
if (!empty($exceptions)) { foreach ($exceptions as $exception) {
// don't check / - front page using regexp, we handle it in wpo_restricted_cache_page_type() if ('/' == $exception) continue;
if (wpo_url_exception_match($url, $exception)) { // Exception match. return true; } } }
return false; } endif;
/** * Check if url string match with exception. * * @param string $url - complete url string i.e. http(s):://domain/path * @param string $exception - complete url or absolute path, can consist (.*) wildcards * * @return bool */ if (!function_exists('wpo_url_exception_match')) : function wpo_url_exception_match($url, $exception) { if (preg_match('#^[\s]*$#', $exception)) { return false; }
$exception = str_replace('*', '.*', $exception);
$exception = trim($exception);
// used to test websites placed in subdirectories. $sub_dir = '';
// if exception defined from root i.e. /page1 then remove domain part in url. if (preg_match('/^\//', $exception)) { // get site sub directory. $sub_dir = preg_replace('#^(http|https):\/\/.*\/#Ui', '', wpo_site_url()); // add prefix slash and remove slash. $sub_dir = ('' == $sub_dir) ? '' : '/' . rtrim($sub_dir, '/'); // get relative path $url = preg_replace('#^(http|https):\/\/.*\/#Ui', '/', $url); }
$url = rtrim($url, '/') . '/'; $exception = rtrim($exception, '/');
// if we have no wildcat in the end of exception then add slash. if (!preg_match('#\(\.\*\)$#', $exception)) $exception .= '/';
$exception = preg_quote($exception);
return preg_match('#^'.$exception.'$#i', $url) || preg_match('#^'.$sub_dir.$exception.'$#i', $url); } endif;
/** * Checks if its a mobile device * * @see https://developer.wordpress.org/reference/functions/wp_is_mobile/ */ if (!function_exists('wpo_is_mobile')) : function wpo_is_mobile() { if (empty($_SERVER['HTTP_USER_AGENT'])) { $is_mobile = false; // many mobile devices (all iPhone, iPad, etc.) } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false ) { $is_mobile = true; } else { $is_mobile = false; }
return $is_mobile; } endif;
/** * Check if current browser agent is not disabled in options. * * @return bool */ if (!function_exists('wpo_is_accepted_user_agent')) : function wpo_is_accepted_user_agent($user_agent) {
$exceptions = is_array($GLOBALS['wpo_cache_config']['cache_exception_browser_agents']) ? $GLOBALS['wpo_cache_config']['cache_exception_browser_agents'] : preg_split('#(\n|\r)#', $GLOBALS['wpo_cache_config']['cache_exception_browser_agents']);
if (!empty($exceptions)) { foreach ($exceptions as $exception) { if ('' == trim($exception)) continue;
if (preg_match('#'.$exception.'#i', $user_agent)) return false; } }
return true; } endif;
/** * Delete function that deals with directories recursively * * @param string $src Path of the folder * @param boolean $recursive If $src is a folder, recursively delete the inner folders. If set to false, only the files will be deleted. * * @return bool */ if (!function_exists('wpo_delete_files')) : function wpo_delete_files($src, $recursive = true) { if (!file_exists($src) || '' == $src || '/' == $src) { return true; }
if (is_file($src)) { return unlink($src); }
$success = true; $has_dir = false;
if ($recursive) { // N.B. If opendir() fails, then a false positive (i.e. true) will be returned if (false !== ($dir = opendir($src))) { $file = readdir($dir); while (false !== $file) { if ('.' == $file || '..' == $file) { $file = readdir($dir); continue; } if (is_dir($src . '/' . $file)) { if (!wpo_delete_files($src . '/' . $file)) { $success = false; } } else { if (!unlink($src . '/' . $file)) { $success = false; } }
$file = readdir($dir); } closedir($dir); } } else { // Not recursive, so we only delete the files // scan directories recursively. $handle = opendir($src);
if (false === $handle) return false;
$file = readdir($handle);
while (false !== $file) {
if ('.' != $file && '..' != $file) { if (is_dir($src . '/' . $file)) { $has_dir = true; } elseif (!unlink($src . '/' . $file)) { $success = false; } }
$file = readdir($handle);
} }
if ($success && !$has_dir) { // Success of this operation is not recorded; we only ultimately care about emptying, not removing entirely (empty folders in our context are harmless) rmdir($src); }
// delete cached information about cache size. WP_Optimize()->get_page_cache()->delete_cache_size_information();
return $success; } endif;
/** * Either store for later output, or output now. Only the most-recent call will be effective. * * @param String|Null $output - if not null, then the string to use when called by the shutdown action. */ if (!function_exists('wpo_cache_add_footer_output')) : function wpo_cache_add_footer_output($output = null) {
static $buffered = null;
if (function_exists('current_filter') && 'shutdown' == current_filter()) { // Only add the line if it was a page, not something else (e.g. REST response) if (function_exists('did_action') && did_action('wp_footer')) { echo "\n<!-- WP Optimize page cache - https://getwpo.com - ".$buffered." -->\n"; } elseif (defined('WPO_CACHE_DEBUG') && WPO_CACHE_DEBUG) { error_log('[CACHE DEBUG] '.wpo_current_url() . ' - ' . $buffered); } } else { if (null == $buffered && function_exists('add_action')) add_action('shutdown', 'wpo_cache_add_footer_output', 11); $buffered = $output; }
} endif;
/** * Remove variable names that shouldn't influence cache. * * @param array $variables List of variable names. * * @return array */ if (!function_exists('wpo_cache_maybe_ignore_query_variables')) : function wpo_cache_maybe_ignore_query_variables($variables) {
/** * Filters the current $_GET variables that will be used when caching or excluding from cache. * Currently: * - 'wpo_cache_debug' (Shows the reason for not being cached even when WP_DEBUG isn't set) * - 'doing_wp_cron' (alternative cron) * - 'aiosp_sitemap_path', 'aiosp_sitemap_page' (All in one SEO sitemap) * - 'xml_sitemap', 'seopress_sitemap', 'seopress_news', 'seopress_video', 'seopress_cpt', 'seopress_paged' (SEOPress sitemap) * - 'sitemap', 'sitemap_n' (YOAST SEO sitemap) */ $exclude_variables = array( 'wpo_cache_debug', // Shows the reason for not being cached even when WP_DEBUG isn't set 'doing_wp_cron', // alternative cron 'aiosp_sitemap_path', // All in one SEO sitemap 'aiosp_sitemap_page', 'xml_sitemap', // SEOPress sitemap 'seopress_sitemap', 'seopress_news', 'seopress_video', 'seopress_cpt', 'seopress_paged', 'sitemap', // YOAST SEO sitemap 'sitemap_n', ); $exclude_variables = function_exists('apply_filters') ? apply_filters('wpo_cache_ignore_query_variables', $exclude_variables) : $exclude_variables;
if (empty($exclude_variables)) return $variables;
foreach ($exclude_variables as $variable) { $exclude = array_search($variable, $variables); if (false !== $exclude) { array_splice($variables, $exclude, 1); } }
return $variables; } endif;
/** * Get cache config * * @param string $key - The config item * @param mixed $default - The default value * * @return mixed */ if (!function_exists('wpo_cache_config_get')) : function wpo_cache_config_get($key, $default = false) { $config = $GLOBALS['wpo_cache_config'];
if (!$config) return false;
if (isset($config[$key])) { return $config[$key]; } else { return $default; } } endif;
if (!function_exists('wpo_disable_cache_directories_viewing')) : function wpo_disable_cache_directories_viewing() { global $is_apache, $is_IIS, $is_iis7;
if (!is_dir(WPO_CACHE_FILES_DIR)) return;
// Create .htaccess file for apache server. if ($is_apache) { $htaccess_filename = WPO_CACHE_FILES_DIR . '/.htaccess';
// CS does not like heredoc // phpcs:disable $htaccess_content = <<<EOF # Disable directory browsing Options -Indexes
# Disable access to any files <FilesMatch ".*"> Order allow,deny Deny from all </FilesMatch> EOF; // phpcs:enable
if (!is_file($htaccess_filename)) @file_put_contents($htaccess_filename, $htaccess_content); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged }
// Create web.config file for IIS servers. if ($is_IIS || $is_iis7) { $webconfig_filename = WPO_CACHE_FILES_DIR . '/web.config'; $webconfig_content = "<configuration>\n<system.webServer>\n<authorization>\n<deny users=\"*\" />\n</authorization>\n</system.webServer>\n</configuration>\n";
if (!is_file($webconfig_filename)) @file_put_contents($webconfig_filename, $webconfig_content); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged }
// Create empty index.php file for all servers. if (!is_file(WPO_CACHE_FILES_DIR . '/index.php')) @file_put_contents(WPO_CACHE_FILES_DIR . '/index.php', '');// phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged } endif;
/** * Add the headers indicating why the page is not cached or served from cache * * @param string $message - The headers * * @return void */ if (!function_exists('wpo_cache_add_nocache_http_header')) : function wpo_cache_add_nocache_http_header($message = '') { static $buffered_message = null;
if (function_exists('current_filter') && 'send_headers' === current_filter() && $buffered_message && !headers_sent()) { header('WPO-Cache-Status: not cached'); header('WPO-Cache-Message: '. trim(str_replace(array("\r", "\n", ':'), ' ', strip_tags($buffered_message)))); } else { if (!$buffered_message && function_exists('add_action')) add_action('send_headers', 'wpo_cache_add_nocache_http_header', 11); $buffered_message = $message; } } endif;
|