cron.php 39 KB

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