*/ public static function summary( bool $refresh = false ): array { $cached = get_transient( self::SUMMARY ); if ( is_array( $cached ) && isset( $cached['time'] ) && ( ! $refresh || time() - (int) $cached['time'] < self::REFRESH_LIMIT ) ) { return $cached; } $summary = self::build_summary(); set_transient( self::SUMMARY, $summary, self::SUMMARY_TTL ); return $summary; } /** * Count everything the summary shows. Every query is index-backed; the only full pass is the * GROUP BY status of `action_counts()` over the covering status index. * * @since 1.0.0 * @return array */ public static function build_summary(): array { global $wpdb; $t = self::tables(); $now = time(); $counts = array_fill_keys( array( 'pending', 'in-progress', 'failed', 'complete', 'canceled' ), 0 ); foreach ( (array) \ActionScheduler::store()->action_counts() as $status => $count ) { if ( isset( $counts[ $status ] ) ) { $counts[ $status ] = (int) $count; } } // phpcs:disable WordPress.DB.DirectDatabaseQuery -- read-only counts on Action Scheduler's tables; the result is cached in a transient. $overdue = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE status = %s AND scheduled_date_gmt <= %s', $t['actions'], 'pending', gmdate( 'Y-m-d H:i:s', $now - self::grace() ) ) ); $oldest = $wpdb->get_var( $wpdb->prepare( 'SELECT MIN(scheduled_date_gmt) FROM %i WHERE status = %s AND scheduled_date_gmt >= %s', $t['actions'], 'pending', '1971-01-01 00:00:00' ) ); $stuck = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE status = %s AND last_attempt_gmt < %s', $t['actions'], 'in-progress', gmdate( 'Y-m-d H:i:s', $now - self::STUCK_AFTER ) ) ); $last = $wpdb->get_var( $wpdb->prepare( 'SELECT MAX(last_attempt_gmt) FROM %i WHERE status = %s', $t['actions'], 'complete' ) ); $failed = $counts['failed'] ? $wpdb->get_results( $wpdb->prepare( 'SELECT hook, COUNT(*) AS n FROM %i WHERE status = %s GROUP BY hook ORDER BY n DESC LIMIT 100', $t['actions'], 'failed' ) ) : array(); // phpcs:enable $next = wp_next_scheduled( 'action_scheduler_run_queue', array( 'WP Cron' ) ); return array( 'time' => $now, 'counts' => $counts, 'overdue' => $overdue, 'oldest_gmt' => is_string( $oldest ) ? $oldest : '', 'stuck' => $stuck, 'last_gmt' => is_string( $last ) && '0000-00-00 00:00:00' !== $last ? $last : '', 'next_cron' => $next ? (int) $next : 0, 'failed_by' => self::sort_hooks( is_array( $failed ) ? $failed : array() ), 'tables' => self::table_sizes(), 'has_attempt' => self::has_index( 'status_last_attempt_gmt' ), ); } /** * Failed counts by hook, with WooCommerce's and Action Scheduler's own hooks first. * * @since 1.0.0 * @param object[] $rows Rows with `hook` and `n`. * @return array */ private static function sort_hooks( array $rows ): array { /** * Filter the hook prefixes listed first in "Failed by hook" on the Monitor tab. * * @since 1.0.0 * @param string[] $prefixes Prefixes (default WooCommerce's and Action Scheduler's). */ $prefixes = array_filter( (array) apply_filters( 'apwc_scheduled_actions_priority_prefixes', array( 'woocommerce_', 'wc_', 'wc-admin_', 'wc_admin_', 'woocommerce/', 'action_scheduler/' ) ), 'is_string' ); $out = array(); foreach ( $rows as $i => $row ) { $hook = (string) $row->hook; $first = false; foreach ( $prefixes as $prefix ) { if ( '' !== $prefix && str_starts_with( $hook, $prefix ) ) { $first = true; break; } } $out[] = array( 'hook' => $hook, 'count' => (int) $row->n, 'rank' => array( $first ? 0 : 1, $i ), ); } usort( $out, static fn( $a, $b ) => $a['rank'] <=> $b['rank'] ); return array_map( static fn( $row ) => array( 'hook' => $row['hook'], 'count' => $row['count'], ), $out ); } /** * Approximate size of the actions and logs tables from information_schema (never a COUNT(*) * of the logs). Null when the server refuses, errors, or takes over a second. * * @since 1.0.0 * @return array|null Keyed `actions`, `logs`. */ public static function table_sizes() { global $wpdb; $t = self::tables(); $quiet = $wpdb->suppress_errors( true ); $start = microtime( true ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- table statistics, cached with the summary. $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT TABLE_NAME AS name, DATA_LENGTH + INDEX_LENGTH AS bytes, TABLE_ROWS AS approx FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME IN (%s, %s)', $t['actions'], $t['logs'] ) ); $elapsed = microtime( true ) - $start; $error = $wpdb->last_error; $wpdb->suppress_errors( $quiet ); if ( '' !== $error || ! is_array( $rows ) || ! $rows || $elapsed > 1 ) { return null; } $out = array(); foreach ( $rows as $row ) { $key = $t['logs'] === $row->name ? 'logs' : ( $t['actions'] === $row->name ? 'actions' : '' ); if ( '' !== $key ) { $out[ $key ] = array( 'bytes' => (int) $row->bytes, 'rows' => (int) $row->approx, ); } } return $out ? $out : null; } /** * Whether the actions table has an index (older Action Scheduler versions lack some). * * @since 1.0.0 * @param string $name Index name. * @return bool */ public static function has_index( string $name ): bool { return ActionHistory::has_index( $name ); } /* ------------------------------------------------------------------ lists */ /** * One page of a list. * * @since 1.0.0 * @param array $query `list` (failed|overdue|running), `hook`, `paged`, `per_page`, * `has_attempt` (the status_last_attempt_gmt index exists). * @return array{rows: object[], total: int, pages: int, paged: int, capped: bool} */ public static function page( array $query ): array { global $wpdb; $t = self::tables(); $list = in_array( $query['list'] ?? '', self::LISTS, true ) ? $query['list'] : 'failed'; $hook = (string) ( $query['hook'] ?? '' ); $per_page = in_array( (int) ( $query['per_page'] ?? 0 ), self::PER_PAGE, true ) ? (int) $query['per_page'] : 20; $paged = Paging::page( $query['paged'] ?? 1, $per_page ); $where = array( 'status = %s' ); $args = array(); switch ( $list ) { case 'overdue': $args[] = 'pending'; $where[] = 'scheduled_date_gmt <= %s'; $args[] = gmdate( 'Y-m-d H:i:s', time() - self::grace() ); $order = 'scheduled_date_gmt ASC, action_id ASC'; break; case 'running': $args[] = 'in-progress'; $order = 'last_attempt_gmt ASC, action_id ASC'; break; default: $args[] = 'failed'; $order = empty( $query['has_attempt'] ) ? 'action_id DESC' : 'last_attempt_gmt DESC, action_id DESC'; } if ( '' !== $hook ) { $where[] = 'hook = %s'; $args[] = $hook; } $where = implode( ' AND ', $where ); $outer = self::prefix_order( $order ); // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $where, $order and $outer are fixed fragments from this method (column names chosen by a switch on a whitelisted list); every value is a placeholder. $total = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE {$where}", array_merge( array( $t['actions'] ), $args ) ) ); $pages = min( self::MAX_PAGES, max( 1, (int) ceil( $total / $per_page ) ) ); $paged = min( $paged, $pages ); $offset = ( $paged - 1 ) * $per_page; $rows = $total ? $wpdb->get_results( $wpdb->prepare( // One query: IDs from the index in a derived table, then the row columns (never `schedule`) and group slug. "SELECT a.action_id, a.hook, a.status, a.scheduled_date_gmt, a.last_attempt_gmt, a.attempts, a.claim_id, a.priority, a.args, a.extended_args, g.slug AS group_slug FROM %i a INNER JOIN ( SELECT action_id FROM %i WHERE {$where} ORDER BY {$order} LIMIT %d, %d ) ids ON ids.action_id = a.action_id LEFT JOIN %i g ON g.group_id = a.group_id ORDER BY {$outer}", array_merge( array( $t['actions'], $t['actions'] ), $args, array( $offset, $per_page, $t['groups'] ) ) ) ) : array(); // phpcs:enable $rows = is_array( $rows ) ? $rows : array(); $logs = self::last_logs( array_map( static fn( $row ) => (int) $row->action_id, $rows ) ); foreach ( $rows as $row ) { $row->last_log = $logs[ (int) $row->action_id ] ?? null; } return array( 'rows' => $rows, 'total' => $total, 'pages' => $pages, 'paged' => $paged, 'capped' => $total > self::MAX_PAGES * $per_page, ); } /** * Point an ORDER BY at the `a.` alias. * * @param string $order ORDER BY list from page(). * @return string */ private static function prefix_order( string $order ): string { return implode( ', ', array_map( static fn( $part ) => 'a.' . trim( $part ), explode( ',', $order ) ) ); } /** * Latest log entry of each action, in one query. * * @since 1.0.0 * @param int[] $ids Action IDs. * @return array */ public static function last_logs( array $ids ): array { global $wpdb; $ids = array_values( array_unique( array_filter( array_map( 'intval', $ids ) ) ) ); if ( ! $ids ) { return array(); } $t = self::tables(); $in = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- $in is one %d per ID, all passed. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT l.action_id, l.message, l.log_date_gmt FROM %i l INNER JOIN ( SELECT MAX(log_id) AS log_id FROM %i WHERE action_id IN ({$in}) GROUP BY action_id ) m ON m.log_id = l.log_id", array_merge( array( $t['logs'], $t['logs'] ), $ids ) ) ); $out = array(); foreach ( (array) $rows as $row ) { $out[ (int) $row->action_id ] = array( 'message' => (string) SafeDump::to_array( (string) $row->message, 1, 1000 ), 'date_gmt' => (string) $row->log_date_gmt, ); } return $out; } /* ------------------------------------------------------------------ one action */ /** * One action's row (never the `schedule` column), or null when it's gone. * * @since 1.0.0 * @param int $id Action ID. * @return object|null */ public static function row( int $id ) { global $wpdb; if ( $id < 1 ) { return null; } $t = self::tables(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- one row by primary key; must be live (no cache) before a change. $row = $wpdb->get_row( $wpdb->prepare( 'SELECT a.action_id, a.hook, a.status, a.scheduled_date_gmt, a.last_attempt_gmt, a.attempts, a.claim_id, a.priority, a.group_id, a.args, a.extended_args, g.slug AS group_slug FROM %i a LEFT JOIN %i g ON g.group_id = a.group_id WHERE a.action_id = %d', $t['actions'], $t['groups'], $id ) ); return is_object( $row ) ? $row : null; } /** * Everything the detail view and the Run now poll need. * * @since 1.0.0 * @param int $id Action ID. * @return array|null Null when the action is gone. */ public static function detail( int $id ) { global $wpdb; $row = self::row( $id ); if ( ! $row ) { return null; } $t = self::tables(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- the action's latest 50 log lines. $logs = $wpdb->get_results( $wpdb->prepare( 'SELECT message, log_date_gmt FROM %i WHERE action_id = %d ORDER BY log_id DESC LIMIT 50', $t['logs'], $id ) ); $logs = array_map( static fn( $log ) => array( 'message' => (string) SafeDump::to_array( (string) $log->message, 1, 2000 ), 'date' => self::local_date( (string) $log->log_date_gmt ), ), is_array( $logs ) ? $logs : array() ); $recurrence = self::recurrence( $id ); $args = self::args( $row->args, $row->extended_args ); $hook = (string) $row->hook; $last = $logs[0]['message'] ?? ''; return array( 'id' => (int) $row->action_id, 'hook' => SafeDump::to_array( $hook, 1, 191 ), 'status' => (string) $row->status, 'state' => self::state( $row, $last ), 'group' => (string) ( $row->group_slug ?? '' ), 'priority' => (int) $row->priority, 'attempts' => (int) $row->attempts, 'claimed' => (int) $row->claim_id > 0, 'scheduled' => self::local_date( (string) $row->scheduled_date_gmt ), 'last_attempt' => self::local_date( (string) $row->last_attempt_gmt ), 'recurring' => $recurrence['recurring'], 'recurrence' => $recurrence['text'], 'args' => $args['value'], 'args_ok' => $args['ok'], 'logs' => $logs, 'last_log' => $last, 'protected' => Jobs::is_protected( $hook, (string) ( $row->group_slug ?? '' ) ), 'may_charge' => Jobs::may_charge( $hook ), 'can' => array( 'run' => null === Jobs::refuse( $row, 'run' ), 'retry' => null === Jobs::refuse( $row, 'retry' ), 'cancel' => null === Jobs::refuse( $row, 'cancel' ), 'delete' => null === Jobs::refuse( $row, 'delete' ), ), ); } /** * How often an action repeats, read through Action Scheduler's own loader. * * @since 1.0.0 * @param int $id Action ID. * @return array{recurring: bool, text: string} */ private static function recurrence( int $id ): array { $none = array( 'recurring' => false, 'text' => '', ); try { $action = \ActionScheduler::store()->fetch_action( $id ); } catch ( \Throwable $e ) { return $none; } $schedule = is_object( $action ) && method_exists( $action, 'get_schedule' ) ? $action->get_schedule() : null; if ( ! is_object( $schedule ) || ! method_exists( $schedule, 'is_recurring' ) || ! $schedule->is_recurring() ) { return $none; } $every = method_exists( $schedule, 'get_recurrence' ) ? $schedule->get_recurrence() : null; if ( is_numeric( $every ) && (int) $every > 0 ) { /* translators: %s: interval, e.g. "1 hour". */ $text = sprintf( __( 'Every %s', 'admin-powerups-for-woocommerce' ), human_time_diff( 0, (int) $every ) ); } elseif ( is_string( $every ) && '' !== $every ) { /* translators: %s: cron expression, e.g. "0 3 * * *". */ $text = sprintf( __( 'Cron schedule %s', 'admin-powerups-for-woocommerce' ), (string) SafeDump::to_array( $every, 1, 100 ) ); } else { $text = __( 'Repeats', 'admin-powerups-for-woocommerce' ); } return array( 'recurring' => true, 'text' => $text, ); } /** * State shown for a row: the Action Scheduler status, or `queued` for a waiting action whose * latest log line is a Run now request (so a page refresh still shows it). * * @since 1.0.0 * @param object $row Row with `status`. * @param string $last_log Latest log message. * @return string */ public static function state( $row, string $last_log ): string { $status = (string) $row->status; if ( 'pending' === $status && str_starts_with( $last_log, Jobs::REQUESTED ) ) { return 'queued'; } return $status; } /** * Labels for states. * * @since 1.0.0 * @return array */ public static function state_labels(): array { return array( 'pending' => __( 'Waiting', 'admin-powerups-for-woocommerce' ), 'queued' => __( 'Queued', 'admin-powerups-for-woocommerce' ), 'in-progress' => __( 'Running', 'admin-powerups-for-woocommerce' ), 'complete' => __( 'Done', 'admin-powerups-for-woocommerce' ), 'failed' => __( 'Failed', 'admin-powerups-for-woocommerce' ), 'canceled' => __( 'Canceled', 'admin-powerups-for-woocommerce' ), ); } /* ------------------------------------------------------------------ args and dates */ /** * Sensitive key patterns for action arguments (see MetaMask::arg_patterns()). * * @since 1.0.0 * @return string[] */ public static function sensitive_patterns(): array { return MetaMask::arg_patterns( 'action' ); } /** * Arguments ready to show: JSON-decoded (depth 32, never unserialized), passed through * SafeDump, and values under sensitive keys masked. * * @since 1.0.0 * @param mixed $args `args` column. * @param mixed $extended_args `extended_args` column (used when set: long args live there). * @return array{ok: bool, value: mixed} */ public static function args( $args, $extended_args ): array { $raw = is_string( $extended_args ) && '' !== $extended_args ? $extended_args : ( is_string( $args ) ? $args : '' ); if ( '' === $raw ) { return array( 'ok' => true, 'value' => array(), ); } $value = json_decode( $raw, true, 32 ); if ( JSON_ERROR_NONE !== json_last_error() ) { return array( 'ok' => false, 'value' => null, ); } return array( 'ok' => true, 'value' => self::mask( SafeDump::to_array( $value, 32, 10000, 1000 ), self::sensitive_patterns() ), ); } /** * Mask values whose key matches a sensitive pattern, at any depth. * * @since 1.0.0 * @param mixed $value Value (already through SafeDump). * @param string[] $patterns Patterns. * @return mixed */ public static function mask( $value, array $patterns ) { if ( ! is_array( $value ) || ! $patterns ) { return $value; } foreach ( $value as $key => $item ) { if ( is_string( $key ) && MetaMask::matches( $key, $patterns ) ) { $value[ $key ] = self::MASK; } elseif ( is_array( $item ) ) { $value[ $key ] = self::mask( $item, $patterns ); } } return $value; } /** * Arguments as one short line for a list row. * * @since 1.0.0 * @param object $row Row with `args` and `extended_args`. * @return string */ public static function args_line( $row ): string { $args = self::args( $row->args ?? null, $row->extended_args ?? null ); if ( ! $args['ok'] ) { return __( '(can’t be read)', 'admin-powerups-for-woocommerce' ); } if ( array() === $args['value'] ) { return ''; } $text = (string) wp_json_encode( $args['value'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR ); return mb_strlen( $text ) > self::ROW_ARGS_CHARS ? mb_substr( $text, 0, self::ROW_ARGS_CHARS ) . '…' : $text; } /** * A GMT date from the database, as a Unix time (0 for none). * * @since 1.0.0 * @param string $gmt `Y-m-d H:i:s` in UTC. * @return int */ public static function timestamp( string $gmt ): int { if ( '' === $gmt || str_starts_with( $gmt, '0000-00-00' ) ) { return 0; } $time = strtotime( $gmt . ' UTC' ); return false === $time || $time < 86400 ? 0 : $time; } /** * A GMT date from the database in the site's format and time zone ('' for none). * * @since 1.0.0 * @param string $gmt `Y-m-d H:i:s` in UTC. * @return string */ public static function local_date( string $gmt ): string { $time = self::timestamp( $gmt ); return $time ? (string) wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $time ) : ''; } /** * "5 minutes ago" / "in 5 minutes" for a Unix time ('' for none). * * @since 1.0.0 * @param int $time Unix time. * @return string */ public static function relative( int $time ): string { if ( $time <= 0 ) { return ''; } $now = time(); if ( $time <= $now ) { /* translators: %s: time span, e.g. "5 minutes". */ return sprintf( __( '%s ago', 'admin-powerups-for-woocommerce' ), human_time_diff( $time, $now ) ); } /* translators: %s: time span, e.g. "5 minutes". */ return sprintf( __( 'in %s', 'admin-powerups-for-woocommerce' ), human_time_diff( $now, $time ) ); } }