PageRenderTime 124ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/cron.php

https://github.com/markjaquith/WordPress
PHP | 1243 lines | 547 code | 139 blank | 557 comment | 127 complexity | ae5befdd6a4531c2797694ad55fdc68a MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1
  1. <?php
  2. /**
  3. * WordPress Cron API
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * Schedules an event to run only once.
  9. *
  10. * Schedules a hook which will be triggered by WordPress at the specified time.
  11. * The action will trigger when someone visits your WordPress site if the scheduled
  12. * time has passed.
  13. *
  14. * Note that scheduling an event to occur within 10 minutes of an existing event
  15. * with the same action hook will be ignored unless you pass unique `$args` values
  16. * for each scheduled event.
  17. *
  18. * Use wp_next_scheduled() to prevent duplicate events.
  19. *
  20. * Use wp_schedule_event() to schedule a recurring event.
  21. *
  22. * @since 2.1.0
  23. * @since 5.1.0 Return value modified to boolean indicating success or failure,
  24. * {@see 'pre_schedule_event'} filter added to short-circuit the function.
  25. * @since 5.7.0 The `$wp_error` parameter was added.
  26. *
  27. * @link https://developer.wordpress.org/reference/functions/wp_schedule_single_event/
  28. *
  29. * @param int $timestamp Unix timestamp (UTC) for when to next run the event.
  30. * @param string $hook Action hook to execute when the event is run.
  31. * @param array $args Optional. Array containing arguments to pass to the
  32. * hook's callback function. Each value in the array
  33. * is passed to the callback as an individual parameter.
  34. * The array keys are ignored. Default empty array.
  35. * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false.
  36. * @return bool|WP_Error True if event successfully scheduled. False or WP_Error on failure.
  37. */
  38. function wp_schedule_single_event( $timestamp, $hook, $args = array(), $wp_error = false ) {
  39. // Make sure timestamp is a positive integer.
  40. if ( ! is_numeric( $timestamp ) || $timestamp <= 0 ) {
  41. if ( $wp_error ) {
  42. return new WP_Error(
  43. 'invalid_timestamp',
  44. __( 'Event timestamp must be a valid Unix timestamp.' )
  45. );
  46. }
  47. return false;
  48. }
  49. $event = (object) array(
  50. 'hook' => $hook,
  51. 'timestamp' => $timestamp,
  52. 'schedule' => false,
  53. 'args' => $args,
  54. );
  55. /**
  56. * Filter to preflight or hijack scheduling an event.
  57. *
  58. * Returning a non-null value will short-circuit adding the event to the
  59. * cron array, causing the function to return the filtered value instead.
  60. *
  61. * Both single events and recurring events are passed through this filter;
  62. * single events have `$event->schedule` as false, whereas recurring events
  63. * have this set to a recurrence from wp_get_schedules(). Recurring
  64. * events also have the integer recurrence interval set as `$event->interval`.
  65. *
  66. * For plugins replacing wp-cron, it is recommended you check for an
  67. * identical event within ten minutes and apply the {@see 'schedule_event'}
  68. * filter to check if another plugin has disallowed the event before scheduling.
  69. *
  70. * Return true if the event was scheduled, false or a WP_Error if not.
  71. *
  72. * @since 5.1.0
  73. * @since 5.7.0 The `$wp_error` parameter was added, and a `WP_Error` object can now be returned.
  74. *
  75. * @param null|bool|WP_Error $pre Value to return instead. Default null to continue adding the event.
  76. * @param stdClass $event {
  77. * An object containing an event's data.
  78. *
  79. * @type string $hook Action hook to execute when the event is run.
  80. * @type int $timestamp Unix timestamp (UTC) for when to next run the event.
  81. * @type string|false $schedule How often the event should subsequently recur.
  82. * @type array $args Array containing each separate argument to pass to the hook's callback function.
  83. * @type int $interval The interval time in seconds for the schedule. Only present for recurring events.
  84. * }
  85. * @param bool $wp_error Whether to return a WP_Error on failure.
  86. */
  87. $pre = apply_filters( 'pre_schedule_event', null, $event, $wp_error );
  88. if ( null !== $pre ) {
  89. if ( $wp_error && false === $pre ) {
  90. return new WP_Error(
  91. 'pre_schedule_event_false',
  92. __( 'A plugin prevented the event from being scheduled.' )
  93. );
  94. }
  95. if ( ! $wp_error && is_wp_error( $pre ) ) {
  96. return false;
  97. }
  98. return $pre;
  99. }
  100. /*
  101. * Check for a duplicated event.
  102. *
  103. * Don't schedule an event if there's already an identical event
  104. * within 10 minutes.
  105. *
  106. * When scheduling events within ten minutes of the current time,
  107. * all past identical events are considered duplicates.
  108. *
  109. * When scheduling an event with a past timestamp (ie, before the
  110. * current time) all events scheduled within the next ten minutes
  111. * are considered duplicates.
  112. */
  113. $crons = _get_cron_array();
  114. if ( ! is_array( $crons ) ) {
  115. $crons = array();
  116. }
  117. $key = md5( serialize( $event->args ) );
  118. $duplicate = false;
  119. if ( $event->timestamp < time() + 10 * MINUTE_IN_SECONDS ) {
  120. $min_timestamp = 0;
  121. } else {
  122. $min_timestamp = $event->timestamp - 10 * MINUTE_IN_SECONDS;
  123. }
  124. if ( $event->timestamp < time() ) {
  125. $max_timestamp = time() + 10 * MINUTE_IN_SECONDS;
  126. } else {
  127. $max_timestamp = $event->timestamp + 10 * MINUTE_IN_SECONDS;
  128. }
  129. foreach ( $crons as $event_timestamp => $cron ) {
  130. if ( $event_timestamp < $min_timestamp ) {
  131. continue;
  132. }
  133. if ( $event_timestamp > $max_timestamp ) {
  134. break;
  135. }
  136. if ( isset( $cron[ $event->hook ][ $key ] ) ) {
  137. $duplicate = true;
  138. break;
  139. }
  140. }
  141. if ( $duplicate ) {
  142. if ( $wp_error ) {
  143. return new WP_Error(
  144. 'duplicate_event',
  145. __( 'A duplicate event already exists.' )
  146. );
  147. }
  148. return false;
  149. }
  150. /**
  151. * Modify an event before it is scheduled.
  152. *
  153. * @since 3.1.0
  154. *
  155. * @param stdClass|false $event {
  156. * An object containing an event's data, or boolean false to prevent the event from being scheduled.
  157. *
  158. * @type string $hook Action hook to execute when the event is run.
  159. * @type int $timestamp Unix timestamp (UTC) for when to next run the event.
  160. * @type string|false $schedule How often the event should subsequently recur.
  161. * @type array $args Array containing each separate argument to pass to the hook's callback function.
  162. * @type int $interval The interval time in seconds for the schedule. Only present for recurring events.
  163. * }
  164. */
  165. $event = apply_filters( 'schedule_event', $event );
  166. // A plugin disallowed this event.
  167. if ( ! $event ) {
  168. if ( $wp_error ) {
  169. return new WP_Error(
  170. 'schedule_event_false',
  171. __( 'A plugin disallowed this event.' )
  172. );
  173. }
  174. return false;
  175. }
  176. $crons[ $event->timestamp ][ $event->hook ][ $key ] = array(
  177. 'schedule' => $event->schedule,
  178. 'args' => $event->args,
  179. );
  180. uksort( $crons, 'strnatcasecmp' );
  181. return _set_cron_array( $crons, $wp_error );
  182. }
  183. /**
  184. * Schedules a recurring event.
  185. *
  186. * Schedules a hook which will be triggered by WordPress at the specified interval.
  187. * The action will trigger when someone visits your WordPress site if the scheduled
  188. * time has passed.
  189. *
  190. * Valid values for the recurrence are 'hourly', 'daily', and 'twicedaily'. These can
  191. * be extended using the {@see 'cron_schedules'} filter in wp_get_schedules().
  192. *
  193. * Note that scheduling an event to occur within 10 minutes of an existing event
  194. * with the same action hook will be ignored unless you pass unique `$args` values
  195. * for each scheduled event.
  196. *
  197. * Use wp_next_scheduled() to prevent duplicate events.
  198. *
  199. * Use wp_schedule_single_event() to schedule a non-recurring event.
  200. *
  201. * @since 2.1.0
  202. * @since 5.1.0 Return value modified to boolean indicating success or failure,
  203. * {@see 'pre_schedule_event'} filter added to short-circuit the function.
  204. * @since 5.7.0 The `$wp_error` parameter was added.
  205. *
  206. * @link https://developer.wordpress.org/reference/functions/wp_schedule_event/
  207. *
  208. * @param int $timestamp Unix timestamp (UTC) for when to next run the event.
  209. * @param string $recurrence How often the event should subsequently recur.
  210. * See wp_get_schedules() for accepted values.
  211. * @param string $hook Action hook to execute when the event is run.
  212. * @param array $args Optional. Array containing arguments to pass to the
  213. * hook's callback function. Each value in the array
  214. * is passed to the callback as an individual parameter.
  215. * The array keys are ignored. Default empty array.
  216. * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false.
  217. * @return bool|WP_Error True if event successfully scheduled. False or WP_Error on failure.
  218. */
  219. function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array(), $wp_error = false ) {
  220. // Make sure timestamp is a positive integer.
  221. if ( ! is_numeric( $timestamp ) || $timestamp <= 0 ) {
  222. if ( $wp_error ) {
  223. return new WP_Error(
  224. 'invalid_timestamp',
  225. __( 'Event timestamp must be a valid Unix timestamp.' )
  226. );
  227. }
  228. return false;
  229. }
  230. $schedules = wp_get_schedules();
  231. if ( ! isset( $schedules[ $recurrence ] ) ) {
  232. if ( $wp_error ) {
  233. return new WP_Error(
  234. 'invalid_schedule',
  235. __( 'Event schedule does not exist.' )
  236. );
  237. }
  238. return false;
  239. }
  240. $event = (object) array(
  241. 'hook' => $hook,
  242. 'timestamp' => $timestamp,
  243. 'schedule' => $recurrence,
  244. 'args' => $args,
  245. 'interval' => $schedules[ $recurrence ]['interval'],
  246. );
  247. /** This filter is documented in wp-includes/cron.php */
  248. $pre = apply_filters( 'pre_schedule_event', null, $event, $wp_error );
  249. if ( null !== $pre ) {
  250. if ( $wp_error && false === $pre ) {
  251. return new WP_Error(
  252. 'pre_schedule_event_false',
  253. __( 'A plugin prevented the event from being scheduled.' )
  254. );
  255. }
  256. if ( ! $wp_error && is_wp_error( $pre ) ) {
  257. return false;
  258. }
  259. return $pre;
  260. }
  261. /** This filter is documented in wp-includes/cron.php */
  262. $event = apply_filters( 'schedule_event', $event );
  263. // A plugin disallowed this event.
  264. if ( ! $event ) {
  265. if ( $wp_error ) {
  266. return new WP_Error(
  267. 'schedule_event_false',
  268. __( 'A plugin disallowed this event.' )
  269. );
  270. }
  271. return false;
  272. }
  273. $key = md5( serialize( $event->args ) );
  274. $crons = _get_cron_array();
  275. if ( ! is_array( $crons ) ) {
  276. $crons = array();
  277. }
  278. $crons[ $event->timestamp ][ $event->hook ][ $key ] = array(
  279. 'schedule' => $event->schedule,
  280. 'args' => $event->args,
  281. 'interval' => $event->interval,
  282. );
  283. uksort( $crons, 'strnatcasecmp' );
  284. return _set_cron_array( $crons, $wp_error );
  285. }
  286. /**
  287. * Reschedules a recurring event.
  288. *
  289. * Mainly for internal use, this takes the time stamp of a previously run
  290. * recurring event and reschedules it for its next run.
  291. *
  292. * To change upcoming scheduled events, use wp_schedule_event() to
  293. * change the recurrence frequency.
  294. *
  295. * @since 2.1.0
  296. * @since 5.1.0 Return value modified to boolean indicating success or failure,
  297. * {@see 'pre_reschedule_event'} filter added to short-circuit the function.
  298. * @since 5.7.0 The `$wp_error` parameter was added.
  299. *
  300. * @param int $timestamp Unix timestamp (UTC) for when the event was scheduled.
  301. * @param string $recurrence How often the event should subsequently recur.
  302. * See wp_get_schedules() for accepted values.
  303. * @param string $hook Action hook to execute when the event is run.
  304. * @param array $args Optional. Array containing arguments to pass to the
  305. * hook's callback function. Each value in the array
  306. * is passed to the callback as an individual parameter.
  307. * The array keys are ignored. Default empty array.
  308. * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false.
  309. * @return bool|WP_Error True if event successfully rescheduled. False or WP_Error on failure.
  310. */
  311. function wp_reschedule_event( $timestamp, $recurrence, $hook, $args = array(), $wp_error = false ) {
  312. // Make sure timestamp is a positive integer.
  313. if ( ! is_numeric( $timestamp ) || $timestamp <= 0 ) {
  314. if ( $wp_error ) {
  315. return new WP_Error(
  316. 'invalid_timestamp',
  317. __( 'Event timestamp must be a valid Unix timestamp.' )
  318. );
  319. }
  320. return false;
  321. }
  322. $schedules = wp_get_schedules();
  323. $interval = 0;
  324. // First we try to get the interval from the schedule.
  325. if ( isset( $schedules[ $recurrence ] ) ) {
  326. $interval = $schedules[ $recurrence ]['interval'];
  327. }
  328. // Now we try to get it from the saved interval in case the schedule disappears.
  329. if ( 0 === $interval ) {
  330. $scheduled_event = wp_get_scheduled_event( $hook, $args, $timestamp );
  331. if ( $scheduled_event && isset( $scheduled_event->interval ) ) {
  332. $interval = $scheduled_event->interval;
  333. }
  334. }
  335. $event = (object) array(
  336. 'hook' => $hook,
  337. 'timestamp' => $timestamp,
  338. 'schedule' => $recurrence,
  339. 'args' => $args,
  340. 'interval' => $interval,
  341. );
  342. /**
  343. * Filter to preflight or hijack rescheduling of events.
  344. *
  345. * Returning a non-null value will short-circuit the normal rescheduling
  346. * process, causing the function to return the filtered value instead.
  347. *
  348. * For plugins replacing wp-cron, return true if the event was successfully
  349. * rescheduled, false if not.
  350. *
  351. * @since 5.1.0
  352. * @since 5.7.0 The `$wp_error` parameter was added, and a `WP_Error` object can now be returned.
  353. *
  354. * @param null|bool|WP_Error $pre Value to return instead. Default null to continue adding the event.
  355. * @param stdClass $event {
  356. * An object containing an event's data.
  357. *
  358. * @type string $hook Action hook to execute when the event is run.
  359. * @type int $timestamp Unix timestamp (UTC) for when to next run the event.
  360. * @type string|false $schedule How often the event should subsequently recur.
  361. * @type array $args Array containing each separate argument to pass to the hook's callback function.
  362. * @type int $interval The interval time in seconds for the schedule. Only present for recurring events.
  363. * }
  364. * @param bool $wp_error Whether to return a WP_Error on failure.
  365. */
  366. $pre = apply_filters( 'pre_reschedule_event', null, $event, $wp_error );
  367. if ( null !== $pre ) {
  368. if ( $wp_error && false === $pre ) {
  369. return new WP_Error(
  370. 'pre_reschedule_event_false',
  371. __( 'A plugin prevented the event from being rescheduled.' )
  372. );
  373. }
  374. if ( ! $wp_error && is_wp_error( $pre ) ) {
  375. return false;
  376. }
  377. return $pre;
  378. }
  379. // Now we assume something is wrong and fail to schedule.
  380. if ( 0 == $interval ) {
  381. if ( $wp_error ) {
  382. return new WP_Error(
  383. 'invalid_schedule',
  384. __( 'Event schedule does not exist.' )
  385. );
  386. }
  387. return false;
  388. }
  389. $now = time();
  390. if ( $timestamp >= $now ) {
  391. $timestamp = $now + $interval;
  392. } else {
  393. $timestamp = $now + ( $interval - ( ( $now - $timestamp ) % $interval ) );
  394. }
  395. return wp_schedule_event( $timestamp, $recurrence, $hook, $args, $wp_error );
  396. }
  397. /**
  398. * Unschedule a previously scheduled event.
  399. *
  400. * The $timestamp and $hook parameters are required so that the event can be
  401. * identified.
  402. *
  403. * @since 2.1.0
  404. * @since 5.1.0 Return value modified to boolean indicating success or failure,
  405. * {@see 'pre_unschedule_event'} filter added to short-circuit the function.
  406. * @since 5.7.0 The `$wp_error` parameter was added.
  407. *
  408. * @param int $timestamp Unix timestamp (UTC) of the event.
  409. * @param string $hook Action hook of the event.
  410. * @param array $args Optional. Array containing each separate argument to pass to the hook's callback function.
  411. * Although not passed to a callback, these arguments are used to uniquely identify the
  412. * event, so they should be the same as those used when originally scheduling the event.
  413. * Default empty array.
  414. * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false.
  415. * @return bool|WP_Error True if event successfully unscheduled. False or WP_Error on failure.
  416. */
  417. function wp_unschedule_event( $timestamp, $hook, $args = array(), $wp_error = false ) {
  418. // Make sure timestamp is a positive integer.
  419. if ( ! is_numeric( $timestamp ) || $timestamp <= 0 ) {
  420. if ( $wp_error ) {
  421. return new WP_Error(
  422. 'invalid_timestamp',
  423. __( 'Event timestamp must be a valid Unix timestamp.' )
  424. );
  425. }
  426. return false;
  427. }
  428. /**
  429. * Filter to preflight or hijack unscheduling of events.
  430. *
  431. * Returning a non-null value will short-circuit the normal unscheduling
  432. * process, causing the function to return the filtered value instead.
  433. *
  434. * For plugins replacing wp-cron, return true if the event was successfully
  435. * unscheduled, false if not.
  436. *
  437. * @since 5.1.0
  438. * @since 5.7.0 The `$wp_error` parameter was added, and a `WP_Error` object can now be returned.
  439. *
  440. * @param null|bool|WP_Error $pre Value to return instead. Default null to continue unscheduling the event.
  441. * @param int $timestamp Timestamp for when to run the event.
  442. * @param string $hook Action hook, the execution of which will be unscheduled.
  443. * @param array $args Arguments to pass to the hook's callback function.
  444. * @param bool $wp_error Whether to return a WP_Error on failure.
  445. */
  446. $pre = apply_filters( 'pre_unschedule_event', null, $timestamp, $hook, $args, $wp_error );
  447. if ( null !== $pre ) {
  448. if ( $wp_error && false === $pre ) {
  449. return new WP_Error(
  450. 'pre_unschedule_event_false',
  451. __( 'A plugin prevented the event from being unscheduled.' )
  452. );
  453. }
  454. if ( ! $wp_error && is_wp_error( $pre ) ) {
  455. return false;
  456. }
  457. return $pre;
  458. }
  459. $crons = _get_cron_array();
  460. $key = md5( serialize( $args ) );
  461. unset( $crons[ $timestamp ][ $hook ][ $key ] );
  462. if ( empty( $crons[ $timestamp ][ $hook ] ) ) {
  463. unset( $crons[ $timestamp ][ $hook ] );
  464. }
  465. if ( empty( $crons[ $timestamp ] ) ) {
  466. unset( $crons[ $timestamp ] );
  467. }
  468. return _set_cron_array( $crons, $wp_error );
  469. }
  470. /**
  471. * Unschedules all events attached to the hook with the specified arguments.
  472. *
  473. * Warning: This function may return Boolean FALSE, but may also return a non-Boolean
  474. * value which evaluates to FALSE. For information about casting to booleans see the
  475. * {@link https://www.php.net/manual/en/language.types.boolean.php PHP documentation}. Use
  476. * the `===` operator for testing the return value of this function.
  477. *
  478. * @since 2.1.0
  479. * @since 5.1.0 Return value modified to indicate success or failure,
  480. * {@see 'pre_clear_scheduled_hook'} filter added to short-circuit the function.
  481. * @since 5.7.0 The `$wp_error` parameter was added.
  482. *
  483. * @param string $hook Action hook, the execution of which will be unscheduled.
  484. * @param array $args Optional. Array containing each separate argument to pass to the hook's callback function.
  485. * Although not passed to a callback, these arguments are used to uniquely identify the
  486. * event, so they should be the same as those used when originally scheduling the event.
  487. * Default empty array.
  488. * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false.
  489. * @return int|false|WP_Error On success an integer indicating number of events unscheduled (0 indicates no
  490. * events were registered with the hook and arguments combination), false or WP_Error
  491. * if unscheduling one or more events fail.
  492. */
  493. function wp_clear_scheduled_hook( $hook, $args = array(), $wp_error = false ) {
  494. // Backward compatibility.
  495. // Previously, this function took the arguments as discrete vars rather than an array like the rest of the API.
  496. if ( ! is_array( $args ) ) {
  497. _deprecated_argument( __FUNCTION__, '3.0.0', __( 'This argument has changed to an array to match the behavior of the other cron functions.' ) );
  498. $args = array_slice( func_get_args(), 1 ); // phpcs:ignore PHPCompatibility.FunctionUse.ArgumentFunctionsReportCurrentValue.NeedsInspection
  499. $wp_error = false;
  500. }
  501. /**
  502. * Filter to preflight or hijack clearing a scheduled hook.
  503. *
  504. * Returning a non-null value will short-circuit the normal unscheduling
  505. * process, causing the function to return the filtered value instead.
  506. *
  507. * For plugins replacing wp-cron, return the number of events successfully
  508. * unscheduled (zero if no events were registered with the hook) or false
  509. * if unscheduling one or more events fails.
  510. *
  511. * @since 5.1.0
  512. * @since 5.7.0 The `$wp_error` parameter was added, and a `WP_Error` object can now be returned.
  513. *
  514. * @param null|int|false|WP_Error $pre Value to return instead. Default null to continue unscheduling the event.
  515. * @param string $hook Action hook, the execution of which will be unscheduled.
  516. * @param array $args Arguments to pass to the hook's callback function.
  517. * @param bool $wp_error Whether to return a WP_Error on failure.
  518. */
  519. $pre = apply_filters( 'pre_clear_scheduled_hook', null, $hook, $args, $wp_error );
  520. if ( null !== $pre ) {
  521. if ( $wp_error && false === $pre ) {
  522. return new WP_Error(
  523. 'pre_clear_scheduled_hook_false',
  524. __( 'A plugin prevented the hook from being cleared.' )
  525. );
  526. }
  527. if ( ! $wp_error && is_wp_error( $pre ) ) {
  528. return false;
  529. }
  530. return $pre;
  531. }
  532. /*
  533. * This logic duplicates wp_next_scheduled().
  534. * It's required due to a scenario where wp_unschedule_event() fails due to update_option() failing,
  535. * and, wp_next_scheduled() returns the same schedule in an infinite loop.
  536. */
  537. $crons = _get_cron_array();
  538. if ( empty( $crons ) ) {
  539. return 0;
  540. }
  541. $results = array();
  542. $key = md5( serialize( $args ) );
  543. foreach ( $crons as $timestamp => $cron ) {
  544. if ( isset( $cron[ $hook ][ $key ] ) ) {
  545. $results[] = wp_unschedule_event( $timestamp, $hook, $args, true );
  546. }
  547. }
  548. $errors = array_filter( $results, 'is_wp_error' );
  549. $error = new WP_Error();
  550. if ( $errors ) {
  551. if ( $wp_error ) {
  552. array_walk( $errors, array( $error, 'merge_from' ) );
  553. return $error;
  554. }
  555. return false;
  556. }
  557. return count( $results );
  558. }
  559. /**
  560. * Unschedules all events attached to the hook.
  561. *
  562. * Can be useful for plugins when deactivating to clean up the cron queue.
  563. *
  564. * Warning: This function may return Boolean FALSE, but may also return a non-Boolean
  565. * value which evaluates to FALSE. For information about casting to booleans see the
  566. * {@link https://www.php.net/manual/en/language.types.boolean.php PHP documentation}. Use
  567. * the `===` operator for testing the return value of this function.
  568. *
  569. * @since 4.9.0
  570. * @since 5.1.0 Return value added to indicate success or failure.
  571. * @since 5.7.0 The `$wp_error` parameter was added.
  572. *
  573. * @param string $hook Action hook, the execution of which will be unscheduled.
  574. * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false.
  575. * @return int|false|WP_Error On success an integer indicating number of events unscheduled (0 indicates no
  576. * events were registered on the hook), false or WP_Error if unscheduling fails.
  577. */
  578. function wp_unschedule_hook( $hook, $wp_error = false ) {
  579. /**
  580. * Filter to preflight or hijack clearing all events attached to the hook.
  581. *
  582. * Returning a non-null value will short-circuit the normal unscheduling
  583. * process, causing the function to return the filtered value instead.
  584. *
  585. * For plugins replacing wp-cron, return the number of events successfully
  586. * unscheduled (zero if no events were registered with the hook) or false
  587. * if unscheduling one or more events fails.
  588. *
  589. * @since 5.1.0
  590. * @since 5.7.0 The `$wp_error` parameter was added, and a `WP_Error` object can now be returned.
  591. *
  592. * @param null|int|false|WP_Error $pre Value to return instead. Default null to continue unscheduling the hook.
  593. * @param string $hook Action hook, the execution of which will be unscheduled.
  594. * @param bool $wp_error Whether to return a WP_Error on failure.
  595. */
  596. $pre = apply_filters( 'pre_unschedule_hook', null, $hook, $wp_error );
  597. if ( null !== $pre ) {
  598. if ( $wp_error && false === $pre ) {
  599. return new WP_Error(
  600. 'pre_unschedule_hook_false',
  601. __( 'A plugin prevented the hook from being cleared.' )
  602. );
  603. }
  604. if ( ! $wp_error && is_wp_error( $pre ) ) {
  605. return false;
  606. }
  607. return $pre;
  608. }
  609. $crons = _get_cron_array();
  610. if ( empty( $crons ) ) {
  611. return 0;
  612. }
  613. $results = array();
  614. foreach ( $crons as $timestamp => $args ) {
  615. if ( ! empty( $crons[ $timestamp ][ $hook ] ) ) {
  616. $results[] = count( $crons[ $timestamp ][ $hook ] );
  617. }
  618. unset( $crons[ $timestamp ][ $hook ] );
  619. if ( empty( $crons[ $timestamp ] ) ) {
  620. unset( $crons[ $timestamp ] );
  621. }
  622. }
  623. /*
  624. * If the results are empty (zero events to unschedule), no attempt
  625. * to update the cron array is required.
  626. */
  627. if ( empty( $results ) ) {
  628. return 0;
  629. }
  630. $set = _set_cron_array( $crons, $wp_error );
  631. if ( true === $set ) {
  632. return array_sum( $results );
  633. }
  634. return $set;
  635. }
  636. /**
  637. * Retrieve a scheduled event.
  638. *
  639. * Retrieve the full event object for a given event, if no timestamp is specified the next
  640. * scheduled event is returned.
  641. *
  642. * @since 5.1.0
  643. *
  644. * @param string $hook Action hook of the event.
  645. * @param array $args Optional. Array containing each separate argument to pass to the hook's callback function.
  646. * Although not passed to a callback, these arguments are used to uniquely identify the
  647. * event, so they should be the same as those used when originally scheduling the event.
  648. * Default empty array.
  649. * @param int|null $timestamp Optional. Unix timestamp (UTC) of the event. If not specified, the next scheduled event
  650. * is returned. Default null.
  651. * @return object|false The event object. False if the event does not exist.
  652. */
  653. function wp_get_scheduled_event( $hook, $args = array(), $timestamp = null ) {
  654. /**
  655. * Filter to preflight or hijack retrieving a scheduled event.
  656. *
  657. * Returning a non-null value will short-circuit the normal process,
  658. * returning the filtered value instead.
  659. *
  660. * Return false if the event does not exist, otherwise an event object
  661. * should be returned.
  662. *
  663. * @since 5.1.0
  664. *
  665. * @param null|false|object $pre Value to return instead. Default null to continue retrieving the event.
  666. * @param string $hook Action hook of the event.
  667. * @param array $args Array containing each separate argument to pass to the hook's callback function.
  668. * Although not passed to a callback, these arguments are used to uniquely identify
  669. * the event.
  670. * @param int|null $timestamp Unix timestamp (UTC) of the event. Null to retrieve next scheduled event.
  671. */
  672. $pre = apply_filters( 'pre_get_scheduled_event', null, $hook, $args, $timestamp );
  673. if ( null !== $pre ) {
  674. return $pre;
  675. }
  676. if ( null !== $timestamp && ! is_numeric( $timestamp ) ) {
  677. return false;
  678. }
  679. $crons = _get_cron_array();
  680. if ( empty( $crons ) ) {
  681. return false;
  682. }
  683. $key = md5( serialize( $args ) );
  684. if ( ! $timestamp ) {
  685. // Get next event.
  686. $next = false;
  687. foreach ( $crons as $timestamp => $cron ) {
  688. if ( isset( $cron[ $hook ][ $key ] ) ) {
  689. $next = $timestamp;
  690. break;
  691. }
  692. }
  693. if ( ! $next ) {
  694. return false;
  695. }
  696. $timestamp = $next;
  697. } elseif ( ! isset( $crons[ $timestamp ][ $hook ][ $key ] ) ) {
  698. return false;
  699. }
  700. $event = (object) array(
  701. 'hook' => $hook,
  702. 'timestamp' => $timestamp,
  703. 'schedule' => $crons[ $timestamp ][ $hook ][ $key ]['schedule'],
  704. 'args' => $args,
  705. );
  706. if ( isset( $crons[ $timestamp ][ $hook ][ $key ]['interval'] ) ) {
  707. $event->interval = $crons[ $timestamp ][ $hook ][ $key ]['interval'];
  708. }
  709. return $event;
  710. }
  711. /**
  712. * Retrieve the next timestamp for an event.
  713. *
  714. * @since 2.1.0
  715. *
  716. * @param string $hook Action hook of the event.
  717. * @param array $args Optional. Array containing each separate argument to pass to the hook's callback function.
  718. * Although not passed to a callback, these arguments are used to uniquely identify the
  719. * event, so they should be the same as those used when originally scheduling the event.
  720. * Default empty array.
  721. * @return int|false The Unix timestamp of the next time the event will occur. False if the event doesn't exist.
  722. */
  723. function wp_next_scheduled( $hook, $args = array() ) {
  724. $next_event = wp_get_scheduled_event( $hook, $args );
  725. if ( ! $next_event ) {
  726. return false;
  727. }
  728. return $next_event->timestamp;
  729. }
  730. /**
  731. * Sends a request to run cron through HTTP request that doesn't halt page loading.
  732. *
  733. * @since 2.1.0
  734. * @since 5.1.0 Return values added.
  735. *
  736. * @param int $gmt_time Optional. Unix timestamp (UTC). Default 0 (current time is used).
  737. * @return bool True if spawned, false if no events spawned.
  738. */
  739. function spawn_cron( $gmt_time = 0 ) {
  740. if ( ! $gmt_time ) {
  741. $gmt_time = microtime( true );
  742. }
  743. if ( defined( 'DOING_CRON' ) || isset( $_GET['doing_wp_cron'] ) ) {
  744. return false;
  745. }
  746. /*
  747. * Get the cron lock, which is a Unix timestamp of when the last cron was spawned
  748. * and has not finished running.
  749. *
  750. * Multiple processes on multiple web servers can run this code concurrently,
  751. * this lock attempts to make spawning as atomic as possible.
  752. */
  753. $lock = get_transient( 'doing_cron' );
  754. if ( $lock > $gmt_time + 10 * MINUTE_IN_SECONDS ) {
  755. $lock = 0;
  756. }
  757. // Don't run if another process is currently running it or more than once every 60 sec.
  758. if ( $lock + WP_CRON_LOCK_TIMEOUT > $gmt_time ) {
  759. return false;
  760. }
  761. // Sanity check.
  762. $crons = wp_get_ready_cron_jobs();
  763. if ( empty( $crons ) ) {
  764. return false;
  765. }
  766. $keys = array_keys( $crons );
  767. if ( isset( $keys[0] ) && $keys[0] > $gmt_time ) {
  768. return false;
  769. }
  770. if ( defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON ) {
  771. if ( 'GET' !== $_SERVER['REQUEST_METHOD'] || defined( 'DOING_AJAX' ) || defined( 'XMLRPC_REQUEST' ) ) {
  772. return false;
  773. }
  774. $doing_wp_cron = sprintf( '%.22F', $gmt_time );
  775. set_transient( 'doing_cron', $doing_wp_cron );
  776. ob_start();
  777. wp_redirect( add_query_arg( 'doing_wp_cron', $doing_wp_cron, wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
  778. echo ' ';
  779. // Flush any buffers and send the headers.
  780. wp_ob_end_flush_all();
  781. flush();
  782. include_once ABSPATH . 'wp-cron.php';
  783. return true;
  784. }
  785. // Set the cron lock with the current unix timestamp, when the cron is being spawned.
  786. $doing_wp_cron = sprintf( '%.22F', $gmt_time );
  787. set_transient( 'doing_cron', $doing_wp_cron );
  788. /**
  789. * Filters the cron request arguments.
  790. *
  791. * @since 3.5.0
  792. * @since 4.5.0 The `$doing_wp_cron` parameter was added.
  793. *
  794. * @param array $cron_request_array {
  795. * An array of cron request URL arguments.
  796. *
  797. * @type string $url The cron request URL.
  798. * @type int $key The 22 digit GMT microtime.
  799. * @type array $args {
  800. * An array of cron request arguments.
  801. *
  802. * @type int $timeout The request timeout in seconds. Default .01 seconds.
  803. * @type bool $blocking Whether to set blocking for the request. Default false.
  804. * @type bool $sslverify Whether SSL should be verified for the request. Default false.
  805. * }
  806. * }
  807. * @param string $doing_wp_cron The unix timestamp of the cron lock.
  808. */
  809. $cron_request = apply_filters(
  810. 'cron_request',
  811. array(
  812. 'url' => add_query_arg( 'doing_wp_cron', $doing_wp_cron, site_url( 'wp-cron.php' ) ),
  813. 'key' => $doing_wp_cron,
  814. 'args' => array(
  815. 'timeout' => 0.01,
  816. 'blocking' => false,
  817. /** This filter is documented in wp-includes/class-wp-http-streams.php */
  818. 'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
  819. ),
  820. ),
  821. $doing_wp_cron
  822. );
  823. $result = wp_remote_post( $cron_request['url'], $cron_request['args'] );
  824. return ! is_wp_error( $result );
  825. }
  826. /**
  827. * Register _wp_cron() to run on the {@see 'wp_loaded'} action.
  828. *
  829. * If the {@see 'wp_loaded'} action has already fired, this function calls
  830. * _wp_cron() directly.
  831. *
  832. * Warning: This function may return Boolean FALSE, but may also return a non-Boolean
  833. * value which evaluates to FALSE. For information about casting to booleans see the
  834. * {@link https://www.php.net/manual/en/language.types.boolean.php PHP documentation}. Use
  835. * the `===` operator for testing the return value of this function.
  836. *
  837. * @since 2.1.0
  838. * @since 5.1.0 Return value added to indicate success or failure.
  839. * @since 5.7.0 Functionality moved to _wp_cron() to which this becomes a wrapper.
  840. *
  841. * @return bool|int|void On success an integer indicating number of events spawned (0 indicates no
  842. * events needed to be spawned), false if spawning fails for one or more events or
  843. * void if the function registered _wp_cron() to run on the action.
  844. */
  845. function wp_cron() {
  846. if ( did_action( 'wp_loaded' ) ) {
  847. return _wp_cron();
  848. }
  849. add_action( 'wp_loaded', '_wp_cron', 20 );
  850. }
  851. /**
  852. * Run scheduled callbacks or spawn cron for all scheduled events.
  853. *
  854. * Warning: This function may return Boolean FALSE, but may also return a non-Boolean
  855. * value which evaluates to FALSE. For information about casting to booleans see the
  856. * {@link https://www.php.net/manual/en/language.types.boolean.php PHP documentation}. Use
  857. * the `===` operator for testing the return value of this function.
  858. *
  859. * @since 5.7.0
  860. * @access private
  861. *
  862. * @return int|false On success an integer indicating number of events spawned (0 indicates no
  863. * events needed to be spawned), false if spawning fails for one or more events.
  864. */
  865. function _wp_cron() {
  866. // Prevent infinite loops caused by lack of wp-cron.php.
  867. if ( strpos( $_SERVER['REQUEST_URI'], '/wp-cron.php' ) !== false || ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) ) {
  868. return 0;
  869. }
  870. $crons = wp_get_ready_cron_jobs();
  871. if ( empty( $crons ) ) {
  872. return 0;
  873. }
  874. $gmt_time = microtime( true );
  875. $keys = array_keys( $crons );
  876. if ( isset( $keys[0] ) && $keys[0] > $gmt_time ) {
  877. return 0;
  878. }
  879. $schedules = wp_get_schedules();
  880. $results = array();
  881. foreach ( $crons as $timestamp => $cronhooks ) {
  882. if ( $timestamp > $gmt_time ) {
  883. break;
  884. }
  885. foreach ( (array) $cronhooks as $hook => $args ) {
  886. if ( isset( $schedules[ $hook ]['callback'] ) && ! call_user_func( $schedules[ $hook ]['callback'] ) ) {
  887. continue;
  888. }
  889. $results[] = spawn_cron( $gmt_time );
  890. break 2;
  891. }
  892. }
  893. if ( in_array( false, $results, true ) ) {
  894. return false;
  895. }
  896. return count( $results );
  897. }
  898. /**
  899. * Retrieve supported event recurrence schedules.
  900. *
  901. * The default supported recurrences are 'hourly', 'twicedaily', 'daily', and 'weekly'.
  902. * A plugin may add more by hooking into the {@see 'cron_schedules'} filter.
  903. * The filter accepts an array of arrays. The outer array has a key that is the name
  904. * of the schedule, for example 'monthly'. The value is an array with two keys,
  905. * one is 'interval' and the other is 'display'.
  906. *
  907. * The 'interval' is a number in seconds of when the cron job should run.
  908. * So for 'hourly' the time is `HOUR_IN_SECONDS` (60 * 60 or 3600). For 'monthly',
  909. * the value would be `MONTH_IN_SECONDS` (30 * 24 * 60 * 60 or 2592000).
  910. *
  911. * The 'display' is the description. For the 'monthly' key, the 'display'
  912. * would be `__( 'Once Monthly' )`.
  913. *
  914. * For your plugin, you will be passed an array. You can easily add your
  915. * schedule by doing the following.
  916. *
  917. * // Filter parameter variable name is 'array'.
  918. * $array['monthly'] = array(
  919. * 'interval' => MONTH_IN_SECONDS,
  920. * 'display' => __( 'Once Monthly' )
  921. * );
  922. *
  923. * @since 2.1.0
  924. * @since 5.4.0 The 'weekly' schedule was added.
  925. *
  926. * @return array[]
  927. */
  928. function wp_get_schedules() {
  929. $schedules = array(
  930. 'hourly' => array(
  931. 'interval' => HOUR_IN_SECONDS,
  932. 'display' => __( 'Once Hourly' ),
  933. ),
  934. 'twicedaily' => array(
  935. 'interval' => 12 * HOUR_IN_SECONDS,
  936. 'display' => __( 'Twice Daily' ),
  937. ),
  938. 'daily' => array(
  939. 'interval' => DAY_IN_SECONDS,
  940. 'display' => __( 'Once Daily' ),
  941. ),
  942. 'weekly' => array(
  943. 'interval' => WEEK_IN_SECONDS,
  944. 'display' => __( 'Once Weekly' ),
  945. ),
  946. );
  947. /**
  948. * Filters the non-default cron schedules.
  949. *
  950. * @since 2.1.0
  951. *
  952. * @param array[] $new_schedules An array of non-default cron schedule arrays. Default empty.
  953. */
  954. return array_merge( apply_filters( 'cron_schedules', array() ), $schedules );
  955. }
  956. /**
  957. * Retrieve the recurrence schedule for an event.
  958. *
  959. * @see wp_get_schedules() for available schedules.
  960. *
  961. * @since 2.1.0
  962. * @since 5.1.0 {@see 'get_schedule'} filter added.
  963. *
  964. * @param string $hook Action hook to identify the event.
  965. * @param array $args Optional. Arguments passed to the event's callback function.
  966. * Default empty array.
  967. * @return string|false Schedule name on success, false if no schedule.
  968. */
  969. function wp_get_schedule( $hook, $args = array() ) {
  970. $schedule = false;
  971. $event = wp_get_scheduled_event( $hook, $args );
  972. if ( $event ) {
  973. $schedule = $event->schedule;
  974. }
  975. /**
  976. * Filters the schedule for a hook.
  977. *
  978. * @since 5.1.0
  979. *
  980. * @param string|false $schedule Schedule for the hook. False if not found.
  981. * @param string $hook Action hook to execute when cron is run.
  982. * @param array $args Arguments to pass to the hook's callback function.
  983. */
  984. return apply_filters( 'get_schedule', $schedule, $hook, $args );
  985. }
  986. /**
  987. * Retrieve cron jobs ready to be run.
  988. *
  989. * Returns the results of _get_cron_array() limited to events ready to be run,
  990. * ie, with a timestamp in the past.
  991. *
  992. * @since 5.1.0
  993. *
  994. * @return array[] Array of cron job arrays ready to be run.
  995. */
  996. function wp_get_ready_cron_jobs() {
  997. /**
  998. * Filter to preflight or hijack retrieving ready cron jobs.
  999. *
  1000. * Returning an array will short-circuit the normal retrieval of ready
  1001. * cron jobs, causing the function to return the filtered value instead.
  1002. *
  1003. * @since 5.1.0
  1004. *
  1005. * @param null|array[] $pre Array of ready cron tasks to return instead. Default null
  1006. * to continue using results from _get_cron_array().
  1007. */
  1008. $pre = apply_filters( 'pre_get_ready_cron_jobs', null );
  1009. if ( null !== $pre ) {
  1010. return $pre;
  1011. }
  1012. $crons = _get_cron_array();
  1013. if ( ! is_array( $crons ) ) {
  1014. return array();
  1015. }
  1016. $gmt_time = microtime( true );
  1017. $keys = array_keys( $crons );
  1018. if ( isset( $keys[0] ) && $keys[0] > $gmt_time ) {
  1019. return array();
  1020. }
  1021. $results = array();
  1022. foreach ( $crons as $timestamp => $cronhooks ) {
  1023. if ( $timestamp > $gmt_time ) {
  1024. break;
  1025. }
  1026. $results[ $timestamp ] = $cronhooks;
  1027. }
  1028. return $results;
  1029. }
  1030. //
  1031. // Private functions.
  1032. //
  1033. /**
  1034. * Retrieve cron info array option.
  1035. *
  1036. * @since 2.1.0
  1037. * @access private
  1038. *
  1039. * @return array[]|false Array of cron info arrays on success, false on failure.
  1040. */
  1041. function _get_cron_array() {
  1042. $cron = get_option( 'cron' );
  1043. if ( ! is_array( $cron ) ) {
  1044. return false;
  1045. }
  1046. if ( ! isset( $cron['version'] ) ) {
  1047. $cron = _upgrade_cron_array( $cron );
  1048. }
  1049. unset( $cron['version'] );
  1050. return $cron;
  1051. }
  1052. /**
  1053. * Updates the cron option with the new cron array.
  1054. *
  1055. * @since 2.1.0
  1056. * @since 5.1.0 Return value modified to outcome of update_option().
  1057. * @since 5.7.0 The `$wp_error` parameter was added.
  1058. *
  1059. * @access private
  1060. *
  1061. * @param array[] $cron Array of cron info arrays from _get_cron_array().
  1062. * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false.
  1063. * @return bool|WP_Error True if cron array updated. False or WP_Error on failure.
  1064. */
  1065. function _set_cron_array( $cron, $wp_error = false ) {
  1066. if ( ! is_array( $cron ) ) {
  1067. $cron = array();
  1068. }
  1069. $cron['version'] = 2;
  1070. $result = update_option( 'cron', $cron );
  1071. if ( $wp_error && ! $result ) {
  1072. return new WP_Error(
  1073. 'could_not_set',
  1074. __( 'The cron event list could not be saved.' )
  1075. );
  1076. }
  1077. return $result;
  1078. }
  1079. /**
  1080. * Upgrade a Cron info array.
  1081. *
  1082. * This function upgrades the Cron info array to version 2.
  1083. *
  1084. * @since 2.1.0
  1085. * @access private
  1086. *
  1087. * @param array $cron Cron info array from _get_cron_array().
  1088. * @return array An upgraded Cron info array.
  1089. */
  1090. function _upgrade_cron_array( $cron ) {
  1091. if ( isset( $cron['version'] ) && 2 == $cron['version'] ) {
  1092. return $cron;
  1093. }
  1094. $new_cron = array();
  1095. foreach ( (array) $cron as $timestamp => $hooks ) {
  1096. foreach ( (array) $hooks as $hook => $args ) {
  1097. $key = md5( serialize( $args['args'] ) );
  1098. $new_cron[ $timestamp ][ $hook ][ $key ] = $args;
  1099. }
  1100. }
  1101. $new_cron['version'] = 2;
  1102. update_option( 'cron', $new_cron );
  1103. return $new_cron;
  1104. }