> */ public function fields() { return array( array( 'id' => 'retention_heading', 'type' => 'heading', 'label' => __( 'Clean-up', 'admin-powerups-for-woocommerce' ), 'description' => __( 'How long Action Scheduler keeps old actions. These apply while this power-up is on; switch it off and Action Scheduler’s defaults apply again.', 'admin-powerups-for-woocommerce' ), ), array( 'id' => 'retention_completed', 'type' => 'number', 'label' => __( 'Keep finished actions for (days)', 'admin-powerups-for-woocommerce' ), 'description' => __( '0 keeps the default (31 days). Action Scheduler removes old ones a few at a time as the queue runs; to clear a big backlog, use Purge on the Monitor tab. Canceled actions that never ran are removed at the next clean-up whatever this says: Action Scheduler counts from the last run, which they never had.', 'admin-powerups-for-woocommerce' ), 'default' => 0, 'min' => 0, 'max' => 365, 'warning' => __( 'A longer period makes the actions table bigger, which slows queue runs and this monitor on busy stores.', 'admin-powerups-for-woocommerce' ), 'warning_icon' => 'gauge', ), array( 'id' => 'retention_failed', 'type' => 'number', 'label' => __( 'Keep failed actions for (days)', 'admin-powerups-for-woocommerce' ), 'description' => static function () { if ( self::has_failed_retention() ) { return __( '0 keeps the default (3 months). If another plugin makes Action Scheduler clean up failed actions together with finished ones, Action Scheduler ignores this and uses the period above.', 'admin-powerups-for-woocommerce' ); } return __( '0 keeps them forever (the default for this site’s Action Scheduler version). Above 0, this power-up deletes older failed actions once a day.', 'admin-powerups-for-woocommerce' ); }, 'default' => 0, 'min' => 0, 'max' => 730, 'warning' => __( 'Failed actions are how you find out what went wrong: keep them long enough to look into them.', 'admin-powerups-for-woocommerce' ), 'warning_icon' => 'circle-alert', ), ); } /** * {@inheritDoc} Also (un)schedules the daily failed clean-up to match. * * @param array $input Raw input keyed by field ID. * @return array */ public function save_settings( array $input ) { $saved = parent::save_settings( $input ); if ( $this->is_enabled() ) { $this->sync_prune_job(); } return $saved; } /** * {@inheritDoc} * * @return array> */ public function data() { global $wpdb; // With a persistent object cache the tokens live there, not in the options table: nothing to // count or delete here, and each one expires on its own. $in_cache = wp_using_ext_object_cache(); $tokens = static function () use ( $wpdb, $in_cache ) { if ( $in_cache ) { return 0; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- our own short-lived tokens. return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE option_name LIKE %s', $wpdb->options, $wpdb->esc_like( '_transient_' . Jobs::RUN_PREFIX ) . '%' ) ); }; return array_merge( parent::data(), array( array( 'id' => 'summary', 'kind' => 'cache', 'label' => __( 'Queue summary', 'admin-powerups-for-woocommerce' ), 'description' => __( 'The Monitor tab’s counts, kept for 10 minutes.', 'admin-powerups-for-woocommerce' ), 'count' => static fn() => false === get_transient( Monitor::SUMMARY ) ? 0 : 1, 'summary' => static fn( $count ) => $count ? __( 'Stored', 'admin-powerups-for-woocommerce' ) : __( 'Nothing stored', 'admin-powerups-for-woocommerce' ), 'delete' => static function () { Monitor::flush(); return 0; }, ), array( 'id' => 'run-tokens', 'kind' => 'cache', 'label' => __( 'Run now requests', 'admin-powerups-for-woocommerce' ), 'description' => __( 'Single-use keys that start a Run now in the background. Each expires after 2 minutes.', 'admin-powerups-for-woocommerce' ), 'count' => $tokens, 'summary' => $in_cache ? static fn() => __( 'In the object cache; each expires after 2 minutes', 'admin-powerups-for-woocommerce' ) : null, 'delete' => static function () use ( $wpdb, $tokens, $in_cache ) { if ( $in_cache ) { return 0; // Nothing in the options table; the cache expires them. } // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- our own short-lived tokens. $names = (array) $wpdb->get_col( $wpdb->prepare( 'SELECT option_name FROM %i WHERE option_name LIKE %s LIMIT 500', $wpdb->options, $wpdb->esc_like( '_transient_' . Jobs::RUN_PREFIX ) . '%' ) ); foreach ( $names as $name ) { delete_transient( substr( (string) $name, strlen( '_transient_' ) ) ); } return $tokens(); }, ), Cleanup::job_history( 'jobs', array( self::PRUNE, self::PRUNE_MORE ) ), Cleanup::record( 'actions', __( 'Changes to scheduled actions', 'admin-powerups-for-woocommerce' ), __( 'Actions you ran, retried, canceled, deleted or purged belong to Action Scheduler. Each change is noted in that action’s log.', 'admin-powerups-for-woocommerce' ) ), ) ); } /** * {@inheritDoc} */ public function activate() { $this->sync_prune_job(); } /** * {@inheritDoc} */ public function deactivate() { if ( function_exists( 'as_unschedule_all_actions' ) ) { as_unschedule_all_actions( self::PRUNE ); as_unschedule_all_actions( self::PRUNE_MORE ); } } /** * Schedule the daily failed clean-up when it's needed (a period is set and Action Scheduler * has no failed retention of its own), unschedule it otherwise. * * @since 1.0.0 * @return void */ public function sync_prune_job() { if ( ! function_exists( 'as_schedule_single_action' ) ) { return; } if ( $this->prune_needed() ) { $this->schedule_prune( HOUR_IN_SECONDS ); return; } $this->deactivate(); } /** * Whether the daily failed clean-up has work: a period is set and Action Scheduler has no * failed retention of its own. * * @since 1.0.0 * @return bool */ private function prune_needed(): bool { return (int) $this->setting( 'retention_failed', 0 ) > 0 && ! self::has_failed_retention(); } /** * Schedule the next clean-up as a single action, unless one is already waiting. A single * action (not a recurring one) so that a run which finds nothing to do can end the chain: * Action Scheduler would schedule a recurring action's next instance after the run even if * the run unscheduled it. * * @since 1.0.0 * @param int $delay Seconds from now. * @return void */ private function schedule_prune( int $delay ) { JobQueue::queue_once( self::PRUNE, $delay, JobQueue::GROUP ); } /** * {@inheritDoc} */ public function boot() { add_action( 'rest_api_init', array( $this, 'register_routes' ) ); // Read only inside Action Scheduler's cleaner (a background queue run). add_filter( 'action_scheduler_retention_period', array( $this, 'retention_period' ) ); add_filter( 'action_scheduler_retention_period_for_failed', array( $this, 'failed_retention_period' ) ); add_action( self::PRUNE, array( $this, 'prune_failed' ) ); add_action( self::PRUNE_MORE, array( $this, 'prune_failed' ) ); if ( wp_doing_ajax() ) { // nosemgrep: apwc-ajax-nopriv -- the cookie-less background Run now request; a hashed single-use 120 s token is the credential (no nonce without a user). add_action( 'wp_ajax_nopriv_' . Jobs::AJAX, array( $this, 'ajax_run' ) ); add_action( 'wp_ajax_' . Jobs::AJAX, array( $this, 'ajax_run' ) ); } } /* ------------------------------------------------------------------ retention */ /** * Retention of finished and canceled actions (seconds). * * @since 1.0.0 * @param mixed $seconds Action Scheduler's value. * @return mixed */ public function retention_period( $seconds ) { $days = (int) $this->setting( 'retention_completed', 0 ); return $days > 0 ? $days * DAY_IN_SECONDS : $seconds; } /** * Retention of failed actions (seconds; Action Scheduler 4.0 and later). * * @since 1.0.0 * @param mixed $seconds Action Scheduler's value. * @return mixed */ public function failed_retention_period( $seconds ) { $days = (int) $this->setting( 'retention_failed', 0 ); return $days > 0 ? $days * DAY_IN_SECONDS : $seconds; } /** * Daily clean-up of old failed actions on Action Scheduler before 4.0, bounded in time; a * follow-up job carries on when there's more. * * @since 1.0.0 * @return void */ public function prune_failed() { if ( ! $this->prune_needed() ) { $this->deactivate(); // Turned off, or Action Scheduler 4 took over: the chain ends here. return; } $this->schedule_prune( DAY_IN_SECONDS ); // Next daily run (only while still needed). if ( '' !== Monitor::unavailable() ) { return; } $days = (int) $this->setting( 'retention_failed', 0 ); /** * Filter how long (seconds) one daily clean-up of old failed actions keeps deleting before * it hands over to a follow-up job. Clamped to 1–20. * * @since 1.0.0 * @param int $seconds Time budget (default 20). */ $budget = max( 1, min( 20, (int) apply_filters( 'apwc_scheduled_actions_prune_seconds', 20 ) ) ); $result = Jobs::purge_step( 'failed', $days, self::purge_batch(), (float) $budget ); if ( $result['left'] > 0 && $result['deleted'] > 0 ) { $this->queue_follow_up(); } } /** * Queue one follow-up clean-up unless one is already waiting (the running one doesn't count). * * @since 1.0.0 * @return void */ private function queue_follow_up() { JobQueue::queue_once( self::PRUNE_MORE, 0, JobQueue::GROUP ); } /** * IDs per purge query. * * @since 1.0.0 * @return int */ public static function purge_batch(): int { /** * Filter how many old scheduled actions each purge query deletes. Clamped to 20–1000. * * @since 1.0.0 * @param int $batch Actions per query (default 200). */ return max( 20, min( 1000, (int) apply_filters( 'apwc_scheduled_actions_purge_batch', 200 ) ) ); } /** * Seconds one purge request keeps deleting. * * @since 1.0.0 * @return int */ public static function purge_seconds(): int { /** * Filter how long (seconds) one purge step on the Monitor tab keeps deleting before it * answers (the page then sends the next step). Clamped to 1–20. * * @since 1.0.0 * @param int $seconds Time budget (default 5). */ return max( 1, min( 20, (int) apply_filters( 'apwc_scheduled_actions_purge_seconds', 5 ) ) ); } /* ------------------------------------------------------------------ background run */ /** * The admin-ajax handler of the background Run now (no user; the single-use token is the key). * Prints nothing. * * @since 1.0.0 * @return void */ public function ajax_run() { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- the single-use token is the credential; this request runs as no user. $token = isset( $_POST['token'] ) && is_string( $_POST['token'] ) ? sanitize_text_field( wp_unslash( $_POST['token'] ) ) : ''; Jobs::handle_run( $token ); wp_die( '', '', array( 'response' => 200 ) ); } /* ------------------------------------------------------------------ screens */ /** * {@inheritDoc} */ public function views() { return array( self::VIEW => __( 'Monitor', 'admin-powerups-for-woocommerce' ) ); } /** * Monitor tab URL. * * @since 1.0.0 * @param array $args Query args (list, hook, paged, per_page). * @return string */ public static function url( array $args = array() ) { return add_query_arg( array_filter( $args, static fn( $v ) => '' !== $v && null !== $v && 0 !== $v ), AdminPage::url( 'scheduled-actions', self::VIEW ) ); } /** * Tools → Scheduled Actions (WooCommerce's list of every action). * * @since 1.0.0 * @param string $status Status filter ('past-due', 'failed', …) or ''. * @param string $hook Search. * @return string */ public static function tools_url( string $status = '', string $hook = '' ): string { return add_query_arg( array_filter( array( 'page' => 'wc-status', 'tab' => 'action-scheduler', 'status' => $status, 's' => $hook, ) ), admin_url( 'admin.php' ) ); } /** * Filters of the Monitor tab from the query string. * * @since 1.0.0 * @return array{list: string, hook: string, paged: int, per_page: int} */ public static function filters(): array { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only screen filters. // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- each value is sanitized below (sanitize_key, clean_hook(), int). $get = static fn( $key ) => isset( $_GET[ $key ] ) && is_string( $_GET[ $key ] ) ? wp_unslash( $_GET[ $key ] ) : ''; $list = sanitize_key( $get( 'list' ) ); $hook = self::clean_hook( $get( 'hook' ) ); $num = static fn( $key ) => max( 0, (int) $get( $key ) ); // phpcs:enable return array( 'list' => in_array( $list, Monitor::LISTS, true ) ? $list : 'failed', 'hook' => $hook, 'paged' => Paging::page( $get( 'paged' ), (int) max( Monitor::PER_PAGE ) ), 'per_page' => in_array( $num( 'per_page' ), Monitor::PER_PAGE, true ) ? $num( 'per_page' ) : 20, ); } /** * A hook name from input: trimmed, no control characters, at most 191 characters (the * column's length). '' when it doesn't qualify. * * @since 1.0.0 * @param string $hook Raw value. * @return string */ public static function clean_hook( string $hook ): string { $hook = trim( $hook ); if ( '' === $hook || ! mb_check_encoding( $hook, 'UTF-8' ) || preg_match( '/[\x00-\x1f\x7f]/', $hook ) || mb_strlen( $hook ) > 191 ) { return ''; } return $hook; } /** * {@inheritDoc} * * @param string $view View slug. */ public function render_view( $view ) { $unavailable = Monitor::unavailable(); $filter = self::filters(); $summary = null; $result = null; if ( '' === $unavailable ) { $summary = Monitor::summary(); $result = Monitor::page( $filter + array( 'has_attempt' => ! empty( $summary['has_attempt'] ) ) ); } include __DIR__ . '/views/monitor.php'; } /** * {@inheritDoc} * * @param string $view View slug. */ public function enqueue_view_assets( $view ) { wp_enqueue_style( 'apwc-scheduled-actions', Assets::url( 'assets/css/scheduled-actions.css' ), array( 'apwc-admin' ), Assets::ver( 'assets/css/scheduled-actions.css' ) ); wp_enqueue_script( 'apwc-scheduled-actions', Assets::url( 'assets/js/scheduled-actions.js' ), array( 'wp-api-fetch', 'wp-i18n', 'apwc-dev-tools', 'apwc-admin' ), Assets::ver( 'assets/js/scheduled-actions.js' ), true ); wp_set_script_translations( 'apwc-scheduled-actions', 'admin-powerups-for-woocommerce' ); } /* ------------------------------------------------------------------ REST */ /** * REST routes (registered only while the power-up is on). * * @since 1.0.0 * @return void */ public function register_routes() { $ns = 'apwc/v1'; $ids = array( 'required' => true, 'type' => 'array', 'items' => array( 'type' => 'integer', 'minimum' => 1, ), 'minItems' => 1, 'maxItems' => Jobs::MAX_IDS, 'uniqueItems' => true, ); $confirm = array( 'type' => 'string' ); register_rest_route( $ns, '/scheduled-actions/summary', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'rest_summary' ), 'permission_callback' => DevGuard::permission( $this, DevGuard::SAFE ), 'args' => array( 'refresh' => array( 'type' => 'boolean', 'default' => false, ), ), ) ); register_rest_route( $ns, '/scheduled-actions/(?P\d+)', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'rest_detail' ), 'permission_callback' => DevGuard::permission( $this, DevGuard::SAFE ), 'args' => array( 'id' => array( 'type' => 'integer', 'minimum' => 1, ), ), ) ); register_rest_route( $ns, '/scheduled-actions/(?P\d+)/run', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'rest_run' ), 'permission_callback' => DevGuard::permission( $this, DevGuard::REVIEW ), 'args' => array( 'id' => array( 'type' => 'integer', 'minimum' => 1, ), ), ) ); register_rest_route( $ns, '/scheduled-actions/retry', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'rest_retry' ), // Review; actions that may charge again need Advanced + the typed word (retry_charge_ok()). 'permission_callback' => DevGuard::permission( $this, DevGuard::REVIEW ), 'args' => array( 'ids' => $ids, 'confirm' => $confirm, ), ) ); register_rest_route( $ns, '/scheduled-actions/cancel', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'rest_cancel' ), 'permission_callback' => DevGuard::permission( $this, DevGuard::ADVANCED, '', 'cancel' ), 'args' => array( 'ids' => $ids, 'confirm' => $confirm, ), ) ); register_rest_route( $ns, '/scheduled-actions/delete', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'rest_delete' ), 'permission_callback' => DevGuard::permission( $this, DevGuard::ADVANCED, '', 'delete' ), 'args' => array( 'ids' => $ids, 'confirm' => $confirm, ), ) ); register_rest_route( $ns, '/scheduled-actions/purge', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'rest_purge' ), 'permission_callback' => DevGuard::permission( $this, DevGuard::ADVANCED, '', 'purge' ), 'args' => array( 'status' => array( 'required' => true, 'type' => 'string', 'enum' => array( 'complete', 'failed', 'canceled' ), ), 'days' => array( 'required' => true, 'type' => 'integer', 'minimum' => 1, 'maximum' => 3650, ), 'confirm' => $confirm, ), ) ); } /** * 409 when Action Scheduler can't be read here, else null. * * @return WP_Error|null */ private function rest_unavailable() { $reason = Monitor::unavailable(); return '' === $reason ? null : new WP_Error( 'apwc_sa_unavailable', $reason, array( 'status' => 409 ) ); } /** * GET /scheduled-actions/summary. * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function rest_summary( WP_REST_Request $request ) { $error = $this->rest_unavailable(); if ( $error ) { return $error; } return rest_ensure_response( Monitor::summary( (bool) $request['refresh'] ) ); } /** * GET /scheduled-actions/{id}: details, also used to poll a Run now. * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function rest_detail( WP_REST_Request $request ) { $error = $this->rest_unavailable(); if ( $error ) { return $error; } $detail = Monitor::detail( (int) $request['id'] ); if ( null === $detail ) { return Jobs::refuse( null, 'run' ); // 404 "gone". } return rest_ensure_response( $detail ); } /** * POST /scheduled-actions/{id}/run: queue a background run (202). * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function rest_run( WP_REST_Request $request ) { $error = $this->rest_unavailable(); if ( $error ) { return $error; } $result = Jobs::request_run( (int) $request['id'] ); if ( is_wp_error( $result ) ) { return $result; } return new WP_REST_Response( $result, 202 ); } /** * POST /scheduled-actions/retry. * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function rest_retry( WP_REST_Request $request ) { return $this->bulk( $request, 'retry', '' ); } /** * Whether a retry request confirms actions that may charge again: `confirm` sent, by a user * with the Advanced level, with the right word. No `confirm` = false (those actions are then * skipped); a `confirm` from a user without Advanced is a 403, a wrong word a 400. * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return bool|WP_Error */ private function retry_charge_ok( WP_REST_Request $request ) { $typed = $request->get_param( 'confirm' ); if ( null === $typed || '' === $typed ) { return false; } if ( ! DevGuard::can( $this, DevGuard::ADVANCED ) ) { return new WP_Error( 'apwc_forbidden', __( 'Retrying actions that may charge again needs an admin who can make Advanced changes.', 'admin-powerups-for-woocommerce' ), array( 'status' => 403 ) ); } $ok = DevGuard::check_confirm( $request, DevGuard::confirm_word( 'retry' ) ); return is_wp_error( $ok ) ? $ok : true; } /** * POST /scheduled-actions/cancel (typed confirmation). * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function rest_cancel( WP_REST_Request $request ) { return $this->bulk( $request, 'cancel', 'cancel' ); } /** * POST /scheduled-actions/delete (typed confirmation). * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function rest_delete( WP_REST_Request $request ) { return $this->bulk( $request, 'delete', 'delete' ); } /** * Run a bulk change. When nothing could be changed, answers with the first refusal's error * (403 protected, 404 gone, 409 wrong status); otherwise 200 with what was done and skipped. * * @param WP_REST_Request $request Request. * @param string $op retry | cancel | delete. * @param string $confirm Confirmation action ('' for none). * @return WP_REST_Response|WP_Error */ private function bulk( WP_REST_Request $request, string $op, string $confirm ) { if ( '' !== $confirm ) { $ok = DevGuard::check_confirm( $request, DevGuard::confirm_word( $confirm ) ); if ( is_wp_error( $ok ) ) { return $ok; } } $error = $this->rest_unavailable(); if ( $error ) { return $error; } $charge_ok = false; if ( 'retry' === $op ) { $charge_ok = $this->retry_charge_ok( $request ); if ( is_wp_error( $charge_ok ) ) { return $charge_ok; } } $ids = array_map( 'intval', (array) $request['ids'] ); switch ( $op ) { case 'cancel': $result = Jobs::cancel( $ids ); break; case 'delete': $result = Jobs::delete( $ids ); break; default: $result = Jobs::retry( $ids, $charge_ok ); } if ( ! $result['done'] && $result['skipped'] ) { $first = $result['skipped'][0]; return new WP_Error( $first['code'], $first['message'], array( 'status' => $first['status'], 'skipped' => $result['skipped'], ) ); } return rest_ensure_response( $result + array( 'message' => $this->bulk_message( $op, count( $result['done'] ), count( $result['skipped'] ) ) ) ); } /** * Result line of a bulk change. * * @param string $op retry | cancel | delete. * @param int $done Changed. * @param int $skipped Skipped. * @return string */ private function bulk_message( string $op, int $done, int $skipped ): string { switch ( $op ) { case 'cancel': /* translators: %s: number of actions. */ $text = sprintf( _n( '%s action canceled.', '%s actions canceled.', $done, 'admin-powerups-for-woocommerce' ), number_format_i18n( $done ) ); break; case 'delete': /* translators: %s: number of actions. */ $text = sprintf( _n( '%s action deleted.', '%s actions deleted.', $done, 'admin-powerups-for-woocommerce' ), number_format_i18n( $done ) ); break; default: /* translators: %s: number of actions. */ $text = sprintf( _n( '%s action queued to run again.', '%s actions queued to run again.', $done, 'admin-powerups-for-woocommerce' ), number_format_i18n( $done ) ); } if ( $skipped ) { /* translators: %s: number of actions. */ $text .= ' ' . sprintf( _n( '%s skipped.', '%s skipped.', $skipped, 'admin-powerups-for-woocommerce' ), number_format_i18n( $skipped ) ); } return $text; } /** * POST /scheduled-actions/purge: one bounded step; the page repeats it until `left` is 0. * * @since 1.0.0 * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function rest_purge( WP_REST_Request $request ) { $ok = DevGuard::check_confirm( $request, DevGuard::confirm_word( 'purge' ) ); if ( is_wp_error( $ok ) ) { return $ok; } $error = $this->rest_unavailable(); if ( $error ) { return $error; } return rest_ensure_response( Jobs::purge_step( (string) $request['status'], (int) $request['days'], self::purge_batch(), (float) self::purge_seconds() ) ); } }