-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.php
More file actions
2176 lines (1836 loc) · 74.9 KB
/
init.php
File metadata and controls
2176 lines (1836 loc) · 74.9 KB
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
1000
<?php
/**
* Plugin Name: Really Simple Cache
* Description: Super lightweight output cache with HTML/CSS/JS minification and auto-defer scripts.
* Version: 2.6
* Author: UnicornPanel.net
*/
if (!defined('ABSPATH')) exit;
require_once __DIR__ . '/includes/class-rsc-remove-unused-css.php';
require_once __DIR__ . '/includes/class-rsc-script-deferrer.php';
require_once __DIR__ . '/includes/class-rsc-script-delayer.php';
require_once __DIR__ . '/includes/class-rsc-minifier.php';
require_once __DIR__ . '/includes/class-rsc-asset-combiner.php';
if (!function_exists('rsc_get_cache_key')) {
/**
* Build a stable cache key for a URI + host + scheme.
*/
function rsc_get_cache_key($uri, $host = null, $scheme = null) {
$uri = is_string($uri) && $uri !== '' ? $uri : '/';
$host = $host ?: (wp_parse_url(home_url('/'), PHP_URL_HOST) ?: '');
$scheme = $scheme ?: (is_ssl() ? 'https' : 'http');
$host = strtolower(trim((string) $host));
$scheme = strtolower(trim((string) $scheme));
return md5($scheme . '://' . $host . $uri);
}
}
if (!function_exists('rsc_get_debug_log_file')) {
function rsc_get_debug_log_file() {
$upload = wp_upload_dir();
return trailingslashit($upload['basedir']) . 'really-simple-cache/debug.log';
}
}
if (!function_exists('rsc_write_debug_log')) {
function rsc_write_debug_log($event, $context = [], $level = 'INFO') {
$event = trim((string) $event);
if ($event === '') {
return;
}
$log_file = rsc_get_debug_log_file();
$dir = dirname($log_file);
if (!is_dir($dir) && !wp_mkdir_p($dir)) {
return;
}
if (!is_array($context)) {
$context = ['value' => $context];
}
$normalized = [];
foreach ($context as $key => $value) {
if (is_scalar($value) || $value === null) {
$normalized[$key] = $value;
continue;
}
if (is_array($value) || is_object($value)) {
$normalized[$key] = wp_json_encode($value);
continue;
}
$normalized[$key] = gettype($value);
}
$timestamp = gmdate('Y-m-d H:i:s');
$level = strtoupper(preg_replace('/[^A-Z]/i', '', (string) $level));
if ($level === '') {
$level = 'INFO';
}
$line = sprintf(
"[%s UTC] [%s] %s | %s\n",
$timestamp,
$level,
$event,
wp_json_encode($normalized)
);
if (@file_put_contents($log_file, $line, FILE_APPEND | LOCK_EX) === false) {
return;
}
$raw = @file_get_contents($log_file);
if (!is_string($raw) || $raw === '') {
return;
}
$lines = preg_split('/\r\n|\r|\n/', trim($raw));
if (!is_array($lines) || count($lines) <= 1000) {
return;
}
$lines = array_slice($lines, -1000);
@file_put_contents($log_file, implode("\n", $lines) . "\n", LOCK_EX);
}
}
class ReallySimpleCache {
private $cache_dir;
private $cache_url;
private $settings;
private $rucss;
private $script_deferrer;
private $script_delayer;
private $minifier;
private $asset_combiner;
public function __construct() {
$upload = wp_upload_dir();
$this->cache_dir = trailingslashit($upload['basedir']) . 'really-simple-cache/';
$this->cache_url = trailingslashit($upload['baseurl']) . 'really-simple-cache/';
$this->settings = $this->load_settings();
add_action('init', [$this, 'create_dirs']);
add_action('template_redirect', [$this, 'serve_cache'], 0);
add_action('template_redirect', [$this, 'start_buffer'], 1);
add_action('shutdown', [$this, 'end_buffer'], 9999);
add_action('save_post', [$this, 'purge_all_cache']);
add_action('deleted_post', [$this, 'purge_all_cache']);
add_action('trashed_post', [$this, 'purge_all_cache']);
add_action('clean_post_cache', [$this, 'purge_all_cache']);
add_action('wp_update_nav_menu', [$this, 'purge_all_cache']);
add_action('switch_theme', [$this, 'purge_all_cache']);
add_action('customize_save_after', [$this, 'purge_all_cache']);
add_action('comment_post', [$this, 'purge_all_cache']);
add_action('edit_comment', [$this, 'purge_all_cache']);
add_action('wp_set_comment_status', [$this, 'purge_all_cache']);
add_action('rsc_download_font_css', [$this, 'handle_font_css_download'], 10, 1);
add_filter('get_avatar_url', [$this, 'filter_avatar_url'], 10, 3);
if (is_admin()) {
add_action('admin_menu', [$this, 'register_settings_page']);
add_action('admin_init', [$this, 'register_settings']);
add_action('admin_post_rsc_clear_debug_log', [$this, 'handle_clear_debug_log']);
add_action('wp_ajax_rsc_refresh_debug_log', [$this, 'ajax_refresh_debug_log']);
}
//$this->log('Plugin initialized', [
// 'cache_dir' => $this->cache_dir,
//]);
}
private function defaults() {
return [
'enable_page_cache' => 1,
'cache_ttl' => 3600,
'minify_html' => 1,
'minify_css' => 1,
'minify_js' => 1,
'defer_scripts' => 1,
'delay_scripts' => 0,
'debug_footer' => 1,
'combine_css' => 0,
'combine_js' => 0,
'local_avatars' => 0,
'local_fonts' => 0,
'remove_unused_css' => 0,
'asset_ttl' => 604800,
'rucss_max_css_kb' => 512,
'excluded_pages' => '',
'excluded_css' => '',
'excluded_js' => '',
'excluded_delay_js' => '',
'rucss_excluded_pages' => '',
'rucss_keep_selectors' => '',
];
}
private function load_settings() {
$stored = get_option('rsc_settings', []);
if (!is_array($stored)) {
$stored = [];
}
return wp_parse_args($stored, $this->defaults());
}
private function setting_enabled($key) {
return !empty($this->settings[$key]);
}
private function setting_int($key, $fallback = 0) {
if (!isset($this->settings[$key])) {
return (int) $fallback;
}
return (int) $this->settings[$key];
}
private function log($event, $context = [], $level = 'INFO') {
if (!is_array($context)) {
$context = ['value' => $context];
}
if (!isset($context['request_uri'])) {
$context['request_uri'] = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '';
}
rsc_write_debug_log($event, $context, $level);
}
private function get_debug_log_contents($max_lines = 300) {
$file = rsc_get_debug_log_file();
if (!is_file($file) || !is_readable($file)) {
return '';
}
$raw = @file_get_contents($file);
if (!is_string($raw) || $raw === '') {
return '';
}
$lines = preg_split('/\r\n|\r|\n/', trim($raw));
if (!is_array($lines) || empty($lines)) {
return '';
}
$slice = array_slice($lines, -max(1, (int) $max_lines));
return implode("\n", $slice);
}
public function register_settings_page() {
add_options_page(
'RS Cache',
'RS Cache',
'manage_options',
'rsc-settings',
[$this, 'render_settings_page']
);
}
public function register_settings() {
register_setting('rsc_settings_group', 'rsc_settings', [$this, 'sanitize_settings']);
}
public function handle_clear_debug_log() {
if (!current_user_can('manage_options')) {
wp_die('No permission.');
}
check_admin_referer('rsc_clear_debug_log');
$file = rsc_get_debug_log_file();
if (is_file($file)) {
@file_put_contents($file, '');
}
$this->log('Debug log cleared by admin user', [
'user_id' => get_current_user_id(),
]);
wp_safe_redirect(admin_url('options-general.php?page=rsc-settings&debug_log_cleared=1'));
exit;
}
public function ajax_refresh_debug_log() {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'No permission.'], 403);
}
check_ajax_referer('rsc_refresh_debug_log');
wp_send_json_success([
'log' => $this->get_debug_log_contents(300),
]);
}
public function sanitize_settings($input) {
$defaults = $this->defaults();
$input = is_array($input) ? $input : [];
$settings = [
'enable_page_cache' => empty($input['enable_page_cache']) ? 0 : 1,
'minify_html' => empty($input['minify_html']) ? 0 : 1,
'minify_css' => empty($input['minify_css']) ? 0 : 1,
'minify_js' => empty($input['minify_js']) ? 0 : 1,
'defer_scripts' => empty($input['defer_scripts']) ? 0 : 1,
'delay_scripts' => empty($input['delay_scripts']) ? 0 : 1,
'debug_footer' => empty($input['debug_footer']) ? 0 : 1,
'combine_css' => empty($input['combine_css']) ? 0 : 1,
'combine_js' => empty($input['combine_js']) ? 0 : 1,
'local_avatars' => empty($input['local_avatars']) ? 0 : 1,
'local_fonts' => empty($input['local_fonts']) ? 0 : 1,
'remove_unused_css' => empty($input['remove_unused_css']) ? 0 : 1,
'cache_ttl' => isset($input['cache_ttl']) ? max(60, (int) $input['cache_ttl']) : $defaults['cache_ttl'],
'asset_ttl' => isset($input['asset_ttl']) ? max(3600, (int) $input['asset_ttl']) : $defaults['asset_ttl'],
'rucss_max_css_kb' => isset($input['rucss_max_css_kb']) ? max(32, (int) $input['rucss_max_css_kb']) : $defaults['rucss_max_css_kb'],
'excluded_pages' => isset($input['excluded_pages']) ? sanitize_textarea_field($input['excluded_pages']) : '',
'excluded_css' => isset($input['excluded_css']) ? sanitize_textarea_field($input['excluded_css']) : '',
'excluded_js' => isset($input['excluded_js']) ? sanitize_textarea_field($input['excluded_js']) : '',
'excluded_delay_js' => isset($input['excluded_delay_js']) ? sanitize_textarea_field($input['excluded_delay_js']) : '',
'rucss_excluded_pages' => isset($input['rucss_excluded_pages']) ? sanitize_textarea_field($input['rucss_excluded_pages']) : '',
'rucss_keep_selectors' => isset($input['rucss_keep_selectors']) ? sanitize_textarea_field($input['rucss_keep_selectors']) : '',
];
$this->settings = wp_parse_args($settings, $defaults);
$this->purge_all_cache();
$this->log('Settings saved and cache purged', [
'user_id' => get_current_user_id(),
'enable_page_cache' => (int) $this->settings['enable_page_cache'],
'minify_html' => (int) $this->settings['minify_html'],
'minify_css' => (int) $this->settings['minify_css'],
'minify_js' => (int) $this->settings['minify_js'],
'defer_scripts' => (int) $this->settings['defer_scripts'],
'delay_scripts' => (int) $this->settings['delay_scripts'],
'combine_css' => (int) $this->settings['combine_css'],
'combine_js' => (int) $this->settings['combine_js'],
'local_avatars' => (int) $this->settings['local_avatars'],
'local_fonts' => (int) $this->settings['local_fonts'],
'remove_unused_css' => (int) $this->settings['remove_unused_css'],
]);
return $this->settings;
}
public function render_settings_page() {
if (!current_user_can('manage_options')) {
return;
}
$s = $this->settings;
$debug_log = $this->get_debug_log_contents(300);
$refresh_nonce = wp_create_nonce('rsc_refresh_debug_log');
?>
<div class="wrap rsc-settings-wrap">
<h1>RS Cache</h1>
<p>Performance controls for page caching, asset optimization, and local third-party assets.</p>
<form method="post" action="options.php">
<?php settings_fields('rsc_settings_group'); ?>
<div class="rsc-grid">
<div class="rsc-card">
<h2>Core Cache</h2>
<?php $this->render_toggle('enable_page_cache', 'Enable Page Cache', 'Enable or disable full-page guest caching.'); ?>
<?php $this->render_toggle('debug_footer', 'Show Debug Footer', 'Adds a small cache timestamp comment to cached HTML.'); ?>
<label class="rsc-field">
<span>Page Cache TTL (seconds)</span>
<input type="number" min="60" step="60" name="rsc_settings[cache_ttl]" value="<?php echo esc_attr((int) $s['cache_ttl']); ?>" />
</label>
</div>
<div class="rsc-card">
<h2>HTML / CSS / JS</h2>
<?php $this->render_toggle('minify_html', 'Minify HTML', 'Removes extra whitespace between tags.'); ?>
<?php $this->render_toggle('minify_css', 'Minify CSS', 'Minifies external and inline CSS.'); ?>
<?php $this->render_toggle('minify_js', 'Minify JS', 'Minifies external and inline JavaScript.'); ?>
<?php $this->render_toggle('defer_scripts', 'Defer Scripts', 'Adds defer to eligible scripts.'); ?>
<?php $this->render_toggle('delay_scripts', 'Delay Scripts', 'Delays eligible external scripts until user interaction or timeout.'); ?>
</div>
<div class="rsc-card">
<h2>Additional Optimizations</h2>
<?php $this->render_toggle('combine_css', 'Combine CSS Files', 'Bundles same-domain stylesheet files into combined output.'); ?>
<?php $this->render_toggle('combine_js', 'Combine JS Files', 'Bundles same-domain head scripts into a combined file.'); ?>
<?php $this->render_toggle('local_avatars', 'Store Gravatar Avatars Locally', 'Caches Gravatar image responses in local uploads.'); ?>
<?php $this->render_toggle('local_fonts', 'Store Bunny and Google Fonts Locally', 'Downloads and rewrites Google/Bunny font stylesheets and font files.'); ?>
<?php $this->render_toggle('remove_unused_css', 'Remove Unused CSS', 'Static pruning for same-domain external CSS. Off by default.'); ?>
<label class="rsc-field">
<span>Remote Asset TTL (seconds)</span>
<input type="number" min="3600" step="3600" name="rsc_settings[asset_ttl]" value="<?php echo esc_attr((int) $s['asset_ttl']); ?>" />
</label>
</div>
<div class="rsc-card rsc-card--full">
<h2>Exclusions</h2>
<p class="rsc-help">Use one pattern per line. Wildcards are supported, for example: <code>/checkout*</code> or <code>*jquery*</code>.</p>
<label class="rsc-field">
<span>Excluded Pages (allow wildcards)</span>
<textarea name="rsc_settings[excluded_pages]" rows="4" placeholder="/checkout* /my-account*"><?php echo esc_textarea((string) $s['excluded_pages']); ?></textarea>
</label>
<label class="rsc-field">
<span>Excluded CSS (allow wildcards)</span>
<textarea name="rsc_settings[excluded_css]" rows="4" placeholder="*/wp-content/plugins/some-plugin/* *critical.css*"><?php echo esc_textarea((string) $s['excluded_css']); ?></textarea>
</label>
<label class="rsc-field">
<span>Excluded JavaScript (allow wildcards)</span>
<textarea name="rsc_settings[excluded_js]" rows="4" placeholder="*gtag/js* *recaptcha*"><?php echo esc_textarea((string) $s['excluded_js']); ?></textarea>
</label>
<label class="rsc-field">
<span>Excluded Delayed JavaScript (allow wildcards)</span>
<textarea name="rsc_settings[excluded_delay_js]" rows="4" placeholder="*jquery* *recaptcha*"><?php echo esc_textarea((string) $s['excluded_delay_js']); ?></textarea>
</label>
</div>
<div class="rsc-card rsc-card--full">
<h2>Remove Unused CSS</h2>
<p class="rsc-help">This feature is conservative, but JavaScript-driven UIs may still need safelisted selectors to avoid style regressions.</p>
<label class="rsc-field">
<span>RU-CSS Excluded Pages (allow wildcards)</span>
<textarea name="rsc_settings[rucss_excluded_pages]" rows="4" placeholder="/checkout* /my-account*"><?php echo esc_textarea((string) $s['rucss_excluded_pages']); ?></textarea>
</label>
<label class="rsc-field">
<span>RU-CSS Keep Selectors (Safelist, one pattern per line)</span>
<textarea name="rsc_settings[rucss_keep_selectors]" rows="4" placeholder=".is-active #mobile-menu-open *[data-state=*]"><?php echo esc_textarea((string) $s['rucss_keep_selectors']); ?></textarea>
</label>
<label class="rsc-field">
<span>Max CSS Size Per File (KB)</span>
<input type="number" min="32" step="32" name="rsc_settings[rucss_max_css_kb]" value="<?php echo esc_attr((int) $s['rucss_max_css_kb']); ?>" />
</label>
</div>
<div class="rsc-card rsc-card--full">
<h2>Debug Log</h2>
<p class="rsc-help">Latest log lines (file capped at 1000 lines): <code><?php echo esc_html(rsc_get_debug_log_file()); ?></code></p>
<textarea class="rsc-debug-log" readonly><?php echo esc_textarea($debug_log); ?></textarea>
<p>
<button
type="button"
class="button rsc-refresh-log"
data-ajax-url="<?php echo esc_url(admin_url('admin-ajax.php')); ?>"
data-nonce="<?php echo esc_attr($refresh_nonce); ?>"
>Refresh Log</button>
</p>
</div>
</div>
<?php submit_button('Save RS Cache Settings'); ?>
</form>
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
<?php wp_nonce_field('rsc_clear_debug_log'); ?>
<input type="hidden" name="action" value="rsc_clear_debug_log" />
<?php submit_button('Clear Debug Log', 'delete', 'submit', false); ?>
</form>
</div>
<style>
.rsc-settings-wrap p { max-width: 900px; }
.rsc-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 30px;
margin-top: 18px;
max-width: 1200px;
}
.rsc-card {
background: linear-gradient(155deg, #ffffff 0%, #f7fafc 100%);
border: 1px solid #d8e1ea;
border-radius: 14px;
padding: 30px;
box-shadow: 0 6px 24px rgba(18, 52, 86, 0.06);
}
.rsc-card h2 {
margin-top: 0;
font-size: 18px;
}
.rsc-card--full {
grid-column: 1 / -1;
}
.rsc-toggle {
display: grid;
grid-template-columns: 1fr auto;
gap: 10px;
align-items: center;
padding: 10px 0;
border-bottom: 1px solid #ecf1f5;
}
.rsc-toggle:last-of-type { border-bottom: 0; }
.rsc-toggle strong { display: block; margin-bottom: 3px; }
.rsc-toggle small { color: #516170; }
.rsc-switch {
position: relative;
display: inline-block;
width: 54px;
height: 30px;
}
.rsc-switch input {
opacity: 0;
width: 0;
height: 0;
}
.rsc-slider {
position: absolute;
inset: 0;
cursor: pointer;
border-radius: 30px;
background: #ccd7e2;
transition: .25s ease;
}
.rsc-slider:before {
content: "";
position: absolute;
left: 4px;
top: 4px;
width: 22px;
height: 22px;
border-radius: 50%;
background: #fff;
transition: .25s ease;
box-shadow: 0 1px 6px rgba(0, 0, 0, .2);
}
.rsc-switch input:checked + .rsc-slider {
background: linear-gradient(120deg, #1f9d55, #1aff85);
}
.rsc-switch input:checked + .rsc-slider:before {
transform: translateX(24px);
}
.rsc-field {
display: grid;
gap: 8px;
margin-top: 14px;
}
.rsc-field span {
font-weight: 600;
}
.rsc-field input[type="number"] {
max-width: 220px;
}
.rsc-field textarea {
width: 100%;
min-height: 96px;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
}
.rsc-help {
margin: 0 0 14px;
color: #516170;
}
.rsc-debug-log {
width: 100%;
min-height: 320px;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
white-space: pre;
}
</style>
<script>
(function () {
var logBox = document.querySelector('.rsc-debug-log');
var refreshButton = document.querySelector('.rsc-refresh-log');
function scrollLogToBottom() {
if (!logBox) return;
logBox.scrollTop = logBox.scrollHeight;
}
scrollLogToBottom();
if (!refreshButton || !logBox) {
return;
}
refreshButton.addEventListener('click', function () {
var ajaxUrl = refreshButton.getAttribute('data-ajax-url');
var nonce = refreshButton.getAttribute('data-nonce');
if (!ajaxUrl || !nonce) {
return;
}
var originalLabel = refreshButton.textContent;
refreshButton.disabled = true;
refreshButton.textContent = 'Refreshing...';
var body = new URLSearchParams();
body.set('action', 'rsc_refresh_debug_log');
body.set('_ajax_nonce', nonce);
fetch(ajaxUrl, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
body: body.toString()
}).then(function (response) {
return response.json();
}).then(function (data) {
if (data && data.success && data.data && typeof data.data.log === 'string') {
logBox.value = data.data.log;
scrollLogToBottom();
}
}).finally(function () {
refreshButton.disabled = false;
refreshButton.textContent = originalLabel;
});
});
})();
</script>
<?php
}
private function render_toggle($key, $label, $help) {
$checked = !empty($this->settings[$key]);
?>
<label class="rsc-toggle" for="rsc-<?php echo esc_attr($key); ?>">
<span>
<strong><?php echo esc_html($label); ?></strong>
<small><?php echo esc_html($help); ?></small>
</span>
<span class="rsc-switch">
<input id="rsc-<?php echo esc_attr($key); ?>" type="checkbox" name="rsc_settings[<?php echo esc_attr($key); ?>]" value="1" <?php checked($checked); ?> />
<span class="rsc-slider"></span>
</span>
</label>
<?php
}
public function create_dirs() {
$paths = [
$this->cache_dir,
$this->cache_dir . 'pages/',
$this->cache_dir . 'css/',
$this->cache_dir . 'js/',
$this->cache_dir . 'rucss/',
$this->cache_dir . 'avatars/',
$this->cache_dir . 'fonts/',
$this->cache_dir . 'fonts/css/',
$this->cache_dir . 'fonts/files/',
];
$created = 0;
foreach ($paths as $path) {
if (!file_exists($path)) {
if (wp_mkdir_p($path)) {
$created++;
}
}
}
if ($created > 0) {
$this->log('Created cache directories', ['count' => $created]);
}
}
private function cache_ttl() {
return max(60, $this->setting_int('cache_ttl', 3600));
}
private function asset_ttl() {
return max(3600, $this->setting_int('asset_ttl', 604800));
}
private function get_exclusion_patterns($setting_key) {
$value = isset($this->settings[$setting_key]) ? (string) $this->settings[$setting_key] : '';
if ($value === '') {
return [];
}
$lines = preg_split('/\r\n|\r|\n/', $value);
if (!is_array($lines)) {
return [];
}
$patterns = [];
foreach ($lines as $line) {
$line = trim($line);
if ($line === '') {
continue;
}
$patterns[] = $line;
}
return $patterns;
}
private function wildcard_match($pattern, $subject) {
$regex = preg_quote($pattern, '/');
$regex = str_replace(['\*', '\?'], ['.*', '.'], $regex);
return preg_match('/^' . $regex . '$/i', (string) $subject) === 1;
}
private function matches_any_pattern($subject, $patterns) {
foreach ((array) $patterns as $pattern) {
if ($this->wildcard_match($pattern, $subject)) {
return true;
}
}
return false;
}
private function is_current_page_excluded() {
$patterns = $this->get_exclusion_patterns('excluded_pages');
if (empty($patterns)) {
return false;
}
$uri = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '/';
$path = wp_parse_url($uri, PHP_URL_PATH);
$path = is_string($path) && $path !== '' ? $path : $uri;
return $this->matches_any_pattern($uri, $patterns) || $this->matches_any_pattern($path, $patterns);
}
private function is_asset_excluded($url, $type) {
$setting = ($type === 'css') ? 'excluded_css' : 'excluded_js';
$patterns = $this->get_exclusion_patterns($setting);
if (empty($patterns)) {
return false;
}
$url = (string) $url;
$parsed_path = wp_parse_url($url, PHP_URL_PATH);
$path = is_string($parsed_path) ? $parsed_path : $url;
return $this->matches_any_pattern($url, $patterns) || $this->matches_any_pattern($path, $patterns);
}
private function is_delay_script_excluded($url) {
if ($this->is_asset_excluded($url, 'js')) {
return true;
}
$patterns = $this->get_exclusion_patterns('excluded_delay_js');
if (empty($patterns)) {
return false;
}
$url = (string) $url;
$parsed_path = wp_parse_url($url, PHP_URL_PATH);
$path = is_string($parsed_path) ? $parsed_path : $url;
return $this->matches_any_pattern($url, $patterns) || $this->matches_any_pattern($path, $patterns);
}
private function is_cacheable_request(&$reason = null) {
if (!$this->setting_enabled('enable_page_cache')) {
$reason = 'page-cache-disabled';
return false;
}
if ($this->is_current_page_excluded()) {
$reason = 'page-excluded';
return false;
}
if (is_user_logged_in()) {
$reason = 'logged-in-user';
return false;
}
if (is_preview() || is_customize_preview()) {
$reason = 'preview-request';
return false;
}
if (php_sapi_name() === 'cli') {
$reason = 'cli-context';
return false;
}
if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] !== 'GET') {
$reason = 'non-get-request';
return false;
}
if (defined('DOING_AJAX') && DOING_AJAX) {
$reason = 'ajax-request';
return false;
}
if (defined('REST_REQUEST') && REST_REQUEST) {
$reason = 'rest-request';
return false;
}
if (isset($_GET['preview']) || isset($_GET['customize_changeset_uuid'])) {
$reason = 'preview-query-flag';
return false;
}
$bypass_cookies = (array) apply_filters('rsc_bypass_cookies', [
'wordpress_logged_in_',
'wordpress_sec_',
'comment_author_',
'wp-postpass_',
'woocommerce_',
'wp_woocommerce_session_',
'edd_items_in_cart',
'edd_cart_hash',
]);
if (!empty($_COOKIE)) {
foreach (array_keys($_COOKIE) as $cookie_name) {
foreach ($bypass_cookies as $prefix) {
if ($prefix !== '' && strpos($cookie_name, $prefix) === 0) {
$reason = 'bypass-cookie:' . $prefix;
return false;
}
}
}
}
if (is_feed() || is_trackback() || is_robots() || is_search()) {
$reason = 'non-html-endpoint';
return false;
}
$reason = 'ok';
return true;
}
/**
* Requests eligible for output optimization, even when page caching is bypassed.
*/
private function can_optimize_output_request(&$reason = null) {
if (is_admin()) {
$reason = 'admin-request';
return false;
}
if ($this->is_current_page_excluded()) {
$reason = 'page-excluded';
return false;
}
// Disable all output optimizations for logged-in users.
if (is_user_logged_in()) {
$reason = 'logged-in-user';
return false;
}
if (php_sapi_name() === 'cli') {
$reason = 'cli-context';
return false;
}
if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] !== 'GET') {
$reason = 'non-get-request';
return false;
}
if (defined('DOING_AJAX') && DOING_AJAX) {
$reason = 'ajax-request';
return false;
}
if (defined('REST_REQUEST') && REST_REQUEST) {
$reason = 'rest-request';
return false;
}
if (is_feed() || is_trackback() || is_robots()) {
$reason = 'non-html-endpoint';
return false;
}
$reason = 'ok';
return true;
}
private function get_cache_file() {
$uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : wp_parse_url(home_url('/'), PHP_URL_HOST);
$scheme = is_ssl() ? 'https' : 'http';
$key = rsc_get_cache_key($uri, $host, $scheme);
return $this->cache_dir . 'pages/' . $key . '.html';
}
private function get_cache_header_file() {
$uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : wp_parse_url(home_url('/'), PHP_URL_HOST);
$scheme = is_ssl() ? 'https' : 'http';
$key = rsc_get_cache_key($uri, $host, $scheme);
return $this->cache_dir . 'pages/' . $key . '.headers.json';
}
private function get_cache_meta_file() {
$uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : wp_parse_url(home_url('/'), PHP_URL_HOST);
$scheme = is_ssl() ? 'https' : 'http';
$key = rsc_get_cache_key($uri, $host, $scheme);
return $this->cache_dir . 'pages/' . $key . '.meta.json';
}
public function serve_cache() {
$reason = '';
if (!$this->is_cacheable_request($reason)) {
return;
}
$file = $this->get_cache_file();
$header_file = $this->get_cache_header_file();
if (file_exists($file) && (time() - filemtime($file)) < $this->cache_ttl()) {
$mtime = filemtime($file);
$ttl = $this->cache_ttl();
$cached_header_names = [];
foreach ($this->read_cached_headers($header_file) as $header_line) {
$name = strtolower(trim(strtok($header_line, ':')));
if ($name !== '') {
$cached_header_names[$name] = true;
}
$replace = ($name === 'content-type');
header($header_line, $replace);
}
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $mtime) . ' GMT');
if (empty($cached_header_names['cache-control'])) {
header("Cache-Control: public, max-age={$ttl}");
}
if (empty($cached_header_names['expires'])) {
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $ttl) . ' GMT');
}
header('X-RSC-Cache: HIT');
if (empty($cached_header_names['content-type'])) {
header('Content-Type: text/html; charset=UTF-8');
}
if (empty($cached_header_names['vary'])) {
header('Vary: Cookie');
}
$etag = '"' . md5_file($file) . '"';
header("ETag: {$etag}");
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && trim($_SERVER['HTTP_IF_NONE_MATCH']) === $etag) {
$this->log('Cache 304 response', [
'file' => basename($file),
'reason' => $reason,
]);
header('HTTP/1.1 304 Not Modified');
exit;
}
$this->log('Cache HIT served', [
'file' => basename($file),
'ttl' => $ttl,
]);
readfile($file);
exit;
}
$this->log('Cache MISS from disk', [
'file' => basename($file),
]);
}
public function start_buffer() {
$optimize_reason = '';
if (!$this->can_optimize_output_request($optimize_reason)) {
return;
}
$cache_reason = '';
if ($this->is_cacheable_request($cache_reason)) {
header('X-RSC-Cache: MISS');
$this->log('Output buffering started', [
'cache' => 'MISS',
]);
} else {
header('X-RSC-Cache: BYPASS');
$this->log('Output buffering started', [
'cache' => 'BYPASS',
'reason' => $cache_reason,
]);
}
ob_start([$this, 'process_output']);
}
public function end_buffer() {
if (ob_get_level() > 0 && ob_get_length() !== false) {
ob_end_flush();
}
}
private function minify_html($html) {
return $this->get_minifier()->minify_html((string) $html);
}
private function minify_css($css) {
return $this->get_minifier()->minify_css((string) $css);
}
private function get_rucss_module() {
if (!($this->rucss instanceof RSC_Remove_Unused_CSS)) {
$this->rucss = new RSC_Remove_Unused_CSS($this->cache_dir, $this->cache_url);
}
return $this->rucss;
}
private function get_script_deferrer() {
if (!($this->script_deferrer instanceof RSC_Script_Deferrer)) {
$this->script_deferrer = new RSC_Script_Deferrer();
}
return $this->script_deferrer;