Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
class-delete-all.php 6.93 KiB
<?php
/**
 * Offload "Empty Trash"
 *
 * @package Bulk_Edit_Cron_Offload
 */

namespace Automattic\WP\Bulk_Edit_Cron_Offload;

/**
 * Class Delete_All
 */
class Delete_All {
	/**
	 * Class constants
	 */
	const CRON_EVENT = 'a8c_bulk_edit_delete_all';

	const ADMIN_NOTICE_KEY = 'a8c_bulk_edit_deleted_all';

	/**
	 * Register this bulk process' hooks
	 */
	public static function register_hooks() {
		add_action( Main::build_hook( 'delete_all' ), array( __CLASS__, 'process' ) );
		add_action( self::CRON_EVENT, array( __CLASS__, 'process_via_cron' ) );

		add_action( 'admin_notices', array( __CLASS__, 'admin_notices' ) );
		add_filter( 'posts_where', array( __CLASS__, 'hide_posts_pending_delete' ), 999, 2 );

		// Limit when caps are intercepted, given frequent execution of the `map_meta_cap` filter.
		add_action( 'load-edit.php', function() {
			add_filter( 'map_meta_cap', array( __CLASS__, 'hide_empty_trash_pending_delete' ), 10, 2 );
		} );
	}

	/**
	 * Handle a request to delete all trashed items for a given post type
	 *
	 * @param object $vars Bulk-request variables.
	 */
	public static function process( $vars ) {
		// Special keys are used to trigger this request, and we need to remove them on redirect.
		$extra_keys = array( 'delete_all', 'delete_all2' );

		$action_scheduled = self::action_next_scheduled( self::CRON_EVENT, $vars->post_type );

		if ( empty( $action_scheduled ) ) {
			wp_schedule_single_event( time(), self::CRON_EVENT, array( $vars ) );

			Main::do_admin_redirect( self::ADMIN_NOTICE_KEY, true, $extra_keys );
		} else {
			Main::do_admin_redirect( self::ADMIN_NOTICE_KEY, false, $extra_keys );
		}
	}

	/**
	 * Cron callback to delete trashed items in a given post type
	 *
	 * @param object $vars Bulk-request variables.
	 * @return array|bool
	 */
	public static function process_via_cron( $vars ) {
		global $wpdb;

		$post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type = %s AND post_status = %s", $vars->post_type, $vars->post_status ) );

		$count = 0;

		if ( is_array( $post_ids ) && ! empty( $post_ids ) ) {