-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththisismyurl-revision-reaper.php
More file actions
1067 lines (964 loc) · 51.1 KB
/
Copy paththisismyurl-revision-reaper.php
File metadata and controls
1067 lines (964 loc) · 51.1 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
/**
* Author: Christopher Ross
* Author URI: https://thisismyurl.com/
* Plugin Name: Revision Reaper by Christopher Ross
* Plugin URI: https://thisismyurl.com/thisismyurl-revision-reaper/
* Description: Non-destructive database optimization with persistent settings, custom scheduling, and email reporting.
* Version: 1.6190.1550
* Requires at least: 6.4
* Requires PHP: 8.1
* Text Domain: thisismyurl-revision-reaper
* Domain Path: /languages
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* @package Thisismyurl_Revision_Reaper
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! defined( 'TIMU_REVISION_REAPER_VERSION' ) ) {
define( 'TIMU_REVISION_REAPER_VERSION', '1.6164.1421' );
}
require_once __DIR__ . '/includes/class-exporter.php';
require_once __DIR__ . '/includes/class-site-health.php';
require_once __DIR__ . '/includes/abilities.php';
if ( defined( 'WP_CLI' ) && WP_CLI ) {
require_once __DIR__ . '/includes/class-cli.php';
}
/**
* Class TIMU_Revision_Reaper
* Handles database cleanup for revisions, trash, and spam with automated scheduling.
*/
class TIMU_Revision_Reaper {
/**
* Initialize plugin hooks.
*/
public static function init() {
add_action( 'admin_menu', array( __CLASS__, 'add_admin_menu' ) );
add_action( 'wp_ajax_timu_rr_purge_item', array( __CLASS__, 'ajax_purge_item' ) );
add_action( 'wp_ajax_timu_rr_optimize_db', array( __CLASS__, 'ajax_optimize_db' ) );
add_action( 'wp_ajax_timu_rr_pre_run_export', array( __CLASS__, 'ajax_pre_run_export' ) );
add_action( 'admin_post_timu_rr_run', array( __CLASS__, 'handle_run_post' ) );
add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_admin_assets' ) );
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( __CLASS__, 'add_plugin_action_links' ) );
// Automated schedule hook
add_action( 'timu_rr_scheduled_cleanup', array( __CLASS__, 'do_scheduled_cleanup' ) );
}
public static function add_admin_menu() {
add_management_page(
__( 'Revision Reaper', 'thisismyurl-revision-reaper' ),
__( 'Revision Reaper', 'thisismyurl-revision-reaper' ),
'manage_options',
'revision-reaper',
array( __CLASS__, 'render_admin_page' )
);
}
/**
* Enqueue the admin runner script — only on our own Tools page.
*
* Uses wp_localize_script() to pass the nonce, items list, run mode,
* and translatable strings. Avoids inline <script> tags entirely.
*
* @param string $hook_suffix Current admin page hook.
* @return void
*/
public static function enqueue_admin_assets( $hook_suffix ) {
if ( 'tools_page_revision-reaper' !== $hook_suffix ) {
return;
}
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
wp_enqueue_script(
'timu-revision-reaper-admin',
plugins_url( 'assets/js/admin.js', __FILE__ ),
array( 'jquery' ),
TIMU_REVISION_REAPER_VERSION,
true
);
// Recompute the items list using the same transient gating the
// page render uses so the script and the page see the same state.
$user_id = get_current_user_id();
$run_intent_key = 'timu_rr_run_intent_' . $user_id;
$run_intent = isset( $_GET['reap'] ) ? get_transient( $run_intent_key ) : false; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$items = array();
$is_dry_run = false;
if ( $run_intent ) {
$settings = array(
'limit' => (int) get_option( 'timu_rr_limit', 3 ),
'include_trash' => (int) get_option( 'timu_rr_auto_trash', 0 ),
'include_spam' => (int) get_option( 'timu_rr_auto_spam', 0 ),
);
$items = self::get_eligible_items( $settings );
$is_dry_run = ( 'dry' === $run_intent );
}
wp_localize_script( 'timu-revision-reaper-admin', 'timuRevisionReaper', array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'timu_rr_nonce' ),
'items' => $items,
'isDryRun' => $is_dry_run,
'limit' => (int) get_option( 'timu_rr_limit', 3 ),
'i18n' => array(
'confirmBackup' => __( 'Please confirm the backup acknowledgement before running a live cleanup.', 'thisismyurl-revision-reaper' ),
'confirmStart' => __( 'Start live database cleanup? Items will be exported to JSON, then trashed.', 'thisismyurl-revision-reaper' ),
'cleanupFinished' => __( 'Cleanup finished. Optimizing tables...', 'thisismyurl-revision-reaper' ),
'simulationComplete' => __( 'Simulation complete. No changes made.', 'thisismyurl-revision-reaper' ),
'writingExport' => __( 'Writing pre-run export...', 'thisismyurl-revision-reaper' ),
'exportFailed' => __( 'Pre-run export failed.', 'thisismyurl-revision-reaper' ),
'exportRequestFailed' => __( 'Aborting: pre-run export request failed.', 'thisismyurl-revision-reaper' ),
),
) );
}
public static function add_plugin_action_links( $links ) {
$custom_links = array(
'<a href="' . esc_url( admin_url( 'tools.php?page=revision-reaper' ) ) . '">' . esc_html__( 'Settings', 'thisismyurl-revision-reaper' ) . '</a>',
'<a href="' . esc_url( 'https://github.com/sponsors/thisismyurl' ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Sponsor', 'thisismyurl-revision-reaper' ) . '</a>',
);
return array_merge( $custom_links, $links );
}
/**
* Automated cleanup logic with email reporting.
*/
public static function do_scheduled_cleanup() {
$settings = array(
'limit' => get_option( 'timu_rr_limit', 3 ),
'include_trash' => get_option( 'timu_rr_auto_trash', 0 ),
'include_spam' => get_option( 'timu_rr_auto_spam', 0 ),
);
$email = get_option( 'timu_rr_report_email', get_option( 'admin_email' ) );
$report = self::run_cleanup( $settings );
// Only email when the run actually cleaned something. A weekly
// "No items required cleaning" notice is the top driver of "why is
// this plugin emailing me" support tickets, so a quiet run stays
// silent. We gate on the per-category counts rather than the log,
// because the log carries bookkeeping lines (pre-run export written,
// etc.) even on a run that removed no rows.
$cleaned = (int) $report['revisions']
+ (int) $report['trashed_posts']
+ (int) $report['spam_comments']
+ (int) $report['transients']
+ (int) $report['tables'];
if ( ! empty( $email ) && $cleaned > 0 ) {
$subject = '[' . get_bloginfo( 'name' ) . '] Revision Reaper Automated Report';
$message = "The scheduled database cleanup has finished.\n\nItems Processed:\n" . implode( "\n", $report['log'] );
wp_mail( $email, $subject, $message );
}
}
/**
* Perform a full cleanup pass and return structured counts plus ROI.
*
* This is the canonical, UI-agnostic cleanup routine. The scheduled-cron
* handler, the WP-CLI command, and the Abilities API all funnel through
* here so the deletion rules and ROI maths live in exactly one place.
*
* The run is non-destructive in the same sense the rest of the plugin is:
* trashed posts are force-deleted only once they have aged past
* EMPTY_TRASH_DAYS, spam comments are moved to the comment trash (not
* force-deleted), and a JSON snapshot is written before any row is touched.
*
* @param array $settings { limit, include_trash, include_spam, include_revisions }.
* include_revisions is optional and defaults to true
* (the historical behaviour); set it false to skip the
* revision sweep entirely.
* @param array $caps Optional overrides forwarded to get_eligible_items().
* @param bool $dry_run When true, compute counts and ROI without deleting.
* @return array {
* @type int $revisions Posts whose surplus revisions were reaped.
* @type int $trashed_posts Trashed posts purged (aged past EMPTY_TRASH_DAYS).
* @type int $trash_skipped Trashed posts skipped (not yet old enough).
* @type int $spam_comments Spam comments moved to the comment trash.
* @type int $transients Expired transient pairs removed.
* @type int $tables Tables optimized.
* @type int $bytes_freed Bytes reclaimed from reaped revision rows.
* @type bool $dry_run Whether this was a preview run.
* @type string $export Snapshot file path, or '' when none was written.
* @type array $log Human-readable per-step log lines.
* }
*/
public static function run_cleanup( array $settings, array $caps = array(), $dry_run = false ) {
$dry_run = (bool) $dry_run;
$limit = max( 0, (int) $settings['limit'] );
$items = self::get_eligible_items( $settings, $caps );
$log = array();
$export = '';
// Revisions are swept by default; an explicit false opts out. We filter
// the eligible set rather than touch the shared scan so nothing excluded
// is ever snapshotted or deleted (mirrors the WP-CLI --include behaviour).
$include_revisions = ! array_key_exists( 'include_revisions', $settings ) || ! empty( $settings['include_revisions'] );
if ( ! $include_revisions ) {
$items = array_values( array_filter( $items, static function ( $item ) {
return 'revision' !== $item['type'];
} ) );
}
// Pre-delete snapshot so a regretted run can be reconstructed from
// disk. Skipped on a dry run — nothing is being removed to snapshot.
if ( ! $dry_run && ! empty( $items ) ) {
$export_path = TIMU_Revision_Reaper_Exporter::snapshot_before_run( $items, $limit );
if ( $export_path ) {
$export = $export_path;
$log[] = 'Pre-run export written: ' . wp_basename( $export_path );
} else {
$log[] = 'WARNING: pre-run export failed to write.';
}
}
$counts = array(
'revisions' => 0,
'trashed_posts' => 0,
'trash_skipped' => 0,
'spam_comments' => 0,
);
$bytes_freed = 0;
foreach ( $items as $item ) {
if ( 'trash' === $item['type'] ) {
// Non-destructive: delegate to WP's trash lifecycle. WP itself
// empties trash items older than EMPTY_TRASH_DAYS via the
// wp_scheduled_delete cron — we never force-delete the young.
if ( ! self::trash_post_eligible_for_purge( $item['id'] ) ) {
$counts['trash_skipped']++;
continue;
}
if ( ! $dry_run ) {
wp_delete_post( $item['id'], false );
}
$counts['trashed_posts']++;
$log[] = "Trashed Post #{$item['id']} purged (older than EMPTY_TRASH_DAYS)";
} elseif ( 'spam' === $item['type'] ) {
// Non-destructive: trash spam comments. Site owner can still
// recover from the Comments > Trash list before WP empties it.
if ( ! $dry_run ) {
wp_trash_comment( $item['id'] );
}
$counts['spam_comments']++;
$log[] = "Spam Comment #{$item['id']} moved to comment trash";
} else {
$revisions = wp_get_post_revisions( $item['id'] );
$to_remove = array_slice( $revisions, $limit );
foreach ( $to_remove as $rev ) {
// Honest ROI: count actual bytes the row contributed
// before we drop it. Sum of post_content lengths is the
// dominant component on a revision.
$bytes_freed += strlen( (string) $rev->post_content );
if ( ! $dry_run ) {
wp_delete_post_revision( $rev->ID );
}
}
$counts['revisions']++;
$log[] = "Reaped revisions for Post #{$item['id']}";
}
}
if ( $bytes_freed > 0 ) {
$log[] = sprintf( 'Bytes freed from revision rows: %s (%s)',
number_format_i18n( $bytes_freed ),
size_format( $bytes_freed )
);
}
// Expired transients live in wp_options (or sitemeta on multisite).
// Counting is inseparable from deletion in WP's helper, so a dry run
// reports a separately-measured eligible count instead.
$transients = $dry_run ? self::count_expired_transients() : self::delete_expired_transients();
if ( $transients > 0 ) {
$log[] = sprintf( 'Deleted %d expired transient pairs.', (int) $transients );
}
// Final database optimization (MyISAM tables only — InnoDB rebuilds
// on OPTIMIZE which is wasteful on a maintenance pass). No-op on a
// dry run; OPTIMIZE has no safe non-destructive preview.
$optimized = $dry_run ? 0 : self::optimize_wp_tables();
if ( $optimized > 0 ) {
$log[] = sprintf( 'Optimized %d tables.', (int) $optimized );
}
return array(
'revisions' => $counts['revisions'],
'trashed_posts' => $counts['trashed_posts'],
'trash_skipped' => $counts['trash_skipped'],
'spam_comments' => $counts['spam_comments'],
'transients' => (int) $transients,
'tables' => (int) $optimized,
'bytes_freed' => $bytes_freed,
'dry_run' => $dry_run,
'export' => $export,
'log' => $log,
);
}
/**
* Count expired transient pairs without deleting them.
*
* WP core's delete_expired_transients() returns void and always deletes,
* so a dry run needs its own read-only count of the same rows that helper
* would remove. Mirrors the LIKE clauses used in delete_expired_transients().
*
* @return int Number of expired transient *pairs* (value + timeout) eligible for removal.
*/
public static function count_expired_transients() {
global $wpdb;
// Timeout rows whose stored expiry is in the past. Each timeout row
// pairs with one value row, so the timeout count is the pair count.
$now = time();
return (int) $wpdb->get_var( $wpdb->prepare(
"SELECT COUNT(*) FROM {$wpdb->options}
WHERE ( option_name LIKE %s OR option_name LIKE %s )
AND option_value < %d",
$wpdb->esc_like( '_transient_timeout_' ) . '%',
$wpdb->esc_like( '_site_transient_timeout_' ) . '%',
$now
) );
}
/**
* Delete expired transients from wp_options (and sitemeta on multisite).
*
* WP core's delete_expired_transients() is the canonical implementation
* and we simply delegate to it — wrapping it here keeps the call site
* legible and lets us return a count for the run report.
*
* We pre-count only the *expired* pairs (the rows core is about to remove)
* with a single scan via count_expired_transients(), rather than counting
* all timeout rows twice (before and after). That earlier before/after
* delta meant three full passes over the timeout rows per run — two of our
* own counts plus core's own scan — when one read of the rows-to-be-removed
* gives the same report number.
*
* @return int Number of expired transient *pairs* (value + timeout) removed.
*/
public static function delete_expired_transients() {
$expired = self::count_expired_transients();
if ( function_exists( 'delete_expired_transients' ) ) {
delete_expired_transients( true );
}
return $expired;
}
/**
* OPTIMIZE TABLE the WordPress-owned tables only, skipping InnoDB.
*
* OPTIMIZE on InnoDB triggers a full table rebuild (ALGORITHM=COPY) which
* is wasteful as a maintenance task — InnoDB's own background cleanup
* already handles fragmentation. We restrict to MyISAM and Aria.
*
* @return int Number of tables optimized.
*/
public static function optimize_wp_tables() {
global $wpdb;
$tables_to_check = $wpdb->tables( 'all' );
if ( empty( $tables_to_check ) ) {
return 0;
}
// information_schema lookup so we know each table's engine.
$placeholders = implode( ',', array_fill( 0, count( $tables_to_check ), '%s' ) );
$sql = $wpdb->prepare(
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
"SELECT TABLE_NAME, ENGINE FROM information_schema.TABLES
WHERE TABLE_SCHEMA = %s AND TABLE_NAME IN ($placeholders)",
array_merge( array( DB_NAME ), $tables_to_check )
);
$rows = $wpdb->get_results( $sql ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
if ( empty( $rows ) ) {
return 0;
}
$optimized = 0;
foreach ( $rows as $row ) {
$engine = strtoupper( (string) $row->ENGINE );
if ( ! in_array( $engine, array( 'MYISAM', 'ARIA' ), true ) ) {
continue;
}
// %i is WP 6.2+ for identifier quoting — uses backticks safely.
$wpdb->query( $wpdb->prepare( 'OPTIMIZE TABLE %i', $row->TABLE_NAME ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
$optimized++;
}
return $optimized;
}
/**
* Validate a YYYY-MM-DD date string strictly.
*
* @param string $date Date string from $_POST.
* @return bool True when the input is a real Gregorian date in ISO form.
*/
public static function validate_iso_date( $date ) {
if ( ! is_string( $date ) || 1 !== preg_match( '/^\d{4}-\d{2}-\d{2}$/', $date ) ) {
return false;
}
$parts = explode( '-', $date );
return checkdate( (int) $parts[1], (int) $parts[2], (int) $parts[0] );
}
/**
* Validate a HH:MM (24-hour) time string strictly.
*
* @param string $time Time string from $_POST.
* @return bool True when the input is a real 24h time.
*/
public static function validate_iso_time( $time ) {
return is_string( $time ) && 1 === preg_match( '/^([01]\d|2[0-3]):[0-5]\d$/', $time );
}
/**
* Convert a site-local "Y-m-d H:i" string to a UTC timestamp.
*
* @param string $local Site-local datetime string.
* @return int|false UTC timestamp, or false on failure.
*/
public static function parse_site_local_to_utc( $local ) {
try {
$tz = wp_timezone();
$dt = new DateTimeImmutable( $local, $tz );
return $dt->getTimestamp();
} catch ( Exception $e ) {
return false;
}
}
/**
* Whether a trashed post has lived in trash long enough to be purged.
*
* Honours the EMPTY_TRASH_DAYS constant — same rule WP core uses in
* wp_scheduled_delete(). When EMPTY_TRASH_DAYS is 0 trash is disabled and
* we never purge; when it's missing/unset we fall back to WP's 30-day
* default. Only the post's own _wp_trash_meta_time is consulted.
*
* @param int $post_id Post ID to inspect.
* @return bool True when the post is older than EMPTY_TRASH_DAYS.
*/
public static function trash_post_eligible_for_purge( $post_id ) {
$days = defined( 'EMPTY_TRASH_DAYS' ) ? (int) EMPTY_TRASH_DAYS : 30;
if ( $days <= 0 ) {
// Trash is disabled site-wide; never purge from a "trash" worker.
return false;
}
$trashed_at = (int) get_post_meta( $post_id, '_wp_trash_meta_time', true );
if ( $trashed_at <= 0 ) {
// No trash timestamp — be conservative, don't purge.
return false;
}
return ( time() - $trashed_at ) >= ( $days * DAY_IN_SECONDS );
}
/**
* Scan database for eligible items using paged WP_Query.
*
* Hard caps are applied so a site with 100k posts doesn't trip an OOM or
* a wpdb timeout on a single render. Operators who want everything in
* one pass should use the WP-CLI command, which streams batches.
*
* @param array $settings { limit, include_trash, include_spam }.
* @param array $caps Optional overrides: { batch_size, max_items, post_types }.
* @return array
*/
public static function get_eligible_items( $settings, $caps = array() ) {
$defaults = array(
// Per-query batch size. 200 keeps wp_get_post_revisions() loops bounded.
'batch_size' => 200,
// Total items returned across all types in one call.
'max_items' => 1000,
// Public + private CPTs only. 'any' silently includes attachments
// and revisions and is never what we want here.
'post_types' => self::get_target_post_types(),
);
$caps = array_merge( $defaults, $caps );
$items = array();
$remaining = (int) $caps['max_items'];
// 1. Posts whose revision count exceeds the keep limit.
$paged = 1;
$rev_done = false;
while ( ! $rev_done && $remaining > 0 ) {
$q = new WP_Query( array(
'post_type' => $caps['post_types'],
'post_status' => array( 'publish', 'future', 'draft', 'pending', 'private' ),
'posts_per_page' => $caps['batch_size'],
'paged' => $paged,
'fields' => 'ids',
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'orderby' => 'ID',
'order' => 'ASC',
) );
if ( empty( $q->posts ) ) {
break;
}
foreach ( $q->posts as $post_id ) {
$revisions = wp_get_post_revisions( $post_id, array( 'fields' => 'ids' ) );
if ( count( $revisions ) > (int) $settings['limit'] ) {
$items[] = array( 'id' => (int) $post_id, 'type' => 'revision' );
$remaining--;
if ( $remaining <= 0 ) {
$rev_done = true;
break;
}
}
}
if ( count( $q->posts ) < $caps['batch_size'] ) {
break;
}
$paged++;
}
// 2. Trashed posts. Same chunking.
if ( ! empty( $settings['include_trash'] ) && $remaining > 0 ) {
$paged = 1;
while ( $remaining > 0 ) {
$trash = get_posts( array(
'post_status' => 'trash',
'posts_per_page' => $caps['batch_size'],
'paged' => $paged,
'fields' => 'ids',
'post_type' => $caps['post_types'],
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'orderby' => 'ID',
'order' => 'ASC',
) );
if ( empty( $trash ) ) {
break;
}
foreach ( $trash as $id ) {
$items[] = array( 'id' => (int) $id, 'type' => 'trash' );
$remaining--;
if ( $remaining <= 0 ) {
break 2;
}
}
if ( count( $trash ) < $caps['batch_size'] ) {
break;
}
$paged++;
}
}
// 3. Spam comments — split auto vs manual; only auto is reaped.
if ( ! empty( $settings['include_spam'] ) && $remaining > 0 ) {
$offset = 0;
while ( $remaining > 0 ) {
$spam = get_comments( array(
'status' => 'spam',
'fields' => 'ids',
'number' => $caps['batch_size'],
'offset' => $offset,
'orderby' => 'comment_ID',
'order' => 'ASC',
) );
if ( empty( $spam ) ) {
break;
}
foreach ( $spam as $comment_id ) {
if ( ! self::is_auto_spam( (int) $comment_id ) ) {
// Manual spam — operator marked this; respect that
// signal and never auto-purge.
continue;
}
$items[] = array( 'id' => (int) $comment_id, 'type' => 'spam' );
$remaining--;
if ( $remaining <= 0 ) {
break 2;
}
}
if ( count( $spam ) < $caps['batch_size'] ) {
break;
}
$offset += $caps['batch_size'];
}
}
return $items;
}
/**
* Public+private custom post types this plugin is willing to scan.
* Excludes attachments and revisions explicitly — those have their own
* lifecycles and are never what we mean by "scan for old revisions."
*
* @return string[]
*/
public static function get_target_post_types() {
$types = get_post_types( array( 'show_ui' => true ), 'names' );
unset( $types['attachment'], $types['revision'], $types['nav_menu_item'] );
return array_values( $types );
}
/**
* Distinguish Akismet auto-spam from manually-marked spam.
*
* Akismet stores akismet_result=spam and a history meta entry on
* comments it flags. Anything without that signature was marked spam
* by a human moderator and we don't auto-purge it.
*
* @param int $comment_id Comment ID.
* @return bool True if this looks like Akismet auto-spam.
*/
public static function is_auto_spam( $comment_id ) {
$akismet_result = get_comment_meta( $comment_id, 'akismet_result', true );
if ( 'true' === $akismet_result || 'spam' === $akismet_result ) {
return true;
}
$history = get_comment_meta( $comment_id, 'akismet_as_submitted', true );
if ( ! empty( $history ) ) {
return true;
}
// No Akismet on the site at all? Treat as auto so the plugin remains
// useful — operator opted into "include spam" knowing what that meant.
if ( ! function_exists( 'is_plugin_active' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
if ( ! is_plugin_active( 'akismet/akismet.php' ) && ! function_exists( 'akismet_init' ) ) {
return true;
}
return false;
}
/**
* AJAX: Purge single item.
*/
public static function ajax_purge_item() {
check_ajax_referer( 'timu_rr_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( 'Unauthorized' ); }
$id = absint( $_POST['item_id'] ?? 0 );
$type = isset( $_POST['item_type'] ) ? sanitize_key( wp_unslash( $_POST['item_type'] ) ) : '';
$is_dry_run = isset( $_POST['dry_run'] ) && 'true' === $_POST['dry_run'];
// Resolve revision-keep limit server-side — never trust the client-supplied value.
// For revision items: apply the per-post-type limit when one is configured.
$global_limit = (int) get_option( 'timu_rr_limit', 3 );
$pt_limits = get_option( 'timu_rr_post_type_limits', array() );
$pt_limits = is_array( $pt_limits ) ? $pt_limits : array();
if ( 'revision' === $type && $id > 0 ) {
$post_type = get_post_type( get_post( $id )->post_parent ?? $id );
$limit = ( $post_type && isset( $pt_limits[ $post_type ] ) )
? (int) $pt_limits[ $post_type ]
: $global_limit;
} else {
$limit = $global_limit;
}
// Whitelist item types — anything else is rejected.
if ( ! in_array( $type, array( 'revision', 'trash', 'spam' ), true ) ) {
wp_send_json_error( esc_html__( 'Invalid item type.', 'thisismyurl-revision-reaper' ), 400 );
}
if ( $id <= 0 ) {
wp_send_json_error( esc_html__( 'Invalid item ID.', 'thisismyurl-revision-reaper' ), 400 );
}
if ( $is_dry_run ) {
wp_send_json_success( sprintf(
/* translators: 1: numeric item ID, 2: item type slug */
esc_html__( '[DRY RUN] Would process item #%1$d (%2$s)', 'thisismyurl-revision-reaper' ),
$id,
esc_html( $type )
) );
}
switch ( $type ) {
case 'revision':
$revisions = wp_get_post_revisions( $id );
$to_remove = array_slice( $revisions, $limit );
foreach ( $to_remove as $rev ) { wp_delete_post_revision( $rev->ID ); }
wp_send_json_success( sprintf(
/* translators: %d: post ID */
esc_html__( 'Reaped revisions for Post #%d', 'thisismyurl-revision-reaper' ),
$id
) );
break;
case 'trash':
if ( ! self::trash_post_eligible_for_purge( $id ) ) {
wp_send_json_success( sprintf(
/* translators: %d: post ID */
esc_html__( 'Skipped Trashed Post #%d (not yet older than EMPTY_TRASH_DAYS)', 'thisismyurl-revision-reaper' ),
$id
) );
break;
}
wp_delete_post( $id, false );
wp_send_json_success( sprintf(
/* translators: %d: post ID */
esc_html__( 'Purged Trashed Post #%d', 'thisismyurl-revision-reaper' ),
$id
) );
break;
case 'spam':
wp_trash_comment( $id );
wp_send_json_success( sprintf(
/* translators: %d: comment ID */
esc_html__( 'Moved Spam Comment #%d to comment trash', 'thisismyurl-revision-reaper' ),
$id
) );
break;
}
// Switch covers every whitelisted type; reaching this branch means
// a switch case forgot to send a response — kept defensively.
wp_send_json_error( esc_html__( 'No handler matched the requested item type.', 'thisismyurl-revision-reaper' ), 500 );
}
/**
* AJAX: snapshot eligible items before a live run.
*
* Triggered by the admin JS once, before the per-item delete loop. We
* recompute the eligible set server-side rather than trusting the JS
* payload — the page may have been open for hours.
*/
public static function ajax_pre_run_export() {
check_ajax_referer( 'timu_rr_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( esc_html__( 'Unauthorized', 'thisismyurl-revision-reaper' ), 403 );
}
$settings = array(
'limit' => (int) get_option( 'timu_rr_limit', 3 ),
'include_trash' => (int) get_option( 'timu_rr_auto_trash', 0 ),
'include_spam' => (int) get_option( 'timu_rr_auto_spam', 0 ),
);
$items = self::get_eligible_items( $settings );
if ( empty( $items ) ) {
wp_send_json_success( esc_html__( 'Nothing to export — no eligible items.', 'thisismyurl-revision-reaper' ) );
}
$path = TIMU_Revision_Reaper_Exporter::snapshot_before_run( $items, $settings['limit'] );
if ( ! $path ) {
wp_send_json_error( esc_html__( 'Pre-run export failed to write. Aborting live run.', 'thisismyurl-revision-reaper' ), 500 );
}
wp_send_json_success( sprintf(
/* translators: %s: filename of the JSON export */
esc_html__( 'Pre-run export written: %s', 'thisismyurl-revision-reaper' ),
esc_html( wp_basename( $path ) )
) );
}
/**
* admin-post handler: state-changing entry point for "begin a run".
*
* Replaces the old GET trigger (tools.php?page=revision-reaper&reap=1).
* Validates nonce + cap, then redirects back to the admin screen with
* the run-mode flag carried in a transient (not the URL).
*/
public static function handle_run_post() {
check_admin_referer( 'timu_rr_run_action', 'timu_rr_run_nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have permission to start a Revision Reaper run.', 'thisismyurl-revision-reaper' ) );
}
$is_dry_run = ! empty( $_POST['dry_run'] );
$user_id = get_current_user_id();
set_transient( 'timu_rr_run_intent_' . $user_id, $is_dry_run ? 'dry' : 'live', 5 * MINUTE_IN_SECONDS );
wp_safe_redirect( admin_url( 'tools.php?page=revision-reaper&reap=1' ) );
exit;
}
/**
* AJAX: Optimize Database Tables + clear expired transients.
*/
public static function ajax_optimize_db() {
check_ajax_referer( 'timu_rr_nonce', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_send_json_error( esc_html__( 'Unauthorized', 'thisismyurl-revision-reaper' ), 403 );
}
$transients = self::delete_expired_transients();
$optimized = self::optimize_wp_tables();
wp_send_json_success( sprintf(
/* translators: 1: number of tables optimized, 2: number of expired transient pairs deleted */
esc_html__( 'Optimized %1$d tables and removed %2$d expired transient pairs.', 'thisismyurl-revision-reaper' ),
(int) $optimized,
(int) $transients
) );
}
/**
* Render Admin Dashboard.
*/
public static function render_admin_page() {
// Capability gate first — nothing in this view is safe for non-admins.
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have permission to manage Revision Reaper.', 'thisismyurl-revision-reaper' ) );
}
// Handle Persistent Save Settings & Schedule.
if ( isset( $_POST['rr_save_settings'] ) ) {
// Nonce + capability gate. Both are required for any state change.
check_admin_referer( 'timu_rr_save_settings', 'timu_rr_settings_nonce' );
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( esc_html__( 'You do not have permission to update these settings.', 'thisismyurl-revision-reaper' ) );
}
update_option( 'timu_rr_limit', absint( wp_unslash( $_POST['rev_limit'] ?? 3 ) ) );
update_option( 'timu_rr_auto_trash', isset( $_POST['include_trash'] ) ? 1 : 0 );
update_option( 'timu_rr_auto_spam', isset( $_POST['include_spam'] ) ? 1 : 0 );
update_option( 'timu_rr_report_email', sanitize_email( wp_unslash( $_POST['report_email'] ?? '' ) ) );
// Automation persistent setting.
$enable_automation = isset( $_POST['enable_schedule'] ) ? 1 : 0;
update_option( 'timu_rr_enable_automation', $enable_automation );
// Validate schedule_date as YYYY-MM-DD; reject anything else.
$raw_date = isset( $_POST['schedule_date'] ) ? sanitize_text_field( wp_unslash( $_POST['schedule_date'] ) ) : '';
$raw_time = isset( $_POST['schedule_time'] ) ? sanitize_text_field( wp_unslash( $_POST['schedule_time'] ) ) : '';
$valid_date = self::validate_iso_date( $raw_date ) ? $raw_date : wp_date( 'Y-m-d' );
$valid_time = self::validate_iso_time( $raw_time ) ? $raw_time : '00:00';
// Whitelist recurrence against actually-registered cron schedules.
$allowed_recurrences = array_keys( wp_get_schedules() );
$raw_recurrence = isset( $_POST['schedule_recurrence'] ) ? sanitize_key( wp_unslash( $_POST['schedule_recurrence'] ) ) : 'weekly';
$valid_recurrence = in_array( $raw_recurrence, $allowed_recurrences, true ) ? $raw_recurrence : 'weekly';
update_option( 'timu_rr_schedule_date', $valid_date );
update_option( 'timu_rr_schedule_time', $valid_time );
update_option( 'timu_rr_schedule_recurrence', $valid_recurrence );
wp_clear_scheduled_hook( 'timu_rr_scheduled_cleanup' );
if ( $enable_automation ) {
// Treat the date+time as site-local; convert to UTC for cron.
$timestamp = self::parse_site_local_to_utc( $valid_date . ' ' . $valid_time );
if ( $timestamp ) {
wp_schedule_event( $timestamp, $valid_recurrence, 'timu_rr_scheduled_cleanup' );
}
}
echo '<div class="updated"><p>' . esc_html__( 'Settings and Schedule updated successfully.', 'thisismyurl-revision-reaper' ) . '</p></div>';
}
// Persistent Option Retrieval
$current_limit = get_option( 'timu_rr_limit', 3 );
$auto_trash = get_option( 'timu_rr_auto_trash', 0 );
$auto_spam = get_option( 'timu_rr_auto_spam', 0 );
$report_email = get_option( 'timu_rr_report_email', get_option( 'admin_email' ) );
$automation_enabled = get_option( 'timu_rr_enable_automation', 0 );
$next_run = wp_next_scheduled( 'timu_rr_scheduled_cleanup' );
$saved_date = get_option( 'timu_rr_schedule_date', wp_date( 'Y-m-d' ) );
$saved_time = get_option( 'timu_rr_schedule_time', '00:00' );
$saved_recurrence = get_option( 'timu_rr_schedule_recurrence', 'weekly' );
$settings = array( 'limit' => $current_limit, 'include_trash' => $auto_trash, 'include_spam' => $auto_spam );
// Run-mode is delivered via transient (set by handle_run_post) so it
// can't be replayed from a URL or bookmarked. ?reap=1 is just a flag
// indicating "we just came back from the admin-post POST".
$user_id = get_current_user_id();
$run_intent_key = 'timu_rr_run_intent_' . $user_id;
$run_intent = isset( $_GET['reap'] ) ? get_transient( $run_intent_key ) : false;
$items = $run_intent ? self::get_eligible_items( $settings ) : array();
$is_dry_run_active = ( 'dry' === $run_intent );
if ( $run_intent ) {
// One-shot — clear so a refresh doesn't re-arm the runner.
delete_transient( $run_intent_key );
}
?>
<div class="wrap">
<h1>
<?php esc_html_e( 'Revision Reaper', 'thisismyurl-revision-reaper' ); ?>
<small style="font-size: 0.5em; font-weight: normal; vertical-align: middle; margin-left: 10px; color: #646970;">
<?php
printf(
/* translators: %s: brand name "Christopher Ross" */
esc_html__( 'by %s', 'thisismyurl-revision-reaper' ),
esc_html__( 'Christopher Ross', 'thisismyurl-revision-reaper' )
);
?>
</small>
</h1>
<p><?php esc_html_e( 'Optimize performance by reaping revisions, trash, and spam using persistent settings.', 'thisismyurl-revision-reaper' ); ?></p>
<div id="poststuff">
<div id="post-body" class="metabox-holder columns-1">
<div id="post-body-content">
<form method="post">
<?php wp_nonce_field( 'timu_rr_save_settings', 'timu_rr_settings_nonce' ); ?>
<div class="postbox">
<h2 class="hndle"><span><?php esc_html_e( 'Configuration & Automation', 'thisismyurl-revision-reaper' ); ?></span></h2>
<div class="inside">
<table class="form-table" role="presentation">
<tr>
<th scope="row"><label for="rr-limit"><?php esc_html_e( 'Revisions to Keep', 'thisismyurl-revision-reaper' ); ?></label></th>
<td><input type="number" name="rev_limit" id="rr-limit" value="<?php echo esc_attr( $current_limit ); ?>" class="small-text"></td>
</tr>
<tr>
<th scope="row" id="rr-trash-label"><?php esc_html_e( 'Include Trash', 'thisismyurl-revision-reaper' ); ?></th>
<td><input type="checkbox" name="include_trash" id="rr-trash" value="1" aria-labelledby="rr-trash-label" <?php checked( $auto_trash ); ?>></td>
</tr>
<tr>
<th scope="row" id="rr-spam-label"><?php esc_html_e( 'Include Spam', 'thisismyurl-revision-reaper' ); ?></th>
<td><input type="checkbox" name="include_spam" id="rr-spam" value="1" aria-labelledby="rr-spam-label" <?php checked( $auto_spam ); ?>></td>
</tr>
<tr><td colspan="2"><hr></td></tr>
<tr>
<th scope="row" id="rr-schedule-label"><?php esc_html_e( 'Enable Automation', 'thisismyurl-revision-reaper' ); ?></th>
<td>
<input type="checkbox" name="enable_schedule" id="rr-schedule" value="1" aria-labelledby="rr-schedule-label" <?php checked( $automation_enabled ); ?>>
<?php if ( $next_run ) : ?>
<p class="description" style="color:#2271b1; font-weight:bold;">
<?php
printf(
/* translators: %s: human-readable next-run datetime in site timezone */
esc_html__( 'Next Scheduled Run: %s', 'thisismyurl-revision-reaper' ),
esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $next_run ) )
);
?>
</p>
<?php endif; ?>
</td>
</tr>
<tr>
<th scope="row"><?php esc_html_e( 'First Run Date & Time', 'thisismyurl-revision-reaper' ); ?></th>
<td>
<input type="date" name="schedule_date" value="<?php echo esc_attr( $saved_date ); ?>">
<input type="time" name="schedule_time" value="<?php echo esc_attr( $saved_time ); ?>">
</td>
</tr>
<tr>
<th scope="row"><?php esc_html_e( 'Recurrence Interval', 'thisismyurl-revision-reaper' ); ?></th>
<td>
<select name="schedule_recurrence">
<?php
// Render exactly the cron schedules WP knows about right now.
// Falls back to hourly/daily/twicedaily/weekly which core ships.
foreach ( wp_get_schedules() as $sched_key => $sched ) {
$label = isset( $sched['display'] ) ? $sched['display'] : $sched_key;
printf(
'<option value="%1$s" %2$s>%3$s</option>',
esc_attr( $sched_key ),
selected( $saved_recurrence, $sched_key, false ),
esc_html( $label )
);
}
?>
</select>
</td>
</tr>
<tr>
<th scope="row"><?php esc_html_e( 'Reporting Email', 'thisismyurl-revision-reaper' ); ?></th>
<td><input type="email" name="report_email" value="<?php echo esc_attr( $report_email ); ?>" class="regular-text"></td>
</tr>
</table>
<p class="submit">
<input type="submit" name="rr_save_settings" class="button button-primary" value="<?php esc_attr_e( 'Save All Settings & Schedule', 'thisismyurl-revision-reaper' ); ?>">
</p>
</div>
</div>
</form>
<div class="postbox">
<h2 class="hndle"><span><?php esc_html_e( 'Run Cleanup', 'thisismyurl-revision-reaper' ); ?></span></h2>
<div class="inside">
<p>
<?php esc_html_e( 'A "Dry Run" reports what would change without touching the database. A live run writes a JSON snapshot of every affected row to your uploads directory before any deletion, then trashes (never force-deletes) the matching items.', 'thisismyurl-revision-reaper' ); ?>
</p>
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:inline-block; margin-right: 8px;">