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