class-events.php 6.61 KB
Newer Older
Erick Hitter's avatar
Erick Hitter committed
1
2
<?php

3
namespace Automattic\WP\Cron_Control;
Erick Hitter's avatar
Erick Hitter committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

class Events extends Singleton {
	/**
	 * PLUGIN SETUP
	 */

	/**
	 * Class properties
	 */
	const LOCK = 'run-events';

	/**
	 * Register hooks
	 */
	protected function class_init() {
		// Prime lock cache if not present
		Lock::prime_lock( self::LOCK );
	}

	/**
	 * List events pending for the current period
	 */
	public function get_events() {
		$events = get_option( 'cron' );

		// That was easy
		if ( ! is_array( $events ) || empty( $events ) ) {
			return array( 'events' => null, );
		}

		// Simplify array format for further processing
		$events = collapse_events_array( $events );

		// Select only those events to run in the next sixty seconds
		// Will include missed events as well
		$current_events = $internal_events = array();
		$current_window = strtotime( sprintf( '+%d seconds', JOB_QUEUE_WINDOW_IN_SECONDS ) );

		foreach ( $events as $event ) {
			// Skip events whose time hasn't come
			if ( $event['timestamp'] > $current_window ) {
				continue;
			}

			// Necessary data to identify an individual event
			// `$event['action']` is hashed to avoid information disclosure
			// Core hashes `$event['instance']` for us
			$event = array(
				'timestamp' => $event['timestamp'],
				'action'    => md5( $event['action'] ),
				'instance'  => $event['instance'],
			);

			// Queue internal events separately to avoid them being blocked
			if ( is_internal_event( $event['action'] ) ) {
				$internal_events[] = $event;
			} else {
				$current_events[] = $event;
			}
		}

		// Limit batch size to avoid resource exhaustion
		if ( count( $current_events ) > JOB_QUEUE_SIZE ) {
			$current_events = array_slice( $current_events, 0, JOB_QUEUE_SIZE );
		}

		return array(
			'events'   => array_merge( $current_events, $internal_events ),
72
			'endpoint' => get_rest_url( null, REST_API::API_NAMESPACE . '/' . REST_API::ENDPOINT_RUN ),
Erick Hitter's avatar
Erick Hitter committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
		);
	}

	/**
	 * Find an event's data using its hashed representations
	 *
	 * The `$instance` argument is hashed for us by Core, while we hash the action to avoid information disclosure
	 */
	private function get_event( $timestamp, $action_hashed, $instance ) {
		$events = get_option( 'cron' );
		$event  = false;

		$filtered_events = collapse_events_array( $events, $timestamp );

		foreach ( $filtered_events as $filtered_event ) {
			if ( hash_equals( md5( $filtered_event['action'] ), $action_hashed ) && hash_equals( $filtered_event['instance'], $instance ) ) {
				$event = $filtered_event['args'];
				$event['timestamp'] = $filtered_event['timestamp'];
				$event['action']    = $filtered_event['action'];
				$event['instance']  = $filtered_event['instance'];
				break;
			}
		}

		return $event;
	}

