__( 'Pending', 'adminease' ), 'in-progress' => __( 'In Progress', 'adminease' ), 'complete' => __( 'Complete', 'adminease' ), 'failed' => __( 'Failed', 'adminease' ), 'canceled' => __( 'Canceled', 'adminease' ), ]; } /** * Enqueues the Scheduled Actions script on the AdminEase admin page. * * The styles live in AdminEaseCronViewerLog.css, which the Cron Viewer * already enqueues on the same screen. * * @param string $hook Current admin page hook. * * @return void */ public function admin_enqueue_scripts( string $hook ): void { if ( 'toplevel_page_adminease' !== $hook || ! self::is_available() ) { return; } wp_enqueue_script( ADMINEASE_NAME . 'ScheduledActions', ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseScheduledActions.js', [ 'jquery', ADMINEASE_NAME ], filemtime( ADMINEASE_DIR . 'assets/js/AdminEaseScheduledActions.js' ), true ); wp_localize_script( ADMINEASE_NAME . 'ScheduledActions', ADMINEASE_NAME . 'ScheduledActionsAjaxObj', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'security' => [ 'getActions' => wp_create_nonce( 'adminease_get_scheduled_actions' ), 'runAction' => wp_create_nonce( 'adminease_run_scheduled_action' ), 'cancelAction' => wp_create_nonce( 'adminease_cancel_scheduled_action' ), 'getLogs' => wp_create_nonce( 'adminease_get_scheduled_action_logs' ), ], 'i18n' => [ 'confirmRun' => esc_html__( 'Are you sure you want to run this action now?', 'adminease' ), 'confirmCancel' => esc_html__( 'Are you sure you want to cancel this action? It will not run.', 'adminease' ), 'runFailed' => esc_html__( 'Failed to run the action.', 'adminease' ), 'cancelFailed' => esc_html__( 'Failed to cancel the action.', 'adminease' ), 'loadFailed' => esc_html__( 'Failed to load data.', 'adminease' ), 'logsLoading' => esc_html__( 'Loading log…', 'adminease' ), 'noLogs' => esc_html__( 'No log entries for this action.', 'adminease' ), 'btnProcessing' => esc_html__( 'Processing…', 'adminease' ), 'btnDone' => esc_html__( 'Done!', 'adminease' ), /* translators: 1: current page, 2: total pages */ 'paginationInfo' => esc_html__( 'Page %1$s of %2$s', 'adminease' ), /* translators: 1: start, 2: end, 3: total */ 'actionCount' => esc_html__( 'Showing %1$s-%2$s of %3$s actions', 'adminease' ), 'actionDetails' => esc_html__( 'Action Details', 'adminease' ), 'labelId' => esc_html__( 'ID', 'adminease' ), 'labelHook' => esc_html__( 'Hook', 'adminease' ), 'labelStatus' => esc_html__( 'Status', 'adminease' ), 'labelGroup' => esc_html__( 'Group', 'adminease' ), 'labelScheduled' => esc_html__( 'Scheduled For', 'adminease' ), 'labelRecurrence' => esc_html__( 'Recurrence', 'adminease' ), 'labelArguments' => esc_html__( 'Arguments', 'adminease' ), 'labelLog' => esc_html__( 'Log', 'adminease' ), 'noGroup' => esc_html__( 'None', 'adminease' ), ], ] ); } // ------------------------------------------------------------------------- // Data // ------------------------------------------------------------------------- /** * Returns a page of actions from the Action Scheduler store. * * @param array $args { * @type int $page Page number. Default 1. * @type int $per_page Items per page, 1-200. Default 50. * @type string $status One of self::STATUSES, or '' for all. Default 'pending'. * @type string $group Exact group slug. Default ''. * @type string $search Matched against hook, args and group by the store. Default ''. * } * * @return array { 'actions' => array, 'total' => int } */ public function get_actions( array $args ): array { $page = max( 1, (int) ( $args['page'] ?? 1 ) ); $per_page = min( 200, max( 1, (int) ( $args['per_page'] ?? 50 ) ) ); $status = (string) ( $args['status'] ?? 'pending' ); $query = [ 'orderby' => 'date', 'order' => 'pending' === $status ? 'ASC' : 'DESC', ]; if ( in_array( $status, self::STATUSES, true ) ) { $query['status'] = $status; } if ( '' !== ( $args['group'] ?? '' ) ) { $query['group'] = $args['group']; } if ( '' !== ( $args['search'] ?? '' ) ) { $query['search'] = $args['search']; } $store = ActionScheduler::store(); $total = (int) $store->query_actions( $query, 'count' ); $query['per_page'] = $per_page; $query['offset'] = ( $page - 1 ) * $per_page; $actions = []; foreach ( (array) $store->query_actions( $query ) as $action_id ) { $action = $this->describe_action( (int) $action_id ); if ( null !== $action ) { $actions[] = $action; } } return [ 'actions' => $actions, 'total' => $total, ]; } /** * Per-status totals for the status filter. * * @return array Status => count, for every status in self::STATUSES. */ public function get_status_counts(): array { $counts = []; try { $counts = (array) ActionScheduler::store()->action_counts(); } catch ( Exception $e ) { $counts = []; } $result = []; foreach ( self::STATUSES as $status ) { $result[ $status ] = (int) ( $counts[ $status ] ?? 0 ); } return $result; } /** * Reads one action into a plain array for rendering. * * @param int $action_id Action ID. * * @return array|null Null when the action no longer exists. */ private function describe_action( int $action_id ): ?array { $store = ActionScheduler::store(); try { $action = $store->fetch_action( $action_id ); $status = $store->get_status( $action_id ); } catch ( Exception $e ) { return null; } if ( ! $action || '' === $action->get_hook() ) { return null; } $schedule = $action->get_schedule(); $date = null; $recurrence = ''; if ( $schedule && method_exists( $schedule, 'get_date' ) ) { $date = $schedule->get_date(); } elseif ( $schedule && method_exists( $schedule, 'next' ) ) { $date = $schedule->next(); } if ( $schedule && method_exists( $schedule, 'is_recurring' ) && $schedule->is_recurring() && method_exists( $schedule, 'get_recurrence' ) ) { $raw = $schedule->get_recurrence(); if ( is_numeric( $raw ) ) { /* translators: %s: human readable interval, e.g. "5 mins" */ $recurrence = sprintf( __( 'Every %s', 'adminease' ), human_time_diff( 0, (int) $raw ) ); } else { $recurrence = (string) $raw; } } return [ 'id' => $action_id, 'hook' => $action->get_hook(), 'status' => (string) $status, 'group' => (string) $action->get_group(), 'args' => (array) $action->get_args(), 'timestamp' => $date ? (int) $date->getTimestamp() : 0, 'recurrence' => $recurrence, ]; } /** * Renders the table rows for a page of actions. * * @param array $actions Rows from get_actions(). * * @return string */ public function render_actions_rows( array $actions ): string { $labels = self::get_status_labels(); $datetime_format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' ); $now = time(); $badges = [ 'pending' => 'pwp-badge-primary', 'in-progress' => 'pwp-badge-citron', 'complete' => 'pwp-badge-success', 'failed' => 'pwp-badge-fail', 'canceled' => 'pwp-badge-muted', ]; ob_start(); foreach ( $actions as $action ) { $args_encoded = (string) wp_json_encode( $action['args'] ); $args_short = mb_strlen( $args_encoded ) > 30 ? mb_substr( $args_encoded, 0, 30 ) . '...' : $args_encoded; $exact_time = $action['timestamp'] > 0 ? wp_date( $datetime_format, $action['timestamp'] ) : '-'; $status_label = $labels[ $action['status'] ] ?? $action['status']; $relative = ''; if ( $action['timestamp'] > 0 ) { $diff = human_time_diff( $action['timestamp'], $now ); if ( $action['timestamp'] > $now ) { /* translators: %s: human readable time difference, e.g. "5 mins" */ $relative = sprintf( __( 'in %s', 'adminease' ), $diff ); } else { /* translators: %s: human readable time difference, e.g. "5 mins" */ $relative = sprintf( __( '%s ago', 'adminease' ), $diff ); } } ?> - get_status( $action_id ) : ''; } catch ( Exception $e ) { $status = ''; } if ( '' === $status ) { wp_send_json_error( new WP_Error( 'not_found', __( 'This action no longer exists.', 'adminease' ) ) ); } return [ $action_id, $status ]; } /** * AJAX: Returns a filtered page of actions as table rows, plus status counts. * * @return void */ public function ajax_get_scheduled_actions(): void { $this->verify_request( 'adminease_get_scheduled_actions' ); // phpcs:disable WordPress.Security.NonceVerification.Missing -- Verified in verify_request(). $args = [ 'page' => isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 1, 'per_page' => isset( $_POST['per_page'] ) ? absint( $_POST['per_page'] ) : 50, 'status' => isset( $_POST['status'] ) ? sanitize_key( wp_unslash( $_POST['status'] ) ) : 'pending', 'group' => isset( $_POST['group'] ) ? sanitize_text_field( wp_unslash( $_POST['group'] ) ) : '', 'search' => isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '', ]; // phpcs:enable WordPress.Security.NonceVerification.Missing try { $result = $this->get_actions( $args ); } catch ( Exception $e ) { wp_send_json_error( new WP_Error( 'query_failed', $e->getMessage() ) ); } wp_send_json_success( [ 'rows_html' => $this->render_actions_rows( $result['actions'] ), 'total' => $result['total'], 'page' => max( 1, $args['page'] ), 'per_page' => min( 200, max( 1, $args['per_page'] ) ), 'counts' => $this->get_status_counts(), ] ); } /** * AJAX: Runs one pending action now, through Action Scheduler's own runner * so it is claimed, logged and marked complete or failed as usual. * * @return void */ public function ajax_run_scheduled_action(): void { $this->verify_request( 'adminease_run_scheduled_action' ); list( $action_id, $status ) = $this->get_posted_action(); if ( ActionScheduler_Store::STATUS_PENDING !== $status ) { wp_send_json_error( new WP_Error( 'not_pending', __( 'Only pending actions can be run.', 'adminease' ) ) ); } try { ActionScheduler::runner()->process_action( $action_id, 'AdminEase' ); $new_status = (string) ActionScheduler::store()->get_status( $action_id ); } catch ( Exception $e ) { wp_send_json_error( new WP_Error( 'run_failed', $e->getMessage() ) ); } if ( ActionScheduler_Store::STATUS_FAILED === $new_status ) { wp_send_json_error( new WP_Error( 'run_failed', __( 'The action ran but failed. Open its details to see the log.', 'adminease' ) ) ); } wp_send_json_success( [ 'message' => __( 'Action ran successfully.', 'adminease' ) ] ); } /** * AJAX: Cancels one pending action. * * @return void */ public function ajax_cancel_scheduled_action(): void { $this->verify_request( 'adminease_cancel_scheduled_action' ); list( $action_id, $status ) = $this->get_posted_action(); if ( ActionScheduler_Store::STATUS_PENDING !== $status ) { wp_send_json_error( new WP_Error( 'not_pending', __( 'Only pending actions can be canceled.', 'adminease' ) ) ); } try { ActionScheduler::store()->cancel_action( $action_id ); } catch ( Exception $e ) { wp_send_json_error( new WP_Error( 'cancel_failed', $e->getMessage() ) ); } wp_send_json_success( [ 'message' => __( 'Action canceled.', 'adminease' ) ] ); } /** * AJAX: Returns Action Scheduler's own log entries for one action. * * @return void */ public function ajax_get_scheduled_action_logs(): void { $this->verify_request( 'adminease_get_scheduled_action_logs' ); list( $action_id ) = $this->get_posted_action(); $datetime_format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' ); $logs = []; try { foreach ( (array) ActionScheduler::logger()->get_logs( $action_id ) as $entry ) { $date = $entry->get_date(); $logs[] = [ 'date' => $date ? wp_date( $datetime_format, $date->getTimestamp() ) : '', 'message' => (string) $entry->get_message(), ]; } } catch ( Exception $e ) { wp_send_json_error( new WP_Error( 'logs_failed', $e->getMessage() ) ); } wp_send_json_success( [ 'logs' => $logs ] ); } }