-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudscale-cleanup.php
More file actions
4538 lines (4045 loc) · 246 KB
/
cloudscale-cleanup.php
File metadata and controls
4538 lines (4045 loc) · 246 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: CloudScale Cleanup
* Plugin URI: https://andrewbaker.ninja
* Description: Database and media library cleanup with dry-run preview, image optimisation, PNG to JPEG conversion, and chunked processing safe on any server. Free, open source, no subscriptions.
* Version: 2.4.2
* Author: Andrew Baker
* Author URI: https://andrewbaker.ninja
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: cloudscale-cleanup
* Requires at least: 6.0
* Requires PHP: 7.4
*/
if ( ! defined( 'ABSPATH' ) ) { exit; }
define( 'CLOUDSCALE_CLEANUP_VERSION', '2.4.2' );
define( 'CLOUDSCALE_CLEANUP_DIR', plugin_dir_path( __FILE__ ) );
define( 'CLOUDSCALE_CLEANUP_URL', plugin_dir_url( __FILE__ ) );
define( 'CLOUDSCALE_CLEANUP_SLUG', 'cloudscale-cleanup' );
// On deactivation, wipe old asset files so next install gets fresh files
register_deactivation_hook( __FILE__, function() {
$dir = CLOUDSCALE_CLEANUP_DIR;
// Clean root-level assets
foreach ( glob( $dir . 'admin.{js,css}', GLOB_BRACE ) as $f ) { wp_delete_file( $f ); }
// Clean old assets/ subdirectory
$assets = $dir . 'assets/';
if ( is_dir( $assets ) ) {
foreach ( glob( $assets . '*' ) as $f ) { if ( is_file( $f ) ) { wp_delete_file( $f ); } }
rmdir( $assets );
}
} );
// Clear opcode cache on activation so updated files take effect immediately
register_activation_hook( __FILE__, function() {
if ( function_exists( 'opcache_reset' ) ) {
opcache_reset();
}
csc_cleanup_stale_assets();
} );
// Also clear on every admin page load if version changed
add_action( 'admin_init', function() {
$cached_version = get_option( 'csc_loaded_version', '' );
if ( $cached_version !== CLOUDSCALE_CLEANUP_VERSION ) {
if ( function_exists( 'opcache_reset' ) ) {
opcache_reset();
}
csc_cleanup_stale_assets();
update_option( 'csc_loaded_version', CLOUDSCALE_CLEANUP_VERSION );
}
} );
/**
* Remove ALL old asset files from the assets directory.
* WordPress plugin upload does not always overwrite existing files in
* subdirectories. By deleting all admin-v* files on version change,
* we guarantee the zip extraction writes fresh copies.
*/
function csc_cleanup_stale_assets() {
$dir = CLOUDSCALE_CLEANUP_DIR;
// Clean old assets/ subdirectory from previous versions
$assets = $dir . 'assets/';
if ( is_dir( $assets ) ) {
foreach ( glob( $assets . '*' ) as $f ) { if ( is_file( $f ) ) { wp_delete_file( $f ); } }
rmdir( $assets );
}
}
/*
* CHUNKED PROCESSING ARCHITECTURE
* ─────────────────────────────────────────────────────────────────────────────
* Every "run" operation works in three AJAX steps:
*
* Step 1 csc_*_start — Build the full list of IDs to process, store in a
* transient, return the total count to JS.
*
* Step 2 csc_*_chunk — Pull the transient, process one small batch, update
* the transient with the remaining IDs, return log
* lines + remaining count. JS fires repeatedly until
* remaining === 0.
*
* Step 3 csc_*_finish — Clean up the transient, write the last-run
* timestamp, return a summary line.
*
* Each AJAX request completes in well under 30 seconds on any shared host.
* Chunk sizes: 50 DB items · 25 image deletions · 5 image optimisations.
*/
define( 'CSC_CHUNK_DB', 50 );
define( 'CSC_CHUNK_IMAGES', 25 );
define( 'CSC_CHUNK_OPTIMISE', 5 );
// PNG to JPEG converter constants
define( 'CSPJ_OPTION_CHUNK_MB', 'cspj_chunk_mb' );
define( 'CSPJ_DEFAULT_CHUNK_MB', 1.5 );
define( 'CSPJ_MAX_TOTAL_MB', 200 );
// ─── Admin menu ──────────────────────────────────────────────────────────────
add_action( 'admin_menu', 'csc_add_menu' );
function csc_add_menu() {
add_management_page(
'CloudScale Cleanup',
'🌩️ CloudScale Cleanup',
'manage_options',
CLOUDSCALE_CLEANUP_SLUG,
'csc_render_page'
);
}
// ─── Enqueue assets ──────────────────────────────────────────────────────────
add_action( 'admin_enqueue_scripts', 'csc_enqueue_assets' );
/**
* Return the versioned filename for a JS/CSS asset. The build script creates
* admin-{ver}.js/.css files in the zip. If the versioned file exists, use it;
* otherwise fall back to the original (ensures nothing breaks).
*/
function csc_get_versioned_asset( string $ext ): string {
$ver_slug = str_replace( '.', '-', CLOUDSCALE_CLEANUP_VERSION );
$dest_name = 'admin-' . $ver_slug . '.' . $ext;
if ( file_exists( CLOUDSCALE_CLEANUP_DIR . $dest_name ) ) {
return $dest_name;
}
return 'admin.' . $ext;
}
function csc_enqueue_assets( $hook ) {
if ( $hook !== 'tools_page_cloudscale-cleanup' ) {
return;
}
$css_file = csc_get_versioned_asset( 'css' );
$js_file = csc_get_versioned_asset( 'js' );
wp_enqueue_style(
'cloudscale-cleanup-css',
CLOUDSCALE_CLEANUP_URL . $css_file,
array(),
CLOUDSCALE_CLEANUP_VERSION
);
wp_enqueue_script(
'cloudscale-cleanup-js',
CLOUDSCALE_CLEANUP_URL . $js_file,
array( 'jquery' ),
CLOUDSCALE_CLEANUP_VERSION,
true
);
$cspj_chunk_mb = csc_get_cspj_chunk_mb();
$cspj_server_max = csc_get_cspj_server_max_mb();
$csc_nonce = wp_create_nonce( 'csc_nonce' );
wp_localize_script( 'cloudscale-cleanup-js', 'CSC', array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => $csc_nonce,
'cspj_chunk_mb' => $cspj_chunk_mb,
'cspj_server_max_mb' => $cspj_server_max,
'cspj_max_total_mb' => CSPJ_MAX_TOTAL_MB,
'version' => CLOUDSCALE_CLEANUP_VERSION,
) );
// Fallback: ensure CSC is always available even if wp_localize_script fails.
$csc_fallback_js = 'if(typeof CSC==="undefined"||!CSC.ajax_url){'
. 'window.CSC=window.CSC||{};'
. 'CSC.ajax_url=CSC.ajax_url||' . wp_json_encode( admin_url( 'admin-ajax.php' ) ) . ';'
. 'CSC.nonce=CSC.nonce||' . wp_json_encode( $csc_nonce ) . ';'
. 'CSC.cspj_chunk_mb=CSC.cspj_chunk_mb||' . wp_json_encode( $cspj_chunk_mb ) . ';'
. 'CSC.cspj_server_max_mb=CSC.cspj_server_max_mb||' . wp_json_encode( $cspj_server_max ) . ';'
. 'CSC.cspj_max_total_mb=CSC.cspj_max_total_mb||' . intval( CSPJ_MAX_TOTAL_MB ) . ';'
. 'CSC.version=CSC.version||' . wp_json_encode( CLOUDSCALE_CLEANUP_VERSION ) . ';'
. 'console.log("[CSC] Fallback CSC injected inline. wp_localize_script may not have fired.");'
. '}';
wp_add_inline_script( 'cloudscale-cleanup-js', $csc_fallback_js );
// Tab colours and health metric styles — inline fallback (cache proof).
$csc_inline_css = '
.csc-tab:nth-child(1) { background: linear-gradient(135deg, #4a148c 0%, #7b1fa2 100%) !important; border-top-color: #ce93d8 !important; }
.csc-tab:nth-child(1).active, .csc-tab:nth-child(1):hover { border-top-color: #ce93d8 !important; }
.csc-tab:nth-child(6) { background: linear-gradient(135deg, #5d4037 0%, #8d6e63 100%) !important; border-top-color: #bcaaa4 !important; }
.csc-tab:nth-child(6).active, .csc-tab:nth-child(6):hover { border-top-color: #bcaaa4 !important; }
div[style*="#fff3e0"] .csc-health-metric,
div[style*="#e3f2fd"] .csc-health-metric,
div[style*="#f3e5f5"] .csc-health-metric { background: transparent !important; border-color: transparent !important; }
div[style*="#fff3e0"] .csc-health-metric-label { color: #e65100 !important; }
div[style*="#fff3e0"] .csc-health-metric-value { color: #e65100 !important; }
div[style*="#efebe9"] .csc-health-metric { background: transparent !important; border-color: transparent !important; }
div[style*="#efebe9"] .csc-health-metric-label { color: #4e342e !important; }
div[style*="#efebe9"] .csc-health-metric-value:not(#hm-weeks-left) { color: #4e342e !important; }
div[style*="#f3e5f5"] .csc-health-metric-label { color: #7b1fa2 !important; }
div[style*="#f3e5f5"] .csc-health-metric-value { color: #7b1fa2 !important; }
.csc-health-metric { border: none !important; }';
wp_add_inline_style( 'cloudscale-cleanup-css', $csc_inline_css );
// Health render, guard, and button handlers — inline (cache proof).
$csc_health_js = <<<'ENDJS'
(function() {
var el = document.getElementById('hm-weeks-left');
if (!el) return;
var obs = new MutationObserver(function() {
var t = el.textContent || '';
if (t.match(/\d{4,}.*wk/i) || t.match(/~\d+.*mo/i)) {
el.textContent = '>> 2 Years';
el.style.color = '#2e7d32';
}
});
obs.observe(el, { childList: true, characterData: true, subtree: true });
})();
(function() {
var target = document.getElementById('tab-site-health');
if (!target) return;
var obs = new MutationObserver(function() {
var bad = document.querySelectorAll('[style*="grid-column"]');
bad.forEach(function(el) {
if (el.textContent && el.textContent.indexOf('Max Resource') >= 0) {
el.remove();
}
});
});
obs.observe(target, { childList: true, subtree: true });
})();
jQuery(function($) {
var fmt = function(b) { if (b >= 1073741824) return (b/1073741824).toFixed(2)+' GB'; if (b >= 1048576) return (b/1048576).toFixed(1)+' MB'; return (b/1024).toFixed(0)+' KB'; };
var ragColors = {green:'#2e7d32',amber:'#e65100',red:'#c62828',grey:'#78909c'};
var ragBgs = {green:'#e8f5e9',amber:'#fff3e0',red:'#ffebee',grey:'#f5f5f5'};
var ragLabels = {green:'6+ months of disk space remaining',amber:'3 to 6 months of disk space remaining',red:'Less than 3 months of disk space remaining',grey:'Collecting weekly data to calculate trend'};
function cscHealthRender(d) {
var rag = d.disk_rag || 'grey';
$('#csc-health-rag-bar').css('background', ragBgs[rag]);
$('#csc-health-rag-dot').css('background', ragColors[rag]);
$('#csc-health-rag-label').text(rag === 'grey' ? 'Collecting Data' : rag.charAt(0).toUpperCase()+rag.slice(1)).css('color', ragColors[rag]);
$('#csc-health-rag-detail').text(ragLabels[rag] || '').css('color', ragColors[rag]);
$('#hm-disk-used').text(fmt(d.disk_used));
$('#hm-disk-free').text(fmt(d.disk_free));
$('#hm-disk-total').text(fmt(d.disk_total));
$('#hm-db-size').text(fmt(d.db_size));
$('#hm-growth').text(d.growth_per_week > 0 ? fmt(d.growth_per_week)+'/wk' : (d.weekly_count >= 2 ? 'Stable' : 'Collecting\u2026'));
if (d.weeks_remaining > 104) {
$('#hm-weeks-left').text('>> 2 Years').css('color', '#2e7d32');
} else if (d.weeks_remaining > 0) {
var wl = Math.round(d.weeks_remaining);
var wlColor = d.disk_rag === 'red' ? '#c62828' : (d.disk_rag === 'amber' ? '#e65100' : '#2e7d32');
$('#hm-weeks-left').text(wl + ' weeks').css('color', wlColor);
} else if (d.growth_per_week <= 0 && d.weekly_count >= 2) {
$('#hm-weeks-left').text('Stable').css('color', '#2e7d32');
} else { $('#hm-weeks-left').text('\u2014').css('color',''); }
var cpuNow = d.cpu_pct_now >= 0 ? d.cpu_pct_now+'%' : '\u2014';
if (d.cpu_load_now >= 0) cpuNow += ' (load '+d.cpu_load_now.toFixed(2)+')';
$('#hm-cpu-now').text(cpuNow);
$('#hm-cpu-24h').text(d.cpu_pct_max_24h >= 0 ? d.cpu_pct_max_24h+'%' : '\u2014');
$('#hm-cpu-7d').text(d.cpu_pct_max_7d >= 0 ? d.cpu_pct_max_7d+'%' : '\u2014');
var memNow = d.mem_pct_now >= 0 ? d.mem_pct_now+'%' : '\u2014';
if (d.mem_used_now >= 0 && d.mem_total > 0) memNow += ' ('+fmt(d.mem_used_now)+' / '+fmt(d.mem_total)+')';
$('#hm-mem-now').text(memNow);
$('#hm-mem-24h').text(d.mem_pct_max_24h >= 0 ? d.mem_pct_max_24h+'%' : '\u2014');
$('#hm-mem-7d').text(d.mem_pct_max_7d >= 0 ? d.mem_pct_max_7d+'%' : '\u2014');
if (d.max_resource_now !== undefined) {
$('[style*="grid-column:1/-1"]').filter(function(){ return $(this).text().indexOf('Max Resource') >= 0; }).remove();
var $memGrid = $('#hm-mem-7d').closest('[style*="grid"]');
if ($memGrid.length && !$('#hm-maxres-now').length) {
$memGrid.after('<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-top:10px">' +
'<div class="csc-health-metric"><div class="csc-health-metric-label">Max Resource (now)</div><div class="csc-health-metric-value" id="hm-maxres-now">—</div></div>' +
'<div class="csc-health-metric"><div class="csc-health-metric-label">Max Resource (24h)</div><div class="csc-health-metric-value" id="hm-maxres-24h">—</div></div>' +
'<div class="csc-health-metric"><div class="csc-health-metric-label">Max Resource (7d)</div><div class="csc-health-metric-value" id="hm-maxres-7d">—</div></div>' +
'</div>');
}
if (d.max_resource_now >= 0) $('#hm-maxres-now').text(d.max_resource_now + '%');
if (d.max_resource_24h >= 0) $('#hm-maxres-24h').text(d.max_resource_24h + '%');
if (d.max_resource_7d >= 0) $('#hm-maxres-7d').text(d.max_resource_7d + '%');
}
$('#hm-hourly-count').text(d.hourly_count);
$('#hm-weekly-count').text(d.weekly_count);
$('#hm-last-hourly').text(d.last_hourly || 'Never');
$('#hm-last-weekly').text(d.last_weekly || 'Never');
$('#hm-data-span').text(d.weeks_of_data > 0 ? d.weeks_of_data : '0');
$('#csc-health-loading').hide();
$('#csc-health-content').show();
}
if ($('#csc-health-loading').is(':visible')) {
$.post(CSC.ajax_url, { action: 'csc_health_get', nonce: CSC.nonce }, function(resp) {
if (resp.success) cscHealthRender(resp.data);
});
}
$(document).on('click', '#btn-health-refresh', function() {
var $b = $(this).prop('disabled',true).html('\u23f3 Loading\u2026');
$.post(CSC.ajax_url, { action: 'csc_health_get', nonce: CSC.nonce }, function(resp) {
$b.prop('disabled',false).html('\ud83d\udd04 Refresh');
if (resp.success) cscHealthRender(resp.data);
}).fail(function(){ $b.prop('disabled',false).html('\ud83d\udd04 Refresh'); });
});
$(document).on('click', '#btn-health-collect', function() {
var $b = $(this).prop('disabled',true).html('\u23f3 Collecting\u2026');
$.post(CSC.ajax_url, { action: 'csc_health_collect_now', nonce: CSC.nonce }, function(resp) {
$b.prop('disabled',false).html('\ud83d\udcca Collect Now');
if (resp.success && resp.data.health) cscHealthRender(resp.data.health);
}).fail(function(){ $b.prop('disabled',false).html('\ud83d\udcca Collect Now'); });
});
$(document).on('click', '#btn-sysstat-test', function() {
var $b = $(this).prop('disabled',true).html('\u23f3 Testing...');
var blue = {background:'#e3f2fd',borderColor:'#90caf9'};
var $box = $('#csc-sysstat-status').show().css(blue);
$('#csc-sysstat-label').text('Testing sysstat...').css('color','#1565c0');
$('#csc-sysstat-icon').text('\u23f3');
$('#csc-sysstat-detail').text('').css('color','#1565c0');
$('#csc-sysstat-instructions').hide();
$.post(CSC.ajax_url, { action: 'csc_health_sysstat_test', nonce: CSC.nonce }, function(resp) {
$b.prop('disabled',false).html('\ud83d\udd27 Test Sysstat');
$box.css(blue);
if (!resp.success) { $('#csc-sysstat-icon').text('\u274c'); $('#csc-sysstat-label').text('Test failed'); return; }
var d = resp.data;
if (!d.exec_available) {
$('#csc-sysstat-icon').text('\u274c'); $('#csc-sysstat-label').text('exec() disabled in php.ini');
} else if (!d.sar_installed) {
$('#csc-sysstat-icon').text('\u274c'); $('#csc-sysstat-label').text('sysstat not installed');
if (d.instructions) $('#csc-sysstat-detail').html('<code style="font-size:11px">'+d.instructions.replace(/Run: /, '')+'</code>');
} else if (!d.sysstat_active) {
$('#csc-sysstat-icon').text('\u26a0\ufe0f'); $('#csc-sysstat-label').text('sysstat installed but service inactive');
$('#csc-sysstat-detail').html(d.sar_version+' at '+d.sar_path+' — <code style="font-size:11px">sudo systemctl enable sysstat && sudo systemctl start sysstat</code>');
} else if (!d.sar_has_data) {
$('#csc-sysstat-icon').text('\ud83d\udd35'); $('#csc-sysstat-label').text('sysstat v'+d.sar_version+' active, waiting for first samples');
$('#csc-sysstat-detail').text('Collects every 10 minutes. Refresh after 10 mins.');
} else {
$('#csc-sysstat-icon').text('\u2705'); $('#csc-sysstat-label').text('sysstat v'+d.sar_version+' working');
$('#csc-sysstat-detail').text(d.sar_samples+' samples/hr | CPU '+d.cpu_pct_now+'% | Mem '+d.mem_pct_now+'%');
}
}).fail(function(){ $b.prop('disabled',false).html('\ud83d\udd27 Test Sysstat'); $('#csc-sysstat-icon').text('\u274c'); $('#csc-sysstat-label').text('Network error'); });
});
});
ENDJS;
wp_add_inline_script( 'cloudscale-cleanup-js', $csc_health_js, 'after' );
}
// ─── Admin dashboard widget ───────────────────────────────────────────────────
add_action( 'wp_dashboard_setup', 'csc_register_dashboard_widget' );
function csc_register_dashboard_widget() {
wp_add_dashboard_widget(
'csc_dashboard_widget',
'🥷 AndrewBaker.Ninja CloudScale Cleanup',
'csc_render_dashboard_widget'
);
}
function csc_render_dashboard_widget() {
$last_db = get_option( 'csc_last_db_cleanup', null );
$last_img = get_option( 'csc_last_img_cleanup', null );
$last_opt = get_option( 'csc_last_img_optimise', null );
$fmt = function ( $val ) {
return $val
? '<span style="font-size:12px;font-weight:700;color:#fff">' . esc_html( human_time_diff( strtotime( $val ), current_time( 'timestamp' ) ) . ' ago' ) . '</span>'
: '<span style="font-size:12px;font-weight:700;color:rgba(255,255,255,0.5)">Not yet run</span>';
};
// Health data
$weekly = get_option( CSC_HEALTH_WEEKLY_KEY, array() );
$health = ( count( $weekly ) >= 2 && function_exists( 'csc_health_calculate' ) ) ? csc_health_calculate() : null;
$rag = $health ? $health['disk_rag'] : 'grey';
$rag_map = array(
'green' => array( 'label' => 'Healthy', 'bg' => 'linear-gradient(135deg,#2e7d32 0%,#43a047 100%)', 'shadow' => 'rgba(46,125,50,0.35)' ),
'amber' => array( 'label' => 'Warning', 'bg' => 'linear-gradient(135deg,#e65100 0%,#f57c00 100%)', 'shadow' => 'rgba(230,81,0,0.35)' ),
'red' => array( 'label' => 'Critical', 'bg' => 'linear-gradient(135deg,#b71c1c 0%,#e53935 100%)', 'shadow' => 'rgba(183,28,28,0.35)' ),
'grey' => array( 'label' => 'Collecting', 'bg' => 'linear-gradient(135deg,#546e7a 0%,#78909c 100%)', 'shadow' => 'rgba(84,110,122,0.35)' ),
);
$rag_info = isset( $rag_map[ $rag ] ) ? $rag_map[ $rag ] : $rag_map['grey'];
$db_url = admin_url( 'tools.php?page=cloudscale-cleanup&tab=db-cleanup' );
$img_url = admin_url( 'tools.php?page=cloudscale-cleanup&tab=img-cleanup' );
$opt_url = admin_url( 'tools.php?page=cloudscale-cleanup&tab=img-optimise' );
$health_url = admin_url( 'tools.php?page=cloudscale-cleanup&tab=site-health' );
$tile = 'display:block;text-decoration:none;border-radius:8px;padding:10px 8px;text-align:center;transition:filter 0.15s,transform 0.15s;cursor:pointer';
$hover = "onmouseover=\"this.style.filter='brightness(1.15)';this.style.transform='scale(1.03)'\" onmouseout=\"this.style.filter='';this.style.transform=''\"";
?>
<div style="padding:4px 0 8px">
<p style="margin:0 0 14px;font-size:13px;color:#50575e;line-height:1.5">
CloudScale Cleanup is keeping your database and media library lean —
revisions, transients, unused media, and unregistered files all handled.
</p>
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-bottom:10px">
<a href="<?php echo esc_url( $db_url ); ?>" style="<?php echo $tile; ?>;background:linear-gradient(135deg,#1565c0 0%,#1976d2 100%);box-shadow:0 2px 6px rgba(21,101,192,0.35)" <?php echo $hover; ?>>
<div style="font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:rgba(255,255,255,0.7);margin-bottom:5px">⚡ DB Cleanup</div>
<?php echo $fmt( $last_db ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
</a>
<a href="<?php echo esc_url( $img_url ); ?>" style="<?php echo $tile; ?>;background:linear-gradient(135deg,#4527a0 0%,#5e35b1 100%);box-shadow:0 2px 6px rgba(69,39,160,0.35)" <?php echo $hover; ?>>
<div style="font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:rgba(255,255,255,0.7);margin-bottom:5px">🖼 Unused Media</div>
<?php echo $fmt( $last_img ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
</a>
<a href="<?php echo esc_url( $opt_url ); ?>" style="<?php echo $tile; ?>;background:linear-gradient(135deg,#00695c 0%,#00897b 100%);box-shadow:0 2px 6px rgba(0,105,92,0.35)" <?php echo $hover; ?>>
<div style="font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:rgba(255,255,255,0.7);margin-bottom:5px">✨ Img Optimise</div>
<?php echo $fmt( $last_opt ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
</a>
<a href="<?php echo esc_url( $health_url ); ?>" style="<?php echo $tile; ?>;background:<?php echo $rag_info['bg']; ?>;box-shadow:0 2px 6px <?php echo $rag_info['shadow']; ?>" <?php echo $hover; ?>>
<div style="font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:0.5px;color:rgba(255,255,255,0.7);margin-bottom:5px">📊 Site Health</div>
<span style="font-size:12px;font-weight:700;color:#fff"><?php echo esc_html( $rag_info['label'] ); ?></span>
</a>
</div>
<?php if ( $health ) : ?>
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-bottom:16px;font-size:11px;text-align:center">
<div style="background:#f0f2f5;border-radius:6px;padding:6px 4px">
<div style="color:#78909c;font-weight:600;margin-bottom:2px">Disk Used</div>
<div style="font-weight:700;color:#263238"><?php echo esc_html( size_format( $health['disk_used'], 1 ) ); ?></div>
</div>
<div style="background:#f0f2f5;border-radius:6px;padding:6px 4px">
<div style="color:#78909c;font-weight:600;margin-bottom:2px">Disk Free</div>
<div style="font-weight:700;color:#263238"><?php echo esc_html( size_format( $health['disk_free'], 1 ) ); ?></div>
</div>
<div style="background:#f0f2f5;border-radius:6px;padding:6px 4px">
<div style="color:#78909c;font-weight:600;margin-bottom:2px">Growth/Wk</div>
<div style="font-weight:700;color:#263238"><?php echo $health['growth_per_week'] > 0 ? esc_html( size_format( $health['growth_per_week'], 1 ) ) : '—'; ?></div>
</div>
<div style="background:#f0f2f5;border-radius:6px;padding:6px 4px">
<div style="color:#78909c;font-weight:600;margin-bottom:2px">Est. Storage Full</div>
<div style="font-weight:700;color:#263238"><?php echo $health['weeks_remaining'] > 104 ? '>> 2 Yrs' : ( $health['weeks_remaining'] > 0 ? esc_html( round( $health['weeks_remaining'] ) ) : '—' ); ?></div>
</div>
</div>
<?php else : ?>
<p style="margin:0 0 16px;font-size:11px;color:#90a4ae;text-align:center">📊 Health metrics collecting — summary available after first weekly snapshot.</p>
<?php endif; ?>
<div style="display:flex;flex-direction:column;gap:10px">
<a href="https://andrewbaker.ninja" target="_blank" rel="noopener"
style="display:flex;align-items:center;justify-content:center;gap:8px;background:linear-gradient(135deg,#f953c6 0%,#b91d73 40%,#4f46e5 100%);color:#fff;font-weight:700;font-size:13px;padding:10px 16px;border-radius:8px;text-decoration:none;box-shadow:0 3px 10px rgba(249,83,198,0.4);transition:filter 0.15s,transform 0.15s"
onmouseover="this.style.filter='brightness(1.15)';this.style.transform='scale(1.02)'"
onmouseout="this.style.filter='';this.style.transform=''">
<span style="font-size:15px">🥷</span> Visit AndrewBaker.Ninja
</a>
<a href="<?php echo esc_url( admin_url( 'tools.php?page=cloudscale-cleanup' ) ); ?>"
style="display:flex;align-items:center;justify-content:center;gap:8px;background:linear-gradient(135deg,#0ea5e9 0%,#0369a1 100%);color:#fff;font-weight:700;font-size:13px;padding:10px 16px;border-radius:8px;text-decoration:none;box-shadow:0 3px 10px rgba(14,165,233,0.35);transition:filter 0.15s,transform 0.15s"
onmouseover="this.style.filter='brightness(1.15)';this.style.transform='scale(1.02)'"
onmouseout="this.style.filter='';this.style.transform=''">
<span style="font-size:15px">⚡</span> Open CloudScale Cleanup
</a>
<a href="<?php echo esc_url( admin_url( 'tools.php?page=cloudscale-cleanup&tab=png-to-jpeg' ) ); ?>"
style="display:flex;align-items:center;justify-content:center;gap:8px;background:linear-gradient(135deg,#689f38 0%,#8bc34a 100%);color:#fff;font-weight:700;font-size:13px;padding:10px 16px;border-radius:8px;text-decoration:none;box-shadow:0 3px 10px rgba(104,159,56,0.35);transition:filter 0.15s,transform 0.15s"
onmouseover="this.style.filter='brightness(1.15)';this.style.transform='scale(1.02)'"
onmouseout="this.style.filter='';this.style.transform=''">
<span style="font-size:15px">🖼</span> PNG to JPEG
</a>
</div>
</div>
<?php
}
// ─── Front-end sidebar widget ─────────────────────────────────────────────────
/*
* Registers a widget visible in Appearance -> Widgets (classic widget screen)
* and the block editor widget screen. Drag it into any sidebar or widget area
* in your theme to show it on the front end of the site.
*/
add_action( 'widgets_init', function () {
register_widget( 'CSC_Front_Widget' );
} );
class CSC_Front_Widget extends WP_Widget {
public function __construct() {
parent::__construct(
'csc_front_widget',
'CloudScale Cleanup',
array(
'description' => 'Shows last cleanup run times and links to the CloudScale Cleanup plugin and andrewbaker.ninja.',
'classname' => 'widget-csc-cleanup',
)
);
}
/** Render the widget on the front end */
public function widget( $args, $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : 'Site Maintenance';
$last_db = get_option( 'csc_last_db_cleanup', null );
$last_img = get_option( 'csc_last_img_cleanup', null );
$last_opt = get_option( 'csc_last_img_optimise', null );
// Site health RAG
$health_rag = 'grey';
$health_label = 'Collecting';
$weekly = get_option( CSC_HEALTH_WEEKLY_KEY, array() );
if ( count( $weekly ) >= 2 && function_exists( 'csc_health_calculate' ) ) {
$h = csc_health_calculate();
$health_rag = $h['disk_rag'];
if ( $health_rag === 'green' ) { $health_label = 'Healthy'; }
elseif ( $health_rag === 'amber' ) { $health_label = 'Warning'; }
elseif ( $health_rag === 'red' ) { $health_label = 'Critical'; }
}
echo $args['before_widget'];
echo $args['before_title'] . esc_html( $title ) . $args['after_title'];
?>
<div class="csc-front-widget">
<ul class="csc-fw-list">
<li>
<span class="csc-fw-label">DB Cleanup</span>
<span class="csc-fw-value"><?php echo $last_db ? esc_html( human_time_diff( strtotime( $last_db ), current_time( 'timestamp' ) ) . ' ago' ) : 'Never run'; ?></span>
</li>
<li>
<span class="csc-fw-label">Unused Media</span>
<span class="csc-fw-value"><?php echo $last_img ? esc_html( human_time_diff( strtotime( $last_img ), current_time( 'timestamp' ) ) . ' ago' ) : 'Never run'; ?></span>
</li>
<li>
<span class="csc-fw-label">Img Optimise</span>
<span class="csc-fw-value"><?php echo $last_opt ? esc_html( human_time_diff( strtotime( $last_opt ), current_time( 'timestamp' ) ) . ' ago' ) : 'Never run'; ?></span>
</li>
<li>
<span class="csc-fw-label">Site Health</span>
<?php
$rag_colors = array( 'green' => '#2e7d32', 'amber' => '#e65100', 'red' => '#c62828', 'grey' => '#78909c' );
$rag_color = isset( $rag_colors[ $health_rag ] ) ? $rag_colors[ $health_rag ] : '#78909c';
?>
<span class="csc-fw-value" style="color:<?php echo esc_attr( $rag_color ); ?>">● <?php echo esc_html( $health_label ); ?></span>
</li>
</ul>
<div class="csc-fw-links">
<a href="https://andrewbaker.ninja" target="_blank" rel="noopener" class="csc-fw-link">andrewbaker.ninja</a>
<?php if ( current_user_can( 'manage_options' ) ) : ?>
<a href="<?php echo esc_url( admin_url( 'tools.php?page=cloudscale-cleanup' ) ); ?>" class="csc-fw-link csc-fw-link-admin">Run Cleanup</a>
<?php endif; ?>
</div>
<p class="csc-fw-credit">Powered by <a href="https://andrewbaker.ninja" target="_blank" rel="noopener">CloudScale Cleanup</a></p>
</div>
<?php
echo $args['after_widget'];
}
/** Settings form in Appearance -> Widgets */
public function form( $instance ) {
$title = ! empty( $instance['title'] ) ? $instance['title'] : 'Site Maintenance';
?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">Title:</label>
<input class="widefat"
id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"
type="text" value="<?php echo esc_attr( $title ); ?>">
</p>
<?php
}
/** Save widget settings */
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = sanitize_text_field( $new_instance['title'] );
return $instance;
}
}
// Inline CSS for the front-end widget — only loaded when widget is active
add_action( 'wp_enqueue_scripts', 'csc_enqueue_front_widget_styles' );
function csc_enqueue_front_widget_styles() {
if ( ! is_active_widget( false, false, 'csc_front_widget', true ) ) {
return;
}
wp_add_inline_style( 'wp-block-library', '
.csc-front-widget{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;font-size:13.5px}
.csc-fw-list{margin:0 0 12px;padding:0;list-style:none}
.csc-fw-list li{display:flex;justify-content:space-between;align-items:center;padding:6px 0;border-bottom:1px solid rgba(0,0,0,.07)}
.csc-fw-list li:last-child{border-bottom:none}
.csc-fw-label{color:#555;font-size:12.5px}
.csc-fw-value{font-weight:600;color:#1a1f2e;font-size:12.5px}
.csc-fw-links{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px}
.csc-fw-link{display:inline-block;font-size:12px;font-weight:600;padding:6px 12px;border-radius:5px;text-decoration:none;background:#1a1f2e;color:#fff!important;transition:background .15s}
.csc-fw-link:hover{background:#4a9eff;color:#fff!important}
.csc-fw-link-admin{background:#27ae60}
.csc-fw-link-admin:hover{background:#219150}
.csc-fw-credit{font-size:11px;color:#999;margin:0}
.csc-fw-credit a{color:#4a9eff;text-decoration:none}
' );
}
// ─── Settings save ────────────────────────────────────────────────────────────
add_action( 'wp_ajax_csc_save_settings', 'csc_ajax_save_settings' );
function csc_ajax_save_settings() {
check_ajax_referer( 'csc_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( 'Insufficient permissions.' );
}
$scalars = array(
'csc_post_revisions_age', 'csc_drafts_age', 'csc_trash_age',
'csc_autodraft_age', 'csc_spam_comments_age', 'csc_trash_comments_age',
'csc_img_max_width', 'csc_img_max_height', 'csc_img_quality',
'csc_schedule_db_hour', 'csc_schedule_img_hour',
'csc_clean_revisions', 'csc_clean_drafts', 'csc_clean_trashed', 'csc_clean_autodrafts',
'csc_clean_transients', 'csc_clean_orphan_post', 'csc_clean_orphan_user',
'csc_clean_spam_comments', 'csc_clean_trash_comments',
);
$bools = array(
'csc_schedule_db_enabled', 'csc_schedule_img_enabled', 'csc_convert_png_to_jpg',
);
$arrays = array( 'csc_schedule_db_days', 'csc_schedule_img_days' );
foreach ( $scalars as $f ) {
if ( isset( $_POST[ $f ] ) ) {
$val = sanitize_text_field( wp_unslash( $_POST[ $f ] ) );
// Toggle fields: only accept '0' or '1'
if ( in_array( $f, array(
'csc_clean_revisions', 'csc_clean_drafts', 'csc_clean_trashed', 'csc_clean_autodrafts',
'csc_clean_transients', 'csc_clean_orphan_post', 'csc_clean_orphan_user',
'csc_clean_spam_comments', 'csc_clean_trash_comments',
), true ) ) {
$val = $val === '1' ? '1' : '0';
}
update_option( $f, $val );
}
}
foreach ( $bools as $f ) {
update_option( $f, isset( $_POST[ $f ] ) ? '1' : '0' );
}
foreach ( $arrays as $f ) {
update_option( $f, isset( $_POST[ $f ] ) && is_array( $_POST[ $f ] )
? array_map( 'sanitize_text_field', $_POST[ $f ] )
: array()
);
}
csc_schedule_crons();
wp_send_json_success( 'Settings saved.' );
}
// ─── Cron scheduling ─────────────────────────────────────────────────────────
function csc_schedule_crons() {
wp_clear_scheduled_hook( 'csc_scheduled_db_cleanup' );
if ( get_option( 'csc_schedule_db_enabled', '0' ) === '1' ) {
$ts = csc_next_run_timestamp(
(array) get_option( 'csc_schedule_db_days', array() ),
intval( get_option( 'csc_schedule_db_hour', 3 ) )
);
if ( $ts ) { wp_schedule_single_event( $ts, 'csc_scheduled_db_cleanup' ); }
}
wp_clear_scheduled_hook( 'csc_scheduled_img_cleanup' );
if ( get_option( 'csc_schedule_img_enabled', '0' ) === '1' ) {
$ts = csc_next_run_timestamp(
(array) get_option( 'csc_schedule_img_days', array() ),
intval( get_option( 'csc_schedule_img_hour', 4 ) )
);
if ( $ts ) { wp_schedule_single_event( $ts, 'csc_scheduled_img_cleanup' ); }
}
}
function csc_next_run_timestamp( $days, $hour ) {
$map = array(
'mon' => 'Monday', 'tue' => 'Tuesday', 'wed' => 'Wednesday',
'thu' => 'Thursday', 'fri' => 'Friday', 'sat' => 'Saturday', 'sun' => 'Sunday',
);
$now = current_time( 'timestamp' );
$best = null;
foreach ( $days as $d ) {
$d = strtolower( trim( $d ) );
if ( ! isset( $map[ $d ] ) ) { continue; }
$candidate = strtotime( 'next ' . $map[ $d ], $now );
$candidate = mktime( $hour, 0, 0, date( 'n', $candidate ), date( 'j', $candidate ), date( 'Y', $candidate ) );
if ( $candidate <= $now ) { $candidate += WEEK_IN_SECONDS; }
if ( $best === null || $candidate < $best ) { $best = $candidate; }
}
return $best;
}
// Cron handlers — run synchronously (no HTTP chunking needed in a cron context)
add_action( 'csc_scheduled_db_cleanup', 'csc_cron_db_cleanup' );
function csc_cron_db_cleanup() {
$ids = csc_build_db_id_list();
foreach ( $ids['revisions'] as $id ) { wp_delete_post( intval( $id ), true ); }
foreach ( $ids['drafts'] as $id ) { wp_delete_post( intval( $id ), true ); }
foreach ( $ids['trashed'] as $id ) { wp_delete_post( intval( $id ), true ); }
foreach ( $ids['autodrafts'] as $id ) { wp_delete_post( intval( $id ), true ); }
csc_delete_expired_transients();
csc_delete_orphaned_postmeta();
csc_delete_orphaned_usermeta();
foreach ( $ids['spam_comments'] as $id ) { wp_delete_comment( intval( $id ), true ); }
foreach ( $ids['trash_comments'] as $id ) { wp_delete_comment( intval( $id ), true ); }
update_option( 'csc_last_db_cleanup', current_time( 'mysql' ) );
update_option( 'csc_last_scheduled_db_cleanup', current_time( 'mysql' ) );
csc_schedule_crons();
}
add_action( 'csc_scheduled_img_cleanup', 'csc_cron_img_cleanup' );
function csc_cron_img_cleanup() {
$used = csc_get_used_attachment_ids();
$all = get_posts( array(
'post_type' => 'attachment', 'post_status' => 'inherit',
'posts_per_page' => -1, 'fields' => 'ids',
) );
// Load existing media recycle manifest
if ( ! csc_media_recycle_ensure_dir() ) {
return;
}
$manifest = csc_media_recycle_read_manifest();
$recycled = 0;
foreach ( $all as $id ) {
if ( isset( $used[ $id ] ) ) { continue; }
try {
$result = csc_media_recycle_save_attachment( intval( $id ) );
if ( ! empty( $result['error'] ) ) {
error_log( '[CSC] Cron recycle error for ID ' . $id . ': ' . $result['error'] );
continue;
}
$manifest[ (string) $id ] = array(
'post' => $result['post'],
'meta' => $result['meta'],
'files_moved' => $result['files_moved'],
'recycled_at' => current_time( 'mysql' ),
);
wp_delete_attachment( $id, true );
$recycled++;
} catch ( Exception $e ) {
error_log( '[CSC] Cron recycle exception for ID ' . $id . ': ' . $e->getMessage() );
} catch ( Throwable $e ) {
error_log( '[CSC] Cron recycle fatal for ID ' . $id . ': ' . $e->getMessage() );
}
}
if ( ! csc_media_recycle_write_manifest( $manifest ) ) {
error_log( '[CSC] Cron: Failed to write media recycle manifest.' );
}
error_log( '[CSC] Cron: Recycled ' . $recycled . ' unused attachment(s). Total in recycle bin: ' . count( $manifest ) );
update_option( 'csc_last_img_cleanup', current_time( 'mysql' ) );
update_option( 'csc_last_scheduled_img_cleanup', current_time( 'mysql' ) );
csc_schedule_crons();
}
// ═════════════════════════════════════════════════════════════════════════════
// DATABASE CLEANUP
// ═════════════════════════════════════════════════════════════════════════════
function csc_build_db_id_list( $overrides = array() ) {
global $wpdb;
$ra = intval( get_option( 'csc_post_revisions_age', 30 ) );
$da = intval( get_option( 'csc_drafts_age', 90 ) );
$ta = intval( get_option( 'csc_trash_age', 30 ) );
$aa = intval( get_option( 'csc_autodraft_age', 7 ) );
$sa = intval( get_option( 'csc_spam_comments_age', 30 ) );
$tca = intval( get_option( 'csc_trash_comments_age', 30 ) );
$tog = function( $opt ) use ( $overrides ) {
if ( ! empty( $overrides ) ) {
// Full UI submission passed — absent key means toggled off
return isset( $overrides[ $opt ] ) && $overrides[ $opt ] === '1';
}
return get_option( $opt, '1' ) === '1';
};
return array(
'revisions' => $tog( 'csc_clean_revisions' ) ? $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_type='revision' AND post_date < DATE_SUB(NOW(), INTERVAL %d DAY)", $ra ) ) : array(),
'drafts' => $tog( 'csc_clean_drafts' ) ? $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_status='draft' AND post_type='post' AND post_date < DATE_SUB(NOW(), INTERVAL %d DAY)", $da ) ) : array(),
'trashed' => $tog( 'csc_clean_trashed' ) ? $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_status='trash' AND post_date < DATE_SUB(NOW(), INTERVAL %d DAY)", $ta ) ) : array(),
'autodrafts' => $tog( 'csc_clean_autodrafts' ) ? $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_status='auto-draft' AND post_date < DATE_SUB(NOW(), INTERVAL %d DAY)", $aa ) ) : array(),
'spam_comments' => $tog( 'csc_clean_spam_comments' ) ? $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_approved='spam' AND comment_date < DATE_SUB(NOW(), INTERVAL %d DAY)", $sa ) ) : array(),
'trash_comments' => $tog( 'csc_clean_trash_comments' ) ? $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_approved='trash' AND comment_date < DATE_SUB(NOW(), INTERVAL %d DAY)", $tca ) ) : array(),
);
}
function csc_delete_expired_transients() {
global $wpdb;
$keys = $wpdb->get_col( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_%' AND option_value < UNIX_TIMESTAMP()" );
foreach ( $keys as $k ) { delete_transient( str_replace( '_transient_timeout_', '', $k ) ); }
return count( $keys );
}
function csc_delete_orphaned_postmeta() {
global $wpdb;
return (int) $wpdb->query( "DELETE pm FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON pm.post_id = p.ID WHERE p.ID IS NULL" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- No user input; table names are trusted $wpdb properties.
}
function csc_delete_orphaned_usermeta() {
global $wpdb;
return (int) $wpdb->query( "DELETE um FROM {$wpdb->usermeta} um LEFT JOIN {$wpdb->users} u ON um.user_id = u.ID WHERE u.ID IS NULL" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- No user input; table names are trusted $wpdb properties.
}
// Dry run
add_action( 'wp_ajax_csc_scan_db', 'csc_ajax_scan_db' );
function csc_ajax_scan_db() {
check_ajax_referer( 'csc_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( 'Insufficient permissions.' );
}
// Read toggle state from POST if provided (live UI state), otherwise fall back to DB.
// If ANY toggle key is present in POST, we treat this as a full UI submission —
// missing keys default to '0' rather than falling back to DB, preventing stale DB
// values from overriding the user's current screen state.
$has_post_toggles = isset( $_POST['csc_clean_revisions'] )
|| isset( $_POST['csc_clean_drafts'] )
|| isset( $_POST['csc_clean_transients'] );
$toggle = function( $opt ) use ( $has_post_toggles ) {
if ( $has_post_toggles ) {
// Full UI submission — use POST value, absent = '0' (toggled off)
return isset( $_POST[ $opt ] ) && $_POST[ $opt ] === '1';
}
// No UI data sent (e.g. scheduled run) — use DB
return get_option( $opt, '1' ) === '1';
};
global $wpdb;
$ra = intval( get_option( 'csc_post_revisions_age', 30 ) );
$da = intval( get_option( 'csc_drafts_age', 90 ) );
$ta = intval( get_option( 'csc_trash_age', 30 ) );
$aa = intval( get_option( 'csc_autodraft_age', 7 ) );
$sa = intval( get_option( 'csc_spam_comments_age', 30 ) );
$tca = intval( get_option( 'csc_trash_comments_age', 30 ) );
$toggle_keys = array(
'csc_clean_revisions', 'csc_clean_drafts', 'csc_clean_trashed', 'csc_clean_autodrafts',
'csc_clean_transients', 'csc_clean_orphan_post', 'csc_clean_orphan_user',
'csc_clean_spam_comments', 'csc_clean_trash_comments',
);
$lines = array();
if ( $toggle( 'csc_clean_revisions' ) ) {
$revisions = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title, post_date FROM {$wpdb->posts} WHERE post_type='revision' AND post_date < DATE_SUB(NOW(), INTERVAL %d DAY) ORDER BY post_date DESC LIMIT 1000", $ra ) );
$lines[] = array( 'type' => 'section', 'text' => 'Post Revisions (older than ' . $ra . ' days)' );
foreach ( $revisions as $r ) { $lines[] = array( 'type' => 'item', 'text' => ' [REVISION] ID ' . $r->ID . ' — ' . esc_html( $r->post_title ) . ' (' . $r->post_date . ')' ); }
$lines[] = array( 'type' => 'count', 'text' => ' Found: ' . count( $revisions ) );
} else {
$lines[] = array( 'type' => 'section', 'text' => 'Post Revisions — SKIPPED (disabled)' );
}
if ( $toggle( 'csc_clean_drafts' ) ) {
$drafts = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title, post_date FROM {$wpdb->posts} WHERE post_status='draft' AND post_type='post' AND post_date < DATE_SUB(NOW(), INTERVAL %d DAY) ORDER BY post_date DESC LIMIT 500", $da ) );
$lines[] = array( 'type' => 'section', 'text' => 'Draft Posts (older than ' . $da . ' days)' );
foreach ( $drafts as $d ) { $lines[] = array( 'type' => 'item', 'text' => ' [DRAFT] ID ' . $d->ID . ' — ' . esc_html( $d->post_title ) . ' (' . $d->post_date . ')' ); }
$lines[] = array( 'type' => 'count', 'text' => ' Found: ' . count( $drafts ) );
} else {
$lines[] = array( 'type' => 'section', 'text' => 'Draft Posts — SKIPPED (disabled)' );
}
if ( $toggle( 'csc_clean_trashed' ) ) {
$trashed = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title, post_modified FROM {$wpdb->posts} WHERE post_status='trash' AND post_date < DATE_SUB(NOW(), INTERVAL %d DAY) ORDER BY post_modified DESC LIMIT 500", $ta ) );
$lines[] = array( 'type' => 'section', 'text' => 'Trashed Posts (older than ' . $ta . ' days)' );
foreach ( $trashed as $t ) { $lines[] = array( 'type' => 'item', 'text' => ' [TRASH] ID ' . $t->ID . ' — ' . esc_html( $t->post_title ) . ' (' . $t->post_modified . ')' ); }
$lines[] = array( 'type' => 'count', 'text' => ' Found: ' . count( $trashed ) );
} else {
$lines[] = array( 'type' => 'section', 'text' => 'Trashed Posts — SKIPPED (disabled)' );
}
if ( $toggle( 'csc_clean_autodrafts' ) ) {
$cnt_auto = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status='auto-draft' AND post_date < DATE_SUB(NOW(), INTERVAL %d DAY)", $aa ) );
$lines[] = array( 'type' => 'section', 'text' => 'Auto-Drafts (older than ' . $aa . ' days)' );
$lines[] = array( 'type' => 'count', 'text' => ' Found: ' . $cnt_auto );
} else {
$lines[] = array( 'type' => 'section', 'text' => 'Auto-Drafts — SKIPPED (disabled)' );
}
if ( $toggle( 'csc_clean_transients' ) ) {
$cnt_t = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_%' AND option_value < UNIX_TIMESTAMP()" );
$lines[] = array( 'type' => 'section', 'text' => 'Expired Transients' );
$lines[] = array( 'type' => 'count', 'text' => ' Found: ' . $cnt_t );
} else {
$lines[] = array( 'type' => 'section', 'text' => 'Expired Transients — SKIPPED (disabled)' );
}
if ( $toggle( 'csc_clean_orphan_post' ) ) {
$cnt_pm = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON pm.post_id = p.ID WHERE p.ID IS NULL" );
$lines[] = array( 'type' => 'section', 'text' => 'Orphaned Post Meta' );
$lines[] = array( 'type' => 'count', 'text' => ' Found: ' . $cnt_pm . ' rows' );
} else {
$lines[] = array( 'type' => 'section', 'text' => 'Orphaned Post Meta — SKIPPED (disabled)' );
}
if ( $toggle( 'csc_clean_orphan_user' ) ) {
$cnt_um = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->usermeta} um LEFT JOIN {$wpdb->users} u ON um.user_id = u.ID WHERE u.ID IS NULL" );
$lines[] = array( 'type' => 'section', 'text' => 'Orphaned User Meta' );
$lines[] = array( 'type' => 'count', 'text' => ' Found: ' . $cnt_um . ' rows' );
} else {
$lines[] = array( 'type' => 'section', 'text' => 'Orphaned User Meta — SKIPPED (disabled)' );
}
if ( $toggle( 'csc_clean_spam_comments' ) ) {
$cnt_spam = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->comments} WHERE comment_approved='spam' AND comment_date < DATE_SUB(NOW(), INTERVAL %d DAY)", $sa ) );
$lines[] = array( 'type' => 'section', 'text' => 'Spam Comments (older than ' . $sa . ' days)' );
$lines[] = array( 'type' => 'count', 'text' => ' Found: ' . $cnt_spam );
} else {
$lines[] = array( 'type' => 'section', 'text' => 'Spam Comments — SKIPPED (disabled)' );
}
if ( $toggle( 'csc_clean_trash_comments' ) ) {
$cnt_tc = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->comments} WHERE comment_approved='trash' AND comment_date < DATE_SUB(NOW(), INTERVAL %d DAY)", $tca ) );
$lines[] = array( 'type' => 'section', 'text' => 'Trashed Comments (older than ' . $tca . ' days)' );
$lines[] = array( 'type' => 'count', 'text' => ' Found: ' . $cnt_tc );
} else {
$lines[] = array( 'type' => 'section', 'text' => 'Trashed Comments — SKIPPED (disabled)' );
}
wp_send_json_success( $lines );
}
// Chunked run — Step 1: build queue
add_action( 'wp_ajax_csc_db_start', 'csc_ajax_db_start' );
function csc_ajax_db_start() {
check_ajax_referer( 'csc_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( 'Insufficient permissions.' );
}
// Collect any toggle overrides sent from the live UI
$toggle_keys = array(
'csc_clean_revisions', 'csc_clean_drafts', 'csc_clean_trashed', 'csc_clean_autodrafts',
'csc_clean_transients', 'csc_clean_orphan_post', 'csc_clean_orphan_user',
'csc_clean_spam_comments', 'csc_clean_trash_comments',
);
$overrides = array();
foreach ( $toggle_keys as $k ) {
if ( isset( $_POST[ $k ] ) ) {
$overrides[ $k ] = $_POST[ $k ] === '1' ? '1' : '0';
}
}
$has_post_toggles = isset( $_POST['csc_clean_revisions'] )
|| isset( $_POST['csc_clean_drafts'] )
|| isset( $_POST['csc_clean_transients'] );
$tog = function( $opt ) use ( $overrides, $has_post_toggles ) {
if ( $has_post_toggles ) {
return isset( $overrides[ $opt ] ) && $overrides[ $opt ] === '1';
}
return get_option( $opt, '1' ) === '1';
};
$ids = csc_build_db_id_list( $overrides );
$queue = array();
foreach ( $ids['revisions'] as $id ) { $queue[] = array( 'type' => 'post', 'id' => intval( $id ), 'label' => 'revision' ); }
foreach ( $ids['drafts'] as $id ) { $queue[] = array( 'type' => 'post', 'id' => intval( $id ), 'label' => 'draft' ); }
foreach ( $ids['trashed'] as $id ) { $queue[] = array( 'type' => 'post', 'id' => intval( $id ), 'label' => 'trashed post' ); }
foreach ( $ids['autodrafts'] as $id ) { $queue[] = array( 'type' => 'post', 'id' => intval( $id ), 'label' => 'auto-draft' ); }
foreach ( $ids['spam_comments'] as $id ) { $queue[] = array( 'type' => 'comment', 'id' => intval( $id ), 'label' => 'spam comment' ); }
foreach ( $ids['trash_comments'] as $id ) { $queue[] = array( 'type' => 'comment', 'id' => intval( $id ), 'label' => 'trashed comment' ); }
if ( $tog( 'csc_clean_transients' ) ) { $queue[] = array( 'type' => 'transients', 'id' => 0, 'label' => 'expired transients' ); }
if ( $tog( 'csc_clean_orphan_post' ) ) { $queue[] = array( 'type' => 'orphan_post', 'id' => 0, 'label' => 'orphaned postmeta' ); }
if ( $tog( 'csc_clean_orphan_user' ) ) { $queue[] = array( 'type' => 'orphan_user', 'id' => 0, 'label' => 'orphaned usermeta' ); }
set_transient( 'csc_db_queue', $queue, HOUR_IN_SECONDS );
wp_send_json_success( array(
'total' => count( $queue ),
'remaining' => count( $queue ),
'lines' => array( array( 'type' => 'info', 'text' => ' Work queue built: ' . count( $queue ) . ' items.' ) ),
) );
}
// Step 2: process a chunk
add_action( 'wp_ajax_csc_db_chunk', 'csc_ajax_db_chunk' );
function csc_ajax_db_chunk() {
check_ajax_referer( 'csc_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( 'Insufficient permissions.' );
}
$queue = get_transient( 'csc_db_queue' );
if ( ! is_array( $queue ) ) { wp_send_json_error( 'Session expired — please start again.' ); }
$chunk = array_splice( $queue, 0, CSC_CHUNK_DB );
set_transient( 'csc_db_queue', $queue, HOUR_IN_SECONDS );
$lines = array();
foreach ( $chunk as $item ) {
switch ( $item['type'] ) {
case 'post':
wp_delete_post( $item['id'], true );
$lines[] = array( 'type' => 'deleted', 'text' => ' Deleted ' . $item['label'] . ' ID ' . $item['id'] );
break;
case 'comment':
wp_delete_comment( $item['id'], true );
$lines[] = array( 'type' => 'deleted', 'text' => ' Deleted ' . $item['label'] . ' ID ' . $item['id'] );
break;
case 'transients':
$n = csc_delete_expired_transients();
$lines[] = array( 'type' => 'count', 'text' => ' Deleted ' . $n . ' expired transients.' );
break;
case 'orphan_post':
$n = csc_delete_orphaned_postmeta();
$lines[] = array( 'type' => 'count', 'text' => ' Deleted ' . $n . ' orphaned postmeta rows.' );
break;
case 'orphan_user':
$n = csc_delete_orphaned_usermeta();
$lines[] = array( 'type' => 'count', 'text' => ' Deleted ' . $n . ' orphaned usermeta rows.' );
break;
}
}
wp_send_json_success( array( 'remaining' => count( $queue ), 'lines' => $lines ) );
}