409 ) ); } return null; } /** * The level "Run now" needs for a hook: `review` for most hooks, `advanced` for hooks * WordPress core or WooCommerce own (by name or by a callback in their files: running them * early publishes scheduled posts, cancels unpaid orders, starts sales …), and '' when it is * refused (other protected hooks: Action Scheduler's queue, this plugin's own jobs, hooks * protected by the site filter). * * @since 1.0.0 * @param string $hook Cron hook. * @return string `review`, `advanced` or ''. */ public static function run_level( string $hook ): string { switch ( ProtectedHooks::reason( $hook ) ) { case '': return DevGuard::REVIEW; case 'core': case 'woocommerce': case 'callback_core': case 'callback_woocommerce': return DevGuard::ADVANCED; default: return ''; } } /** * Run an event now: due or overdue events are left in place and a cron run is started; a * future one-off event is moved to now (so it doesn't run twice); a future recurring event * gets one extra run now and keeps its schedule. Refused (403) for hooks run_level() refuses; * the caller checks the Advanced level and typed word for WordPress and WooCommerce hooks. * * @since 1.0.0 * @param string $hook Hook. * @param int $timestamp Scheduled time. * @param string $sig Args signature. * @return array|WP_Error */ public static function run( string $hook, int $timestamp, string $sig ) { $blocked = self::check_writable(); if ( $blocked ) { return $blocked; } if ( '' === self::run_level( $hook ) ) { return new WP_Error( 'apwc_cron_protected', __( 'This hook is protected, so it can’t be run from here. It runs on its own schedule.', 'admin-powerups-for-woocommerce' ), array( 'status' => 403 ) ); } $event = Events::find( $hook, $timestamp, $sig ); if ( ! $event ) { return self::gone(); } if ( ! self::matches( $event ) ) { return self::unmatched(); } $args = $event['args']; $now = time(); if ( $timestamp <= $now ) { // Already due: nothing to change, a cron run picks it up. $mode = 'due'; $message = __( 'This event is already due.', 'admin-powerups-for-woocommerce' ); } elseif ( self::identical_due_soon( $hook, $sig, $timestamp, $now ) ) { $mode = 'duplicate'; $message = self::duplicate_message(); } elseif ( $timestamp <= $now + 10 * MINUTE_IN_SECONDS ) { // WP-Cron treats events within 10 minutes as the same run: leave it where it is. $mode = 'due_soon'; $message = __( 'It’s due within 10 minutes anyway, so it was left as it is.', 'admin-powerups-for-woocommerce' ); } elseif ( '' === $event['schedule'] ) { $moved = self::move_to_now( $hook, $timestamp, $args, $now, $sig ); if ( is_wp_error( $moved ) ) { return $moved; } if ( 'came_back' === $moved ) { $mode = 'came_back'; $message = __( 'It moved, but the old time came back (another process saved cron at the same time), so it may run again then.', 'admin-powerups-for-woocommerce' ); } else { $mode = 'moved'; $message = __( 'Moved to now. It won’t run again at its old time.', 'admin-powerups-for-woocommerce' ); } $timestamp = $now; } else { $added = wp_schedule_single_event( $now, $hook, $args, true ); if ( is_wp_error( $added ) ) { if ( 'duplicate_event' !== $added->get_error_code() ) { return self::scheduling_error( $added ); } $mode = 'duplicate'; $message = self::duplicate_message(); } else { $mode = 'extra'; $message = __( 'Added one extra run now. Its schedule stays the same.', 'admin-powerups-for-woocommerce' ); } } /** * Fires after the Cron inspector made an event due to run now (before a cron run is * started). The hook itself has not run. * * @since 1.0.0 * @param string $hook Hook. * @param int $timestamp Time it was scheduled for. * @param mixed $args Event args (raw; may hold objects). * @param string $mode `due`, `moved`, `came_back`, `extra`, `due_soon` or `duplicate`. */ do_action( 'apwc_cron_event_run_requested', $hook, (int) $event['timestamp'], $event['args'], $mode ); $spawn = self::spawn(); return array( 'mode' => $mode, 'message' => $message, 'spawn' => $spawn, 'timestamp' => $timestamp, ); } /** * Start a WP-Cron run in the background, and say honestly what happened. * * @since 1.0.0 * @param bool|null $disabled Whether DISABLE_WP_CRON is on (null: read the constant; tests pass it). * @param bool|null $alternate Whether ALTERNATE_WP_CRON is on (null: read the constant). * @return array{state: string, message: string} */ public static function spawn( $disabled = null, $alternate = null ): array { $disabled = null === $disabled ? defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON : (bool) $disabled; $alternate = null === $alternate ? defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON : (bool) $alternate; if ( $disabled ) { return array( 'state' => 'server_cron', 'message' => __( 'WP-Cron is turned off here (DISABLE_WP_CRON), so it runs at the next server cron run.', 'admin-powerups-for-woocommerce' ), ); } if ( $alternate ) { // spawn_cron() only works on a page load here; it refuses this request. return array( 'state' => 'next_visit', 'message' => __( 'This site uses the alternate cron (ALTERNATE_WP_CRON), so it runs on the next page visit.', 'admin-powerups-for-woocommerce' ), ); } $lock = get_transient( 'doing_cron' ); $lock = is_numeric( $lock ) ? (float) $lock : 0.0; $timeout = defined( 'WP_CRON_LOCK_TIMEOUT' ) ? (int) WP_CRON_LOCK_TIMEOUT : MINUTE_IN_SECONDS; $now = microtime( true ); if ( $lock > 0 && $lock <= $now + 10 * MINUTE_IN_SECONDS && $lock + $timeout > $now ) { return array( 'state' => 'locked', 'message' => __( 'Cron is already running; it will pick this up.', 'admin-powerups-for-woocommerce' ), ); } if ( spawn_cron() ) { return array( 'state' => 'spawned', 'message' => __( 'Started a cron run in the background.', 'admin-powerups-for-woocommerce' ), ); } return array( 'state' => 'not_started', 'message' => __( 'Couldn’t start a cron run from here, so it runs on the next page visit or server cron run.', 'admin-powerups-for-woocommerce' ), ); } /** * Delete events, each read fresh and matched by time, hook and args signature. * * @since 1.0.0 * @param array $events Events (already validated). * @return array */ public static function delete( array $events ): array { $out = array(); foreach ( $events as $ref ) { $out[] = array_merge( $ref, self::delete_one( $ref['hook'], $ref['timestamp'], $ref['sig'] ) ); } return $out; } /** * Delete every event of a hook that has no callback. * * @since 1.0.0 * @param string $hook Hook. * @return array{deleted: int, left: int, message: string}|WP_Error */ public static function delete_hook( string $hook ) { $blocked = self::check_writable(); if ( $blocked ) { return $blocked; } $reason = ProtectedHooks::reason( $hook ); if ( '' !== $reason ) { return new WP_Error( 'apwc_cron_protected', ProtectedHooks::label( $reason ), array( 'status' => 403 ) ); } if ( Events::has_callback( $hook ) ) { return new WP_Error( 'apwc_cron_has_callback', __( 'This hook has a callback now. Delete its events one by one if you’re sure.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); } $owner = Owners::guess( $hook, 'cron_hook' ); if ( ! Events::owner_allows_bulk_delete( $owner ) ) { $label = Events::owner_label( $owner['type'], $owner['slug'], $owner['name'] ); return new WP_Error( 'apwc_cron_owner_active', '' === $label || 'unknown' === $owner['state'] ? __( 'It isn’t clear which plugin owns this hook, and it may add its callback only while cron runs, so its events are kept. Delete them one by one if you’re sure.', 'admin-powerups-for-woocommerce' ) : sprintf( /* translators: %s: plugin, theme, "WordPress" or "WooCommerce". */ __( '%s is active and may add its callback only while cron runs, so its events are kept. Delete them one by one if you’re sure.', 'admin-powerups-for-woocommerce' ), $label ), array( 'status' => 403 ) ); } $found = array(); foreach ( ( new Events() )->all() as $event ) { if ( $event['hook'] === $hook ) { $found[] = $event; } } if ( ! $found ) { return new WP_Error( 'apwc_cron_gone', __( 'This hook has no events any more. Reload the list.', 'admin-powerups-for-woocommerce' ), array( 'status' => 404 ) ); } $result = wp_unschedule_hook( $hook, true ); if ( is_wp_error( $result ) ) { return self::scheduling_error( $result ); } $left = 0; foreach ( ( new Events() )->all() as $event ) { if ( $event['hook'] === $hook ) { ++$left; } } $deleted = max( 0, count( $found ) - $left ); if ( $deleted > 0 ) { foreach ( $found as $event ) { if ( ! Events::find( $hook, $event['timestamp'], $event['sig'] ) ) { /** This action is documented in src/Modules/CronInspector/Actions.php */ do_action( 'apwc_cron_event_deleted', $hook, $event['timestamp'], $event['args'] ); } } } $message = $left /* translators: 1: events deleted, 2: events that came back. */ ? sprintf( __( 'Deleted %1$s. %2$s came back (another process saved cron at the same time).', 'admin-powerups-for-woocommerce' ), number_format_i18n( $deleted ), number_format_i18n( $left ) ) /* translators: %s: number of events. */ : sprintf( _n( 'Deleted %s event.', 'Deleted %s events.', $deleted, 'admin-powerups-for-woocommerce' ), number_format_i18n( $deleted ) ); return array( 'deleted' => $deleted, 'left' => $left, 'message' => $message, ); } /** * Delete one event. * * @since 1.0.0 * @param string $hook Hook. * @param int $timestamp Time. * @param string $sig Args signature. * @return array{result: string, message: string} Result: deleted, gone, protected, came_back or failed. */ private static function delete_one( string $hook, int $timestamp, string $sig ): array { $event = Events::find( $hook, $timestamp, $sig ); if ( ! $event ) { return array( 'result' => 'gone', 'message' => __( 'Already gone.', 'admin-powerups-for-woocommerce' ), ); } $reason = ProtectedHooks::reason( $hook ); if ( '' !== $reason ) { return array( 'result' => 'protected', 'message' => ProtectedHooks::label( $reason ), ); } if ( ! self::matches( $event ) ) { return array( 'result' => 'unmatched', 'message' => self::unmatched()->get_error_message(), ); } $done = wp_unschedule_event( $timestamp, $hook, $event['args'], true ); if ( is_wp_error( $done ) ) { return array( 'result' => 'failed', 'message' => wp_strip_all_tags( $done->get_error_message() ), ); } if ( Events::find( $hook, $timestamp, $sig ) ) { return array( 'result' => 'came_back', 'message' => __( 'It came back (another process saved cron at the same time).', 'admin-powerups-for-woocommerce' ), ); } /** * Fires after the Cron inspector deleted a cron event. * * @since 1.0.0 * @param string $hook Hook. * @param int $timestamp Time it was scheduled for. * @param mixed $args Event args (raw; may hold objects). */ do_action( 'apwc_cron_event_deleted', $hook, $timestamp, $event['args'] ); return array( 'result' => 'deleted', 'message' => __( 'Deleted.', 'admin-powerups-for-woocommerce' ), ); } /** * Move a future one-off event (more than 10 minutes away) to now: the copy at now is added * first and the old one removed only after that worked, so a refused change never loses it. * * @since 1.0.0 * @param string $hook Hook. * @param int $timestamp Old time. * @param array $args Args (already checked against the signature). * @param int $now New time. * @param string $sig Args signature. * @return true|string|WP_Error True when moved, `came_back` when the old time came back. */ private static function move_to_now( string $hook, int $timestamp, array $args, int $now, string $sig ) { $added = wp_schedule_single_event( $now, $hook, $args, true ); if ( is_wp_error( $added ) ) { return new WP_Error( 'apwc_cron_not_moved', /* translators: %s: error message. */ sprintf( __( 'Couldn’t move the event (%s). It keeps its old time.', 'admin-powerups-for-woocommerce' ), wp_strip_all_tags( $added->get_error_message() ) ), array( 'status' => 409 ) ); } $removed = wp_unschedule_event( $timestamp, $hook, $args, true ); if ( ! is_wp_error( $removed ) ) { // Another process may have saved cron from an older copy meanwhile. return Events::find( $hook, $timestamp, $sig ) ? 'came_back' : true; } wp_unschedule_event( $now, $hook, $args, true ); // Undo the copy so it doesn't run twice. if ( Events::find( $hook, $now, $sig ) ) { return new WP_Error( 'apwc_cron_partly_moved', __( 'Added a run for now but couldn’t remove the old one or the copy, so it may run twice. Delete one of them.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); } return new WP_Error( 'apwc_cron_not_moved', /* translators: %s: error message. */ sprintf( __( 'Couldn’t move the event (%s). It keeps its old time.', 'admin-powerups-for-woocommerce' ), wp_strip_all_tags( $removed->get_error_message() ) ), array( 'status' => 409 ) ); } /** * Whether an event's stored args still produce its key (the signature WordPress matches on). * When they don't, WordPress's cron functions would act on a different event. * * @since 1.0.0 * @param array $event Event from Events::find(). * @return bool */ private static function matches( array $event ): bool { // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- the same key WordPress computes for every cron call on these args. return is_array( $event['args'] ) && md5( serialize( $event['args'] ) ) === $event['sig']; } /** * 409 for an event whose stored data doesn't match its key. * * @since 1.0.0 * @return WP_Error */ private static function unmatched(): WP_Error { return new WP_Error( 'apwc_cron_unmatched', __( 'This event’s stored data doesn’t match its key, so WordPress can’t change it safely.', 'admin-powerups-for-woocommerce' ), array( 'status' => 409 ) ); } /** * Message when the same hook and args are already due. * * @since 1.0.0 * @return string */ private static function duplicate_message(): string { return __( 'The same event (same hook and arguments) is already due, so this one keeps its time.', 'admin-powerups-for-woocommerce' ); } /** * Whether the same hook and args are scheduled at another time that is due within 10 * minutes (WP-Cron would refuse the move as a duplicate). * * @since 1.0.0 * @param string $hook Hook. * @param string $sig Args signature. * @param int $timestamp The event's own time (skipped). * @param int $now Current time. * @return bool */ private static function identical_due_soon( string $hook, string $sig, int $timestamp, int $now ): bool { foreach ( ( new Events() )->all() as $event ) { if ( $event['timestamp'] > $now + 10 * MINUTE_IN_SECONDS ) { break; } if ( $event['hook'] === $hook && $event['sig'] === $sig && $event['timestamp'] !== $timestamp ) { return true; } } return false; } /** * 404 for an event that isn't scheduled any more. * * @since 1.0.0 * @return WP_Error */ public static function gone(): WP_Error { return new WP_Error( 'apwc_cron_gone', __( 'This event isn’t scheduled any more. Reload the list.', 'admin-powerups-for-woocommerce' ), array( 'status' => 404 ) ); } /** * A cron function's error as a REST error. * * @since 1.0.0 * @param WP_Error $error Error from a cron function. * @return WP_Error */ private static function scheduling_error( WP_Error $error ): WP_Error { return new WP_Error( 'apwc_cron_failed', /* translators: %s: error message from WordPress. */ sprintf( __( 'WordPress couldn’t change the event: %s', 'admin-powerups-for-woocommerce' ), wp_strip_all_tags( $error->get_error_message() ) ), array( 'status' => 409 ) ); } }