cron.php 32 KB

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