Make WordPress Core

Ticket #42758: cron.php

File cron.php, 17.2 KB (added by ajami, 6 years ago)

Wp Cron patch

Line 
1<?php
2/**
3 * WordPress Cron API
4 *
5 * @package WordPress
6 */
7
8/**
9 * Schedules an event to run only once.
10 *
11 * Schedules a hook which will be triggered by WordPress at the specified time.
12 * The action will trigger when someone visits your WordPress site if the scheduled
13 * time has passed.
14 *
15 * Note that scheduling an event to occur within 10 minutes of an existing event
16 * with the same action hook will be ignored unless you pass unique `$args` values
17 * for each scheduled event.
18 *
19 * Use wp_next_scheduled() to prevent duplicate events.
20 *
21 * Use wp_schedule_event() to schedule a recurring event.
22 *
23 * @since 2.1.0
24 * @link https://codex.wordpress.org/Function_Reference/wp_schedule_single_event
25 *
26 * @param int    $timestamp  Unix timestamp (UTC) for when to next run the event.
27 * @param string $hook       Action hook to execute when the event is run.
28 * @param array  $args       Optional. Array containing each separate argument to pass to the hook's callback function.
29 * @return false|void False if the event did not get scheduled.
30 */
31function wp_schedule_single_event( $timestamp, $hook, $args = array()) {
32        // Make sure timestamp is a positive integer
33        if ( ! is_numeric( $timestamp ) || $timestamp <= 0 ) {
34                return false;
35        }
36
37        // Don't schedule a duplicate if there's already an identical event due within 10 minutes of it
38        $next = wp_next_scheduled($hook, $args);
39        if ( $next && abs( $next - $timestamp ) <= 10 * MINUTE_IN_SECONDS ) {
40                return false;
41        }
42
43        $crons = _get_cron_array();
44        $event = (object) array( 'hook' => $hook, 'timestamp' => $timestamp, 'schedule' => false, 'args' => $args );
45
46        /**
47         * Filters a single event before it is scheduled.
48         *
49         * @since 3.1.0
50         *
51         * @param stdClass $event {
52         *     An object containing an event's data.
53         *
54         *     @type string       $hook      Action hook to execute when the event is run.
55         *     @type int          $timestamp Unix timestamp (UTC) for when to next run the event.
56         *     @type string|false $schedule  How often the event should subsequently recur.
57         *     @type array        $args      Array containing each separate argument to pass to the hook's callback function.
58         *     @type int          $interval  The interval time in seconds for the schedule. Only present for recurring events.
59         * }
60         */
61        $event = apply_filters( 'schedule_event', $event );
62
63        // A plugin disallowed this event
64        if ( ! $event )
65                return false;
66
67        $key = md5(serialize($event->args));
68
69        $crons[$event->timestamp][$event->hook][$key] = array( 'schedule' => $event->schedule, 'args' => $event->args );
70        uksort( $crons, "strnatcasecmp" );
71        _set_cron_array( $crons );
72}
73
74/**
75 * Schedules a recurring event.
76 *
77 * Schedules a hook which will be triggered by WordPress at the specified interval.
78 * The action will trigger when someone visits your WordPress site if the scheduled
79 * time has passed.
80 *
81 * Valid values for the recurrence are 'hourly', 'daily', and 'twicedaily'. These can
82 * be extended using the {@see 'cron_schedules'} filter in wp_get_schedules().
83 *
84 * Note that scheduling an event to occur within 10 minutes of an existing event
85 * with the same action hook will be ignored unless you pass unique `$args` values
86 * for each scheduled event.
87 *
88 * Use wp_next_scheduled() to prevent duplicate events.
89 *
90 * Use wp_schedule_single_event() to schedule a non-recurring event.
91 *
92 * @since 2.1.0
93 * @link https://codex.wordpress.org/Function_Reference/wp_schedule_event
94 *
95 * @param int    $timestamp  Unix timestamp (UTC) for when to next run the event.
96 * @param string $recurrence How often the event should subsequently recur. See wp_get_schedules() for accepted values.
97 * @param string $hook       Action hook to execute when the event is run.
98 * @param array  $args       Optional. Array containing each separate argument to pass to the hook's callback function.
99 * @return false|void False if the event did not get scheduled.
100 */
101function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array()) {
102        // Make sure timestamp is a positive integer
103        if ( ! is_numeric( $timestamp ) || $timestamp <= 0 ) {
104                return false;
105        }
106
107        $crons = _get_cron_array();
108        $schedules = wp_get_schedules();
109
110        if ( !isset( $schedules[$recurrence] ) )
111                return false;
112
113        $event = (object) array( 'hook' => $hook, 'timestamp' => $timestamp, 'schedule' => $recurrence, 'args' => $args, 'interval' => $schedules[$recurrence]['interval'] );
114        /** This filter is documented in wp-includes/cron.php */
115        $event = apply_filters( 'schedule_event', $event );
116
117        // A plugin disallowed this event
118        if ( ! $event )
119                return false;
120
121        $key = md5(serialize($event->args));
122
123        $crons[$event->timestamp][$event->hook][$key] = array( 'schedule' => $event->schedule, 'args' => $event->args, 'interval' => $event->interval );
124        uksort( $crons, "strnatcasecmp" );
125        _set_cron_array( $crons );
126}
127
128/**
129 * Reschedules a recurring event.
130 *
131 * @since 2.1.0
132 *
133 * @param int    $timestamp  Unix timestamp (UTC) for when to next run the event.
134 * @param string $recurrence How often the event should subsequently recur. See wp_get_schedules() for accepted values.
135 * @param string $hook       Action hook to execute when the event is run.
136 * @param array  $args       Optional. Array containing each separate argument to pass to the hook's callback function.
137 * @return false|void False if the event did not get rescheduled.
138 */
139function wp_reschedule_event( $timestamp, $recurrence, $hook, $args = array() ) {
140        // Make sure timestamp is a positive integer
141        if ( ! is_numeric( $timestamp ) || $timestamp <= 0 ) {
142                return false;
143        }
144
145        $crons = _get_cron_array();
146        $schedules = wp_get_schedules();
147        $key = md5( serialize( $args ) );
148        $interval = 0;
149
150        // First we try to get it from the schedule
151        if ( isset( $schedules[ $recurrence ] ) ) {
152                $interval = $schedules[ $recurrence ]['interval'];
153        }
154        // Now we try to get it from the saved interval in case the schedule disappears
155        if ( 0 == $interval ) {
156                $interval = $crons[ $timestamp ][ $hook ][ $key ]['interval'];
157        }
158        // Now we assume something is wrong and fail to schedule
159        if ( 0 == $interval ) {
160                return false;
161        }
162
163        $now = time();
164
165        if ( $timestamp >= $now ) {
166                $timestamp = $now + $interval;
167        } else {
168                $timestamp = $now + ( $interval - ( ( $now - $timestamp ) % $interval ) );
169        }
170
171        wp_schedule_event( $timestamp, $recurrence, $hook, $args );
172}
173
174/**
175 * Unschedule a previously scheduled event.
176 *
177 * The $timestamp and $hook parameters are required so that the event can be
178 * identified.
179 *
180 * @since 2.1.0
181 *
182 * @param int    $timestamp Unix timestamp (UTC) of the event.
183 * @param string $hook      Action hook of the event.
184 * @param array  $args      Optional. Array containing each separate argument to pass to the hook's callback function.
185 *                          Although not passed to a callback, these arguments are used to uniquely identify the
186 *                          event, so they should be the same as those used when originally scheduling the event.
187 * @return false|void False if the event did not get unscheduled.
188 */
189function wp_unschedule_event( $timestamp, $hook, $args = array() ) {
190        // Make sure timestamp is a positive integer
191        if ( ! is_numeric( $timestamp ) || $timestamp <= 0 ) {
192                return false;
193        }
194
195        $crons = _get_cron_array();
196        $key = md5(serialize($args));
197        unset( $crons[$timestamp][$hook][$key] );
198        if ( empty($crons[$timestamp][$hook]) )
199                unset( $crons[$timestamp][$hook] );
200        if ( empty($crons[$timestamp]) )
201                unset( $crons[$timestamp] );
202        _set_cron_array( $crons );
203}
204
205/**
206 * Unschedules all events attached to the hook with the specified arguments.
207 *
208 * @since 2.1.0
209 *
210 * @param string $hook Action hook, the execution of which will be unscheduled.
211 * @param array $args Optional. Arguments that were to be passed to the hook's callback function.
212 */
213function wp_clear_scheduled_hook( $hook, $args = array() ) {
214        // Backward compatibility
215        // Previously this function took the arguments as discrete vars rather than an array like the rest of the API
216        if ( !is_array($args) ) {
217                _deprecated_argument( __FUNCTION__, '3.0.0', __('This argument has changed to an array to match the behavior of the other cron functions.') );
218                $args = array_slice( func_get_args(), 1 );
219        }
220
221        // This logic duplicates wp_next_scheduled()
222        // It's required due to a scenario where wp_unschedule_event() fails due to update_option() failing,
223        // and, wp_next_scheduled() returns the same schedule in an infinite loop.
224        $crons = _get_cron_array();
225        if ( empty( $crons ) )
226                return;
227
228        $key = md5( serialize( $args ) );
229        foreach ( $crons as $timestamp => $cron ) {
230                if ( isset( $cron[ $hook ][ $key ] ) ) {
231                        wp_unschedule_event( $timestamp, $hook, $args );
232                }
233        }
234}
235
236/**
237 * Unschedules all events attached to the hook.
238 *
239 * Can be useful for plugins when deactivating to clean up the cron queue.
240 *
241 * @since 4.9.0
242 *
243 * @param string $hook Action hook, the execution of which will be unscheduled.
244 */
245function wp_unschedule_hook( $hook ) {
246        $crons = _get_cron_array();
247
248        foreach( $crons as $timestamp => $args ) {
249                unset( $crons[ $timestamp ][ $hook ] );
250
251                if ( empty( $crons[ $timestamp ] ) ) {
252                        unset( $crons[ $timestamp ] );
253                }
254        }
255
256        _set_cron_array( $crons );
257}
258
259/**
260 * Retrieve the next timestamp for an event.
261 *
262 * @since 2.1.0
263 *
264 * @param string $hook Action hook of the event.
265 * @param array  $args Optional. Array containing each separate argument to pass to the hook's callback function.
266 *                     Although not passed to a callback, these arguments are used to uniquely identify the
267 *                     event, so they should be the same as those used when originally scheduling the event.
268 * @return false|int The Unix timestamp of the next time the event will occur. False if the event doesn't exist.
269 */
270function wp_next_scheduled( $hook, $args = array() ) {
271        $crons = _get_cron_array();
272        $key = md5(serialize($args));
273        if ( empty($crons) )
274                return false;
275        foreach ( $crons as $timestamp => $cron ) {
276                if ( isset( $cron[$hook][$key] ) )
277                        return $timestamp;
278        }
279        return false;
280}
281
282/**
283 * Sends a request to run cron through HTTP request that doesn't halt page loading.
284 *
285 * @since 2.1.0
286 *
287 * @param int $gmt_time Optional. Unix timestamp (UTC). Default 0 (current time is used).
288 */
289function spawn_cron( $gmt_time = 0 ) {
290        if ( ! $gmt_time )
291                $gmt_time = microtime( true );
292
293        if ( defined('DOING_CRON') || isset($_GET['doing_wp_cron']) )
294                return;
295
296        /*
297         * Get the cron lock, which is a Unix timestamp of when the last cron was spawned
298         * and has not finished running.
299         *
300         * Multiple processes on multiple web servers can run this code concurrently,
301         * this lock attempts to make spawning as atomic as possible.
302         */
303        $lock = get_transient('doing_cron');
304
305        if ( $lock > $gmt_time + 10 * MINUTE_IN_SECONDS )
306                $lock = 0;
307
308        // don't run if another process is currently running it or more than once every 60 sec.
309        if ( $lock + WP_CRON_LOCK_TIMEOUT > $gmt_time )
310                return;
311
312        //sanity check
313        $crons = _get_cron_array();
314        if ( !is_array($crons) )
315                return;
316
317        $keys = array_keys( $crons );
318        if ( isset($keys[0]) && $keys[0] > $gmt_time )
319                return;
320
321        if ( defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON ) {
322                if ( 'GET' !== $_SERVER['REQUEST_METHOD'] || defined( 'DOING_AJAX' ) ||  defined( 'XMLRPC_REQUEST' ) ) {
323                        return;
324                }
325
326                $doing_wp_cron = sprintf( '%.22F', $gmt_time );
327                set_transient( 'doing_cron', $doing_wp_cron );
328
329                ob_start();
330                wp_redirect( add_query_arg( 'doing_wp_cron', $doing_wp_cron, wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
331                echo ' ';
332
333                // flush any buffers and send the headers
334                while ( @ob_end_flush() );
335                flush();
336
337                WP_DEBUG ? include_once( ABSPATH . 'wp-cron.php' ) : @include_once( ABSPATH . 'wp-cron.php' );
338                return;
339        }
340
341        // Set the cron lock with the current unix timestamp, when the cron is being spawned.
342        $doing_wp_cron = sprintf( '%.22F', $gmt_time );
343        set_transient( 'doing_cron', $doing_wp_cron );
344
345        /**
346         * Filters the cron request arguments.
347         *
348         * @since 3.5.0
349         * @since 4.5.0 The `$doing_wp_cron` parameter was added.
350         *
351         * @param array $cron_request_array {
352         *     An array of cron request URL arguments.
353         *
354         *     @type string $url  The cron request URL.
355         *     @type int    $key  The 22 digit GMT microtime.
356         *     @type array  $args {
357         *         An array of cron request arguments.
358         *
359         *         @type int  $timeout   The request timeout in seconds. Default .01 seconds.
360         *         @type bool $blocking  Whether to set blocking for the request. Default false.
361         *         @type bool $sslverify Whether SSL should be verified for the request. Default false.
362         *     }
363         * }
364         * @param string $doing_wp_cron The unix timestamp of the cron lock.
365         */
366        $cron_request = apply_filters( 'cron_request', array(
367                'url'  => add_query_arg( 'doing_wp_cron', $doing_wp_cron, site_url( 'wp-cron.php' ) ),
368                'key'  => $doing_wp_cron,
369                'args' => array(
370                        'timeout'   => 0.01,
371                        'blocking'  => false,
372                        /** This filter is documented in wp-includes/class-wp-http-streams.php */
373                        'sslverify' => apply_filters( 'https_local_ssl_verify', false )
374                )
375        ), $doing_wp_cron );
376
377        wp_remote_post( $cron_request['url'], $cron_request['args'] );
378}
379
380/**
381 * Run scheduled callbacks or spawn cron for all scheduled events.
382 *
383 * @since 2.1.0
384 */
385function wp_cron() {
386        // Prevent infinite loops caused by lack of wp-cron.php
387        if ( strpos($_SERVER['REQUEST_URI'], '/wp-cron.php') !== false || ( defined('DISABLE_WP_CRON') && DISABLE_WP_CRON ) )
388                return;
389
390        if ( false === $crons = _get_cron_array() )
391                return;
392
393        $gmt_time = microtime( true );
394        $keys = array_keys( $crons );
395        if ( isset($keys[0]) && $keys[0] > $gmt_time )
396                return;
397
398        $schedules = wp_get_schedules();
399        foreach ( $crons as $timestamp => $cronhooks ) {
400                if ( $timestamp > $gmt_time ) break;
401                foreach ( (array) $cronhooks as $hook => $args ) {
402                        if ( isset($schedules[$hook]['callback']) && !call_user_func( $schedules[$hook]['callback'] ) )
403                                continue;
404                        apply_action( $hook, $args );
405                        spawn_cron( $gmt_time );
406                        break 2;
407                }
408        }
409}
410
411/**
412 * Retrieve supported event recurrence schedules.
413 *
414 * The default supported recurrences are 'hourly', 'twicedaily', and 'daily'. A plugin may
415 * add more by hooking into the {@see 'cron_schedules'} filter. The filter accepts an array
416 * of arrays. The outer array has a key that is the name of the schedule or for
417 * example 'weekly'. The value is an array with two keys, one is 'interval' and
418 * the other is 'display'.
419 *
420 * The 'interval' is a number in seconds of when the cron job should run. So for
421 * 'hourly', the time is 3600 or 60*60. For weekly, the value would be
422 * 60*60*24*7 or 604800. The value of 'interval' would then be 604800.
423 *
424 * The 'display' is the description. For the 'weekly' key, the 'display' would
425 * be `__( 'Once Weekly' )`.
426 *
427 * For your plugin, you will be passed an array. you can easily add your
428 * schedule by doing the following.
429 *
430 *     // Filter parameter variable name is 'array'.
431 *     $array['weekly'] = array(
432 *         'interval' => 604800,
433 *         'display'  => __( 'Once Weekly' )
434 *     );
435 *
436 *
437 * @since 2.1.0
438 *
439 * @return array
440 */
441function wp_get_schedules() {
442        $schedules = array(
443                'hourly'     => array( 'interval' => HOUR_IN_SECONDS,      'display' => __( 'Once Hourly' ) ),
444                'twicedaily' => array( 'interval' => 12 * HOUR_IN_SECONDS, 'display' => __( 'Twice Daily' ) ),
445                'daily'      => array( 'interval' => DAY_IN_SECONDS,       'display' => __( 'Once Daily' ) ),
446        );
447        /**
448         * Filters the non-default cron schedules.
449         *
450         * @since 2.1.0
451         *
452         * @param array $new_schedules An array of non-default cron schedules. Default empty.
453         */
454        return array_merge( apply_filters( 'cron_schedules', array() ), $schedules );
455}
456
457/**
458 * Retrieve the recurrence schedule for an event.
459 *
460 * @see wp_get_schedules() for available schedules.
461 *
462 * @since 2.1.0
463 *
464 * @param string $hook Action hook to identify the event.
465 * @param array $args Optional. Arguments passed to the event's callback function.
466 * @return string|false False, if no schedule. Schedule name on success.
467 */
468function wp_get_schedule($hook, $args = array()) {
469        $crons = _get_cron_array();
470        $key = md5(serialize($args));
471        if ( empty($crons) )
472                return false;
473        foreach ( $crons as $timestamp => $cron ) {
474                if ( isset( $cron[$hook][$key] ) )
475                        return $cron[$hook][$key]['schedule'];
476        }
477        return false;
478}
479
480//
481// Private functions
482//
483
484/**
485 * Retrieve cron info array option.
486 *
487 * @since 2.1.0
488 * @access private
489 *
490 * @return false|array CRON info array.
491 */
492function _get_cron_array()  {
493        $cron = get_option('cron');
494        if ( ! is_array($cron) )
495                return false;
496
497        if ( !isset($cron['version']) )
498                $cron = _upgrade_cron_array($cron);
499
500        unset($cron['version']);
501
502        return $cron;
503}
504
505/**
506 * Updates the CRON option with the new CRON array.
507 *
508 * @since 2.1.0
509 * @access private
510 *
511 * @param array $cron Cron info array from _get_cron_array().
512 */
513function _set_cron_array($cron) {
514        $cron['version'] = 2;
515        update_option( 'cron', $cron );
516}
517
518/**
519 * Upgrade a Cron info array.
520 *
521 * This function upgrades the Cron info array to version 2.
522 *
523 * @since 2.1.0
524 * @access private
525 *
526 * @param array $cron Cron info array from _get_cron_array().
527 * @return array An upgraded Cron info array.
528 */
529function _upgrade_cron_array($cron) {
530        if ( isset($cron['version']) && 2 == $cron['version'])
531                return $cron;
532
533        $new_cron = array();
534
535        foreach ( (array) $cron as $timestamp => $hooks) {
536                foreach ( (array) $hooks as $hook => $args ) {
537                        $key = md5(serialize($args['args']));
538                        $new_cron[$timestamp][$hook][$key] = $args;
539                }
540        }
541
542        $new_cron['version'] = 2;
543        update_option( 'cron', $new_cron );
544        return $new_cron;
545}