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