404 ) ); } if ( self::is_protected( (string) $row->hook, (string) ( $row->group_slug ?? '' ) ) ) { return new WP_Error( 'apwc_sa_protected', __( 'Action Scheduler’s own actions and WooCommerce’s database updates can’t be changed here.', 'admin-powerups-for-woocommerce' ), array( 'status' => 403 ) ); } $status = (string) $row->status; if ( 'in-progress' === $status ) { return new WP_Error( 'apwc_sa_running', __( 'It’s running right now. Wait until it finishes.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); } switch ( $op ) { case 'run': if ( 'pending' !== $status ) { return new WP_Error( 'apwc_sa_not_pending', __( 'Only actions waiting to run can run now.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); } $due = Monitor::timestamp( (string) $row->scheduled_date_gmt ); if ( ! $due || $due > time() ) { return new WP_Error( 'apwc_sa_not_due', __( 'It isn’t due yet. Only due actions can run now.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); } if ( (int) $row->claim_id > 0 ) { return new WP_Error( 'apwc_sa_claimed', __( 'A queue run has already picked it up.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); } return null; case 'retry': return 'failed' === $status ? null : new WP_Error( 'apwc_sa_not_failed', __( 'Only failed actions can be retried.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); case 'cancel': return 'pending' === $status ? null : new WP_Error( 'apwc_sa_not_pending', __( 'Only actions waiting to run can be canceled.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); case 'delete': if ( 'pending' === $status ) { return new WP_Error( 'apwc_sa_cancel_first', __( 'It’s still waiting to run: cancel it instead. Deleting a waiting action (a repeating one especially) would stop it without a trace.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); } return in_array( $status, array( 'complete', 'failed', 'canceled' ), true ) ? null : new WP_Error( 'apwc_sa_bad_status', __( 'Only finished, failed or canceled actions can be deleted.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); } return new WP_Error( 'apwc_sa_unknown', __( 'Unknown change.', 'admin-powerups-for-woocommerce' ), array( 'status' => 400 ) ); } /** * Add a line to an action's Action Scheduler log. * * @since 1.0.0 * @param int $id Action ID. * @param string $message Message. * @return void */ public static function log( int $id, string $message ): void { if ( class_exists( '\ActionScheduler_Logger' ) ) { \ActionScheduler_Logger::instance()->log( (string) $id, $message ); } } /* ------------------------------------------------------------------ run now */ /** * Request a background run of one due action (REST, Review level). * * @since 1.0.0 * @param int $id Action ID. * @return array{queued: bool, id: int}|WP_Error */ public static function request_run( int $id ) { $row = Monitor::row( $id ); $refuse = self::refuse( $row, 'run' ); if ( $refuse ) { return $refuse; } $token = bin2hex( random_bytes( 16 ) ); // Not wp_generate_password(): the random_password filter may change it. $hash = hash( 'sha256', $token ); if ( ! set_transient( self::RUN_PREFIX . $hash, $id, self::TOKEN_TTL ) ) { return new WP_Error( 'apwc_sa_token', __( 'Couldn’t save the Run now request. Try again.', 'admin-powerups-for-woocommerce' ), array( 'status' => 500 ) ); } self::log( $id, sprintf( '%s by user #%d', self::REQUESTED, get_current_user_id() ) ); /** * Filter the background request that starts a Run now (for example to add basic-auth * headers on a staging site). Never add credentials of a WordPress user: the request runs * as no user on purpose. `blocking`, `cookies` and `body` are always reset afterwards and * any Cookie header is dropped: the request never waits and never carries cookies. * * @since 1.0.0 * @param array $args wp_remote_post() arguments. * @param int $id Action ID. */ $args = (array) apply_filters( 'apwc_scheduled_actions_run_request', array( 'timeout' => 0.01, // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WordPress core filter, read the same way spawn_cron() does. 'sslverify' => apply_filters( 'https_local_ssl_verify', false ), ), $id ); $args['blocking'] = false; $args['cookies'] = array(); if ( isset( $args['headers'] ) && is_array( $args['headers'] ) ) { foreach ( array_keys( $args['headers'] ) as $name ) { if ( 'cookie' === strtolower( trim( (string) $name ) ) ) { unset( $args['headers'][ $name ] ); } } } elseif ( isset( $args['headers'] ) ) { unset( $args['headers'] ); // A raw header string can't be checked: drop it. } $args['body'] = array( 'action' => self::AJAX, 'token' => $token, ); $response = wp_remote_post( admin_url( 'admin-ajax.php' ), $args ); if ( is_wp_error( $response ) ) { delete_transient( self::RUN_PREFIX . $hash ); self::log( $id, 'Run now could not start: the background request to this site failed.' ); return new WP_Error( 'apwc_sa_loopback', /* translators: %s: error message. */ sprintf( __( 'Couldn’t start the background run: %s', 'admin-powerups-for-woocommerce' ), $response->get_error_message() ), array( 'status' => 502 ) ); } /** * Fires after Run now was requested for a scheduled action (it runs moments later in a * background request). * * @since 1.0.0 * @param int $id Action ID. */ do_action( 'apwc_scheduled_action_run_requested', $id ); Monitor::flush(); return array( 'queued' => true, 'id' => $id, ); } /** * The background request: check and use up the token, then run the action as no user. * Anything wrong ends quietly (no output, no hint whether a token existed). * * @since 1.0.0 * @param mixed $token Token from the request. * @return string `invalid`, `skipped` or `ran` (for tests; the AJAX handler prints nothing). */ public static function handle_run( $token ): string { wp_set_current_user( 0 ); // Run as no user, like WP-Cron and Action Scheduler's own runner. if ( ! is_string( $token ) || ! preg_match( '/^[a-f0-9]{32}$/', $token ) ) { return 'invalid'; } // The key is the token's hash: only the holder of the token can name it. $key = self::RUN_PREFIX . hash( 'sha256', $token ); $stored = get_transient( $key ); if ( ! is_numeric( $stored ) || (int) $stored < 1 ) { return 'invalid'; } // Single use: only the request whose delete succeeds goes on. if ( ! delete_transient( $key ) ) { return 'invalid'; } if ( '' !== Monitor::unavailable() ) { return 'skipped'; } ignore_user_abort( true ); if ( class_exists( '\ActionScheduler_Compatibility' ) ) { \ActionScheduler_Compatibility::raise_time_limit(); } return self::run_claimed( (int) $stored ); } /** * Claim exactly this action with Action Scheduler's claim query, process it, release the * claim. The claim is taken with SELECT … FOR UPDATE [SKIP LOCKED], so a queue runner can't * take the same action at the same time; while it runs it counts as one of Action Scheduler's * concurrent batches, like any queue run. * * @since 1.0.0 * @param int $id Action ID. * @return string `skipped` or `ran`. */ public static function run_claimed( int $id ): string { $row = Monitor::row( $id ); if ( self::refuse( $row, 'run' ) ) { if ( $row ) { self::log( $id, 'Run now skipped: already claimed or no longer pending.' ); } return 'skipped'; } $store = \ActionScheduler::store(); if ( ! $store instanceof \ActionScheduler_DBStore ) { return 'skipped'; } $order = static function () use ( $id ) { return sprintf( 'ORDER BY (action_id = %d) DESC, priority ASC, attempts ASC, scheduled_date_gmt ASC, action_id ASC', $id ); }; $before = self::claim_date( (string) $row->scheduled_date_gmt ); $hooks_filter = $store->get_claim_filter( 'hooks' ); $group_filter = $store->get_claim_filter( 'group' ); $claim = null; add_filter( 'action_scheduler_claim_actions_order_by', $order, PHP_INT_MAX ); try { $claim = $store->stake_claim( 1, $before, array( (string) $row->hook ), (string) ( $row->group_slug ?? '' ) ); } catch ( \InvalidArgumentException | \RuntimeException $e ) { $claim = null; } finally { remove_filter( 'action_scheduler_claim_actions_order_by', $order, PHP_INT_MAX ); // stake_claim() keeps its hook and group as the store's claim filters; put them back. $store->set_claim_filter( 'hooks', $hooks_filter ); $store->set_claim_filter( 'group', $group_filter ); } if ( ! $claim instanceof \ActionScheduler_ActionClaim || array_map( 'intval', $claim->get_actions() ) !== array( $id ) ) { if ( $claim instanceof \ActionScheduler_ActionClaim ) { self::release( $store, $claim ); } self::log( $id, 'Run now skipped: already claimed or no longer pending.' ); return 'skipped'; } // Like a queue run: a fatal error inside the action marks it failed instead of leaving it in progress. $monitor = class_exists( '\ActionScheduler_FatalErrorMonitor' ) ? new \ActionScheduler_FatalErrorMonitor( $store ) : null; try { if ( $monitor ) { $monitor->attach( $claim ); } \ActionScheduler::runner()->process_action( $id, self::CONTEXT ); } catch ( \Throwable $e ) { unset( $e ); // process_action() records failures on the action itself. } finally { if ( $monitor ) { $monitor->detach(); } self::release( $store, $claim ); Monitor::flush(); } return 'ran'; } /** * The "before" date for the claim query: the action's own scheduled time (UTC). * * @param string $gmt Scheduled date (UTC). * @return \DateTime */ private static function claim_date( string $gmt ): \DateTime { $time = Monitor::timestamp( $gmt ); return as_get_datetime_object( $time ? $time : time() ); } /** * Release a claim, ignoring "already released". * * @param \ActionScheduler_DBStore $store Store. * @param \ActionScheduler_ActionClaim $claim Claim. * @return void */ private static function release( $store, $claim ): void { try { $store->release_claim( $claim ); } catch ( \RuntimeException $e ) { unset( $e ); } } /* ------------------------------------------------------------------ bulk changes */ /** * Retry failed actions: each gets a NEW async action with the same hook, args, group and * priority (the failed one stays for its history). Refused when a copy is already waiting, * and for actions that may charge, refund or send again (may_charge()) unless the caller * confirmed them as an Advanced change (`$charge_ok`). * * @since 1.0.0 * @param int[] $ids Action IDs. * @param bool $charge_ok Whether may-charge actions were confirmed at the Advanced level * (typed word checked by the caller). * @return array{done: int[], skipped: array} */ public static function retry( array $ids, bool $charge_ok = false ): array { $user = get_current_user_id(); return self::each( $ids, 'retry', static function ( $row ) use ( $user, $charge_ok ) { if ( ! $charge_ok && self::may_charge( (string) $row->hook ) ) { return new WP_Error( 'apwc_sa_charge_confirm', __( 'It may charge, refund or send again, so retrying it is an Advanced change: retry it on its own and type the word to confirm.', 'admin-powerups-for-woocommerce' ), array( 'status' => 403 ) ); } $id = (int) $row->action_id; $action = \ActionScheduler::store()->fetch_action( $id ); if ( ! $action instanceof \ActionScheduler_Action || $action instanceof \ActionScheduler_NullAction ) { return self::refuse( null, 'retry' ); } $hook = (string) $action->get_hook(); $args = (array) $action->get_args(); if ( as_has_scheduled_action( $hook, $args ) ) { return new WP_Error( 'apwc_sa_waiting', __( 'A copy is already waiting to run.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); } $priority = (int) $action->get_priority(); $new = (int) as_enqueue_async_action( $hook, $args, (string) $action->get_group(), false, $priority ); if ( $new < 1 ) { return new WP_Error( 'apwc_sa_not_queued', __( 'Action Scheduler didn’t accept the retry.', 'admin-powerups-for-woocommerce' ), array( 'status' => 500 ) ); } self::log( $id, sprintf( 'Retried in Admin Powerups by user #%d as action #%d', $user, $new ) ); self::log( $new, sprintf( 'Retry of action #%d requested in Admin Powerups by user #%d', $id, $user ) ); /** * Fires after a failed scheduled action was retried as a new action. * * @since 1.0.0 * @param int $new_id New action ID. * @param int $old_id Failed action ID. */ do_action( 'apwc_scheduled_action_retried', $new, $id ); return true; } ); } /** * Cancel waiting actions (a repeating action stops repeating). * * @since 1.0.0 * @param int[] $ids Action IDs. * @return array{done: int[], skipped: array} */ public static function cancel( array $ids ): array { $user = get_current_user_id(); return self::each( $ids, 'cancel', static function ( $row ) use ( $user ) { $id = (int) $row->action_id; try { \ActionScheduler::store()->cancel_action( $id ); } catch ( \InvalidArgumentException $e ) { return self::refuse( null, 'cancel' ); } self::log( $id, sprintf( 'Canceled in Admin Powerups by user #%d', $user ) ); return true; } ); } /** * Delete finished, failed or canceled actions (their logs go with them). * * @since 1.0.0 * @param int[] $ids Action IDs. * @return array{done: int[], skipped: array} */ public static function delete( array $ids ): array { return self::each( $ids, 'delete', static function ( $row ) { try { \ActionScheduler::store()->delete_action( (int) $row->action_id ); } catch ( \InvalidArgumentException $e ) { return self::refuse( null, 'delete' ); } return true; } ); } /** * Apply a change to each action that allows it. * * @param int[] $ids Action IDs. * @param string $op Operation for refuse(). * @param callable $change Receives the row; returns true or a WP_Error. * @return array{done: int[], skipped: array} */ private static function each( array $ids, string $op, callable $change ): array { $out = array( 'done' => array(), 'skipped' => array(), ); foreach ( array_slice( array_values( array_unique( array_filter( array_map( 'intval', $ids ), static fn( $id ) => $id > 0 ) ) ), 0, self::MAX_IDS ) as $id ) { $row = Monitor::row( $id ); $result = self::refuse( $row, $op ); if ( ! $result ) { $result = $change( $row ); } if ( true === $result ) { $out['done'][] = $id; continue; } $error = $result instanceof WP_Error ? $result : new WP_Error( 'apwc_sa_failed', __( 'Couldn’t change it.', 'admin-powerups-for-woocommerce' ), array( 'status' => 500 ) ); $data = $error->get_error_data(); $out['skipped'][] = array( 'id' => $id, 'code' => (string) $error->get_error_code(), 'message' => $error->get_error_message(), 'status' => is_array( $data ) && isset( $data['status'] ) ? (int) $data['status'] : 500, ); } if ( $out['done'] ) { Monitor::flush(); } return $out; } /* ------------------------------------------------------------------ purge */ /** * How many actions of a status are older than the cutoff: one indexed COUNT. * * @since 1.0.0 * @param string $status complete | failed | canceled. * @param \DateTime $cutoff Cutoff (UTC). * @return int */ public static function count_old( string $status, \DateTime $cutoff ): int { return ActionHistory::count_old( $status, $cutoff ); } /** * Delete one bounded step of old actions of a status (see ActionHistory::purge_step()). * Fires `apwc_scheduled_actions_purged` with the source `monitor`. * * @since 1.0.0 * @param string $status complete | failed | canceled. * @param int $days Older than this many days (1–3650). * @param int $batch IDs per query. * @param float $budget Seconds to keep going. * @return array{deleted: int, left: int, done: bool} */ public static function purge_step( string $status, int $days, int $batch, float $budget ): array { $days = max( 1, min( 3650, $days ) ); $cutoff = as_get_datetime_object( time() - $days * DAY_IN_SECONDS ); return ActionHistory::purge_step( $status, $cutoff, $batch, $budget, 'monitor' ); } }