	/**
	 * Execute a specific event
	 *
	 * @param $timestamp  int     Unix timestamp
	 * @param $action     string  md5 hash of the action used when the event is registered
	 * @param $instance   string  md5 hash of the event's arguments array, which Core uses to index the `cron` option
	 *
	 * @return array|\WP_Error
	 */
	public function run_event( $timestamp, $action, $instance ) {
		// Validate input data
		if ( empty( $timestamp ) || empty( $action ) || empty( $instance ) ) {
112
			return new \WP_Error( 'missing-data', __( 'Invalid or incomplete request data.', 'automattic-cron-control' ), array( 'status' => 400, ) );
Erick Hitter's avatar
Erick Hitter committed
113
114
115
116
		}

		// Ensure we don't run jobs too far ahead
		if ( $timestamp > strtotime( sprintf( '+%d seconds', JOB_EXECUTION_BUFFER_IN_SECONDS ) ) ) {
117
			return new \WP_Error( 'premature', sprintf( __( 'Job with identifier `%1$s` is not scheduled to run yet.', 'automattic-cron-control' ), "$timestamp-$action-$instance" ), array( 'status' => 403, ) );
Erick Hitter's avatar
Erick Hitter committed
118
119
120
121
122
123
124
		}

		// Find the event to retrieve the full arguments
		$event = $this->get_event( $timestamp, $action, $instance );

		// Nothing to do...
		if ( ! is_array( $event ) ) {
125
			return new \WP_Error( 'no-event', sprintf( __( 'Job with identifier `%1$s` could not be found.', 'automattic-cron-control' ), "$timestamp-$action-$instance" ), array( 'status' => 404, ) );
Erick Hitter's avatar
Erick Hitter committed
126
127
		}

128
129
		unset( $timestamp, $action, $instance );

Erick Hitter's avatar
Erick Hitter committed
130
131
132
133
134
		// And we're off!
		$time_start = microtime( true );

		// Limit how many events are processed concurrently
		if ( ! is_internal_event( $event['action'] ) && ! Lock::check_lock( self::LOCK ) ) {
135
			return new \WP_Error( 'no-free-threads', sprintf( __( 'No resources available to run the job with action action `%1$s` and arguments `%2$s`.', 'automattic-cron-control' ), $event['action'], maybe_serialize( $event['args'] ) ), array( 'status' => 429, ) );
Erick Hitter's avatar
Erick Hitter committed
136
137
		}

Erick Hitter's avatar
Erick Hitter committed
138
139
140
		// Mark the event completed, and reschedule if desired
		$this->update_event_record( $event );

Erick Hitter's avatar
Erick Hitter committed
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
		// Prepare environment to run job
		ignore_user_abort( true );
		set_time_limit( JOB_TIMEOUT_IN_MINUTES * MINUTE_IN_SECONDS );
		define( 'DOING_CRON', true );

		// Run the event
		do_action_ref_array( $event['action'], $event['args'] );

		// Free process for the next event
		if ( ! is_internal_event( $event['action'] ) ) {
			Lock::free_lock( self::LOCK );
		}

		$time_end = microtime( true );

		return array(
			'success' => true,
158
			'message' => sprintf( __( 'Job with action `%1$s` and arguments `%2$s` completed in %3$d seconds.', 'automattic-cron-control' ), $event['action'], maybe_serialize( $event['args'] ), $time_end - $time_start ),
Erick Hitter's avatar
Erick Hitter committed
159
160
		);
	}
161
162
163
164
165
166

	/**
	 * Mark an event completed, and reschedule when requested
	 */
	private function update_event_record( $event ) {
		if ( false !== $event['schedule'] ) {
Erick Hitter's avatar
Erick Hitter committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
			// Re-implements much of the logic from `wp_reschedule_event()`
			$schedules = wp_get_schedules();
			$interval  = 0;

			// First, we try to get it from the schedule
			if ( isset( $schedules[ $event['schedule'] ] ) ) {
				$interval = $schedules[ $event['schedule'] ]['interval'];
			}

			// Now we try to get it from the saved interval, in case the schedule disappears
			if ( 0 == $interval ) {
				$interval = $event['interval'];
			}

			// If we have an interval, create a new event entry
			if ( 0 != $interval ) {
				// Determine new timestamp, according to how `wp_reschedule_event()` does
				$now           = time();
				$new_timestamp = $event['timestamp'];

				if ( $new_timestamp >= $now ) {
					$new_timestamp = $now + $interval;
				} else {
					$new_timestamp = $now + ( $interval - ( ( $now - $new_timestamp ) % $interval ) );
				}

				// Build the expected arguments format
				$event_args = array(
					'schedule' => $event['schedule'],
					'args'     => $event['args'],
					'interval' => $interval,
				);

				Cron_Options_CPT::instance()->create_job( $new_timestamp, $event['action'], $event_args );
			}
202
203
204
205
		}

		Cron_Options_CPT::instance()->mark_job_completed( $event['timestamp'], $event['action'], $event['instance'] );
	}
Erick Hitter's avatar
Erick Hitter committed
206
207
208
}

Events::instance();