Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
class-delete-all.php 5.57 KiB
<?php

namespace Automattic\WP\Bulk_Edit_Cron_Offload;

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 );
	}

	/**
	 * Handle a request to delete all trashed items for a given post type
	 */
	public static function process( $vars ) {
		$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 ) );

			self::redirect( true );
		} else {
			self::redirect( false );
		}
	}

	/**
	 * Cron callback to delete trashed items in a given post type
	 */
	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 ) ) {
			require_once ABSPATH . '/wp-admin/includes/post.php';

			$deleted = $locked = $auth_error = $error = array();

			foreach ( $post_ids as $post_id ) {
				// Can the user delete this post
				if ( ! user_can( $vars->user_id, 'delete_post', $post_id ) ) {
					$auth_error[] = $post_id;
					continue;
				}

				// Post is locked by someone, so leave it alone
				if ( false !== wp_check_post_lock( $post_id ) ) {
					$locked[] = $post_id;
					continue;
				}

				// Try deleting
				$post_deleted = wp_delete_post( $post_id );
				if ( $post_deleted ) {
					$deleted[] = $post_id;