Sin descripción

cron.php 40KB

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