Editing revisions setting, wp-config.php and any filter. */ class DeleteOldRevisions { /** * Wall-clock seconds one request may spend before it returns what it did and leaves the rest * for the next request, so a reverse proxy never times the request out. */ private const BATCH_TIME_BUDGET = 20.0; /** * Parent posts looked up per query. */ private const PARENTS_PER_QUERY = 50; private array $settings; public function __construct() { $this->settings = Plugin::get_settings( 'posts' ); add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] ); add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] ); add_action( 'wp_ajax_adminease_delete_old_revisions', [ $this, 'ajax_delete_old_revisions' ] ); } /** * Adds the button to the Posts tab. * * @param array $fields The existing settings fields. * * @return array */ public function adminease_settings_fields( array $fields ): array { $fields['posts']['fields'][] = [ 'type' => 'select', 'id' => 'delete-old-revisions-post-types', 'name' => 'adminease[posts][delete_old_revisions_post_types][]', 'value' => $this->get_saved_post_types(), 'options' => $this->get_post_type_options(), 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input adminease-choices', 'label' => __( 'Delete old revisions of', 'adminease' ), 'field_description' => __( 'Leave empty to clean every post type.', 'adminease' ), 'placeholder' => __( 'All post types', 'adminease' ), 'attributes' => [ 'multiple' => 'multiple', 'data-allow_clear' => true, ], 'child_fields' => [ [ 'type' => 'button', 'id' => 'delete-old-revisions-submit', 'input_class' => 'pwp-btn pwp-btn-ghost', 'label' => __( 'Delete old revisions', 'adminease' ), 'field_description' => __( 'Deletes the revisions above your revisions limit on every post of the chosen types. Autosaves are kept.', 'adminease' ), 'attributes' => [ 'role' => 'button', ], ], ], ]; return $fields; } /** * Returns the saved list of post types. Empty means every post type. * * @return array */ private function get_saved_post_types(): array { $saved = $this->settings['delete_old_revisions_post_types'] ?? []; if( ! is_array( $saved ) ) { return []; } return array_values( array_map( 'strval', $saved ) ); } /** * Lists every post type that keeps revisions, plus every type already saved. * * Saved types stay in the list after their revision support is removed, so saving never refuses them. * * @return array Post type name => label. */ public function get_post_type_options(): array { $options = []; foreach( get_post_types( [ 'show_ui' => true ], 'objects' ) as $name => $object ) { if( post_type_supports( $name, 'revisions' ) ) { $options[ $name ] = $object->labels->name ?? $name; } } foreach( $this->get_saved_post_types() as $name ) { if( ! isset( $options[ $name ] ) ) { $object = get_post_type_object( $name ); $options[ $name ] = $object ? ( $object->labels->name ?? $name ) : $name; } } return $options; } /** * Loads the button script on the AdminEase screen. * * @param string $hook The current admin page hook. * * @return void */ public function admin_enqueue_scripts( string $hook ): void { if( 'toplevel_page_adminease' !== $hook || ! current_user_can( 'manage_options' ) ) { return; } wp_enqueue_script( ADMINEASE_NAME . 'DeleteOldRevisions', ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseDeleteOldRevisions.js', [ 'jquery', ADMINEASE_NAME ], filemtime( ADMINEASE_DIR . 'assets/js/AdminEaseDeleteOldRevisions.js' ), true ); wp_localize_script( ADMINEASE_NAME . 'DeleteOldRevisions', ADMINEASE_NAME . 'DeleteOldRevisionsAjaxObj', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'security' => wp_create_nonce( 'adminease_delete_old_revisions_nonce' ), 'i18n' => [ 'checking' => esc_html__( 'Checking...', 'adminease' ), /* translators: %d: number of revisions deleted so far */ 'deleting' => esc_html__( 'Deleting... %d', 'adminease' ), 'noLimit' => esc_html__( 'Set a revisions limit and save first.', 'adminease' ), 'nothing' => esc_html__( 'No old revisions to delete.', 'adminease' ), /* translators: %d: number of revisions that will be deleted */ 'confirm' => esc_html__( 'This will delete %d old revisions. Autosaves are kept. This cannot be undone.', 'adminease' ), 'revisionsOff' => esc_html__( 'Revisions are turned off, so this deletes every revision of every post.', 'adminease' ), /* translators: %d: number of revisions deleted */ 'done' => esc_html__( 'Deleted %d old revisions.', 'adminease' ), 'error' => esc_html__( 'An error occurred. Refresh the page and try again.', 'adminease' ), ], ] ); } /** * Counts or deletes one batch of old revisions. * * @return void */ public function ajax_delete_old_revisions(): void { if( ! isset( $_POST['security'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_delete_old_revisions_nonce' ) ) { wp_send_json_error( new WP_Error( 'security_error', esc_html__( 'Security check failed. Refresh the page and try again.', 'adminease' ) ), 403 ); } if( ! current_user_can( 'manage_options' ) || ! current_user_can( 'delete_posts' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ), 403 ); } $dry_run = ! empty( $_POST['dry_run'] ); $last_id = isset( $_POST['last_id'] ) ? absint( $_POST['last_id'] ) : 0; $post_types = isset( $_POST['post_types'] ) ? array_map( 'sanitize_key', (array) wp_unslash( $_POST['post_types'] ) ) : []; $allowed = array_values( array_intersect( $post_types, array_keys( $this->get_post_type_options() ) ) ); if( ! empty( $post_types ) && empty( $allowed ) ) { wp_send_json_error( new WP_Error( 'invalid_post_types', esc_html__( 'Choose a valid post type and try again.', 'adminease' ) ), 400 ); } wp_send_json_success( $this->process_batch( $last_id, $dry_run, $allowed ) ); } /** * Works through parent posts in id order until the time budget is spent. * * @param int $last_id The last parent post id handled by the previous call. * @param bool $dry_run True to count instead of delete. * @param string[] $post_types Parent post types to clean. Empty means every post type. * * @return array { * @type int $revisions Revisions deleted (or that would be deleted) by this call. * @type int $limited Parent posts with a limit that were checked. * @type int $unlimited Parent posts skipped because they keep every revision. * @type bool $all_off True when a post with a limit of zero was found. * @type int $last_id Last parent post id handled. * @type bool $done True when no parent post is left. * } */ public function process_batch( int $last_id, bool $dry_run, array $post_types = [] ): array { global $wpdb; /** * Filters the seconds one delete old revisions request may run. * * @param float $seconds The time budget. */ $budget = (float) apply_filters( 'adminease_delete_old_revisions_time_budget', self::BATCH_TIME_BUDGET ); $start = microtime( true ); $result = [ 'revisions' => 0, 'limited' => 0, 'unlimited' => 0, 'all_off' => false, 'last_id' => $last_id, 'done' => false, ]; while( true ) { if( empty( $post_types ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $parents = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT post_parent FROM {$wpdb->posts} WHERE post_type = 'revision' AND post_name NOT LIKE %s AND post_parent > %d ORDER BY post_parent ASC LIMIT %d", '%' . $wpdb->esc_like( 'autosave' ) . '%', $result['last_id'], self::PARENTS_PER_QUERY ) ); } else { $values = array_merge( [ '%' . $wpdb->esc_like( 'autosave' ) . '%', $result['last_id'] ], $post_types, [ self::PARENTS_PER_QUERY ] ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $parents = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT r.post_parent FROM {$wpdb->posts} r INNER JOIN {$wpdb->posts} p ON p.ID = r.post_parent WHERE r.post_type = 'revision' AND r.post_name NOT LIKE %s AND r.post_parent > %d AND p.post_type IN (" . implode( ', ', array_fill( 0, count( $post_types ), '%s' ) ) . ') ORDER BY r.post_parent ASC LIMIT %d', $values ) ); } if( empty( $parents ) ) { $result['done'] = true; break; } foreach( $parents as $parent_id ) { $parent_id = (int) $parent_id; $this->clean_parent( $parent_id, $dry_run, $result ); $result['last_id'] = $parent_id; if( ( microtime( true ) - $start ) >= $budget ) { return $result; } } } return $result; } /** * Deletes (or counts) the revisions of one post that are above its limit. * * @param int $parent_id The parent post id. * @param bool $dry_run True to count instead of delete. * @param array $result The running totals, updated in place. * * @return void */ private function clean_parent( int $parent_id, bool $dry_run, array &$result ): void { $parent = get_post( $parent_id ); if( ! $parent ) { return; } $keep = wp_revisions_to_keep( $parent ); if( $keep < 0 ) { ++$result['unlimited']; return; } ++$result['limited']; if( 0 === $keep ) { $result['all_off'] = true; } $revisions = wp_get_post_revisions( $parent_id, [ 'order' => 'DESC', 'orderby' => 'date ID', 'check_enabled' => false, ] ); $revisions = array_filter( $revisions, static function ( $revision ) { return ! wp_is_post_autosave( $revision ); } ); foreach( array_slice( array_values( $revisions ), $keep ) as $revision ) { if( $dry_run ) { ++$result['revisions']; continue; } if( wp_delete_post_revision( $revision->ID ) ) { ++$result['revisions']; } } } }