This commit is contained in:
Javier Casares 2026-08-24 12:10:32 +00:00
commit a558ac478c
111 changed files with 17935 additions and 56 deletions

View file

@ -1,5 +1,32 @@
== Changelog == == Changelog ==
= 1.9.0 =
_Release date: 2026-08-24_
**Highlights**
* Action Scheduler is now bundled via Composer (`woocommerce/action-scheduler` 3.9.3): the external `action-scheduler` plugin is no longer required.
**Added**
* Bundled Action Scheduler library (production Composer dependency), loaded from the main plugin file and guarded so a standalone Action Scheduler plugin that loads first is respected. The library self-arbitrates when multiple plugins ship their own copy: only the newest registered version initializes.
* Header test `test_no_external_plugin_dependency` asserting the `Requires Plugins` header is gone, the main plugin file requires the bundled library, and composer.json declares it as a production dependency.
**Changed**
* `Requires Plugins: action-scheduler` removed from the plugin header and readme.txt; the plugin now works standalone.
**Compatibility**
* WordPress: 5.3 - 7.1
* PHP: 8.0 - 8.5
* WP-CLI: 2.x
**Tests**
* PHPUnit: 12 tests, 55 assertions
= 1.8.3 = = 1.8.3 =
_Release date: 2026-08-17_ _Release date: 2026-08-17_

View file

@ -14,9 +14,10 @@ if ( ! defined( 'ABSPATH' ) ) {
/** /**
* Thin wrapper around Action Scheduler that namespaces all jobs under a single group. * Thin wrapper around Action Scheduler that namespaces all jobs under a single group.
* *
* Action Scheduler is declared as a required plugin (Requires Plugins: action-scheduler) * Action Scheduler is bundled via Composer (woocommerce/action-scheduler) and
* so its functions are always available at runtime. The is_available() guard is kept * loaded from the main plugin file, so its functions are always available at
* for defensive unit-test scenarios only. * runtime. The is_available() guard is kept for defensive unit-test scenarios
* only.
*/ */
class Scheduler { class Scheduler {
@ -31,7 +32,9 @@ class Scheduler {
* @return bool * @return bool
*/ */
public static function is_available(): bool { public static function is_available(): bool {
return function_exists( 'as_schedule_single_action' ); return function_exists( 'as_schedule_single_action' )
&& function_exists( 'as_has_scheduled_action' )
&& function_exists( 'as_unschedule_all_actions' );
} }
/** /**

View file

@ -4,9 +4,8 @@ Tags: media, copyright, images, reverse image search, media library
Requires at least: 5.3 Requires at least: 5.3
Tested up to: 7.1 Tested up to: 7.1
Requires PHP: 8.0 Requires PHP: 8.0
Requires Plugins: action-scheduler Stable tag: 1.9.0
Stable tag: 1.8.3 Version: 1.9.0
Version: 1.8.3
License: GPL-3.0-or-later License: GPL-3.0-or-later
License URI: https://www.gnu.org/licenses/gpl-3.0.txt License URI: https://www.gnu.org/licenses/gpl-3.0.txt
@ -25,11 +24,10 @@ Media Audit helps site owners and editors understand where their media files are
* **Alert management** — dedicated Alerts page to review active copyright-risk alerts and dismiss false positives with optional notes. Dismissed alerts are tracked separately and can be reactivated at any time. * **Alert management** — dedicated Alerts page to review active copyright-risk alerts and dismiss false positives with optional notes. Dismissed alerts are tracked separately and can be reactivated at any time.
* **WP-CLI support** — run or schedule scans from the command line. * **WP-CLI support** — run or schedule scans from the command line.
* **GDPR compliance** — full WordPress privacy API integration for personal data export and erasure on request. * **GDPR compliance** — full WordPress privacy API integration for personal data export and erasure on request.
* **Async processing** — all scanning runs via Action Scheduler to avoid blocking web requests. * **Async processing** — all scanning runs via the bundled Action Scheduler library to avoid blocking web requests (no extra plugin needed).
= Requirements = = Requirements =
* [Action Scheduler](https://actionscheduler.org/) plugin (declared as a required dependency).
* [Manager (by ROBOTSTXT)](https://www.robotstxt.software/plugins/robotstxt-manager/) plugin (recommended) — required to receive plugin updates. * [Manager (by ROBOTSTXT)](https://www.robotstxt.software/plugins/robotstxt-manager/) plugin (recommended) — required to receive plugin updates.
* Google Cloud Vision API key (for Web Detection scanning). * Google Cloud Vision API key (for Web Detection scanning).
* TinEye Commercial API key (for reverse image search). * TinEye Commercial API key (for reverse image search).
@ -95,12 +93,16 @@ By default, no. Enable **Settings → Delete data on uninstall** if you want all
* WordPress: 5.3 - 7.1 * WordPress: 5.3 - 7.1
* PHP: 8.0 - 8.5 * PHP: 8.0 - 8.5
* WP-CLI: 2.x * WP-CLI: 2.x
* Requires Plugins: action-scheduler
== Changelog == == Changelog ==
Only the 3 latest versions. The full changelog is at [www.robotstxt.software/plugins/robotstxt-mediaaudit/](https://www.robotstxt.software/plugins/robotstxt-mediaaudit/). Only the 3 latest versions. The full changelog is at [www.robotstxt.software/plugins/robotstxt-mediaaudit/](https://www.robotstxt.software/plugins/robotstxt-mediaaudit/).
= 1.9.0 =
* Action Scheduler is now bundled via Composer (`woocommerce/action-scheduler`): the external `action-scheduler` plugin is no longer required.
* The library self-arbitrates when another plugin (e.g. WooCommerce) loads its own copy — only the newest version initializes.
= 1.8.3 = = 1.8.3 =
* Updates are now delivered through [Manager (by ROBOTSTXT)](https://www.robotstxt.software/plugins/robotstxt-manager/): the bundled self-updater (`robotstxt-updater.php`, `update.json`) was removed. * Updates are now delivered through [Manager (by ROBOTSTXT)](https://www.robotstxt.software/plugins/robotstxt-manager/): the bundled self-updater (`robotstxt-updater.php`, `update.json`) was removed.
@ -116,12 +118,6 @@ Only the 3 latest versions. The full changelog is at [www.robotstxt.software/plu
* Added `.claude/agents/security-auditor.md` and `.claude/commands/deploy-check.md` for clean-context pre-deploy audits. * Added `.claude/agents/security-auditor.md` and `.claude/commands/deploy-check.md` for clean-context pre-deploy audits.
* Fixed `bin/deploy.sh` excluding all `AGENTS-*.md` dev docs from the release ZIP (previously only `AGENTS.md`). * Fixed `bin/deploy.sh` excluding all `AGENTS-*.md` dev docs from the release ZIP (previously only `AGENTS.md`).
= 1.8.1 =
* Network Operations buttons now use standard HTML POST Forms with server-side redirect (PRG pattern), replacing the AJAX approach that failed due to network admin script-loading constraints.
* Removed unreliable in-render script enqueueing for Network Tools page; operation buttons now work without JavaScript.
* JS dismiss/cancel labels on the Alerts page now use i18n strings from `wp_localize_script`.
= Previous versions = = Previous versions =
If you want to see the full changelog, visit [www.robotstxt.software/plugins/robotstxt-mediaaudit/](https://www.robotstxt.software/plugins/robotstxt-mediaaudit/). If you want to see the full changelog, visit [www.robotstxt.software/plugins/robotstxt-mediaaudit/](https://www.robotstxt.software/plugins/robotstxt-mediaaudit/).

View file

@ -3,11 +3,10 @@
* Plugin Name: Media Audit (by ROBOTSTXT) * Plugin Name: Media Audit (by ROBOTSTXT)
* Plugin URI: https://www.robotstxt.software/plugins/robotstxt-mediaaudit/ * Plugin URI: https://www.robotstxt.software/plugins/robotstxt-mediaaudit/
* Description: Internal media library usage auditing and external reverse image search to detect potential copyright issues. * Description: Internal media library usage auditing and external reverse image search to detect potential copyright issues.
* Version: 1.8.3 * Version: 1.9.0
* Requires at least: 5.3 * Requires at least: 5.3
* Tested up to: 7.1 * Tested up to: 7.1
* Requires PHP: 8.0 * Requires PHP: 8.0
* Requires Plugins: action-scheduler
* Update URI: https://www.robotstxt.software/plugins/robotstxt-mediaaudit/ * Update URI: https://www.robotstxt.software/plugins/robotstxt-mediaaudit/
* Network: true * Network: true
* Author: ROBOTSTXT * Author: ROBOTSTXT
@ -25,7 +24,7 @@ if ( ! defined( 'ABSPATH' ) ) {
exit; exit;
} }
define( 'ROBOTSTXT_MEDIAAUDIT_VERSION', '1.8.3' ); define( 'ROBOTSTXT_MEDIAAUDIT_VERSION', '1.9.0' );
define( 'ROBOTSTXT_MEDIAAUDIT_DB_VERSION', '1.3.0' ); define( 'ROBOTSTXT_MEDIAAUDIT_DB_VERSION', '1.3.0' );
define( 'ROBOTSTXT_MEDIAAUDIT_PLUGIN_FILE', __FILE__ ); define( 'ROBOTSTXT_MEDIAAUDIT_PLUGIN_FILE', __FILE__ );
define( 'ROBOTSTXT_MEDIAAUDIT_PLUGIN_DIR', plugin_dir_path( __FILE__ ) ); define( 'ROBOTSTXT_MEDIAAUDIT_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
@ -33,6 +32,15 @@ define( 'ROBOTSTXT_MEDIAAUDIT_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
require_once ROBOTSTXT_MEDIAAUDIT_PLUGIN_DIR . 'vendor/autoload.php'; require_once ROBOTSTXT_MEDIAAUDIT_PLUGIN_DIR . 'vendor/autoload.php';
/*
* Action Scheduler is bundled via Composer (woocommerce/action-scheduler).
* The require is unconditional by design: the library self-arbitrates when
* other plugins load their own copy — every host registers its version and
* only the newest registered version initializes. All files are guarded
* against double loading.
*/
require_once ROBOTSTXT_MEDIAAUDIT_PLUGIN_DIR . 'vendor/woocommerce/action-scheduler/action-scheduler.php';
use MediaRightsAudit\Core\Activator; use MediaRightsAudit\Core\Activator;
use MediaRightsAudit\Core\Deactivator; use MediaRightsAudit\Core\Deactivator;
use MediaRightsAudit\Core\NetworkActivator; use MediaRightsAudit\Core\NetworkActivator;

View file

@ -1,27 +0,0 @@
{
"name": "Media Audit (by ROBOTSTXT)",
"slug": "robotstxt-mediaaudit",
"version": "1.8.8",
"download_url": "https://git.robotstxt.es/ROBOTSTXT/robotstxt-mediaaudit/releases/download/1.8.3/robotstxt-mediaaudit-1.8.3.zip",
"requires": "5.3",
"requires_php": "8.0",
"tested": "7.1",
"last_updated": "2026-08-08",
"author": "ROBOTSTXT",
"author_profile": "https://www.robotstxt.es/",
"homepage": "https://git.robotstxt.es/ROBOTSTXT/robotstxt-mediaaudit",
"description": "Audit your media library for copyright risks: track internal usage, run reverse image search via Google Vision, TinEye, and PicDefense, and classify results against configurable alert and ignored hostname lists.",
"changelog": "",
"sections": {
"description": "Audit your media library for copyright risks: track internal usage, run reverse image search via Google Vision, TinEye, and PicDefense, and classify results against configurable alert and ignored hostname lists.",
"changelog": ""
},
"banners": {
"low": "",
"high": ""
},
"icons": {
"1x": "",
"2x": ""
}
}

2
vendor/autoload.php vendored
View file

@ -19,4 +19,4 @@ if (PHP_VERSION_ID < 50600) {
require_once __DIR__ . '/composer/autoload_real.php'; require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit149e6f8eeaef8d46113f09e1e8d4e757::getLoader(); return ComposerAutoloaderInite5e52722a3dd923332bc7708a6f4efbf::getLoader();

View file

@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer // autoload_real.php @generated by Composer
class ComposerAutoloaderInit149e6f8eeaef8d46113f09e1e8d4e757 class ComposerAutoloaderInite5e52722a3dd923332bc7708a6f4efbf
{ {
private static $loader; private static $loader;
@ -24,12 +24,12 @@ class ComposerAutoloaderInit149e6f8eeaef8d46113f09e1e8d4e757
require __DIR__ . '/platform_check.php'; require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInit149e6f8eeaef8d46113f09e1e8d4e757', 'loadClassLoader'), true, true); spl_autoload_register(array('ComposerAutoloaderInite5e52722a3dd923332bc7708a6f4efbf', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__)); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInit149e6f8eeaef8d46113f09e1e8d4e757', 'loadClassLoader')); spl_autoload_unregister(array('ComposerAutoloaderInite5e52722a3dd923332bc7708a6f4efbf', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php'; require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit149e6f8eeaef8d46113f09e1e8d4e757::getInitializer($loader)); call_user_func(\Composer\Autoload\ComposerStaticInite5e52722a3dd923332bc7708a6f4efbf::getInitializer($loader));
$loader->register(true); $loader->register(true);

View file

@ -4,7 +4,7 @@
namespace Composer\Autoload; namespace Composer\Autoload;
class ComposerStaticInit149e6f8eeaef8d46113f09e1e8d4e757 class ComposerStaticInite5e52722a3dd923332bc7708a6f4efbf
{ {
public static $prefixLengthsPsr4 = array ( public static $prefixLengthsPsr4 = array (
'M' => 'M' =>
@ -60,9 +60,9 @@ class ComposerStaticInit149e6f8eeaef8d46113f09e1e8d4e757
public static function getInitializer(ClassLoader $loader) public static function getInitializer(ClassLoader $loader)
{ {
return \Closure::bind(function () use ($loader) { return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit149e6f8eeaef8d46113f09e1e8d4e757::$prefixLengthsPsr4; $loader->prefixLengthsPsr4 = ComposerStaticInite5e52722a3dd923332bc7708a6f4efbf::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit149e6f8eeaef8d46113f09e1e8d4e757::$prefixDirsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInite5e52722a3dd923332bc7708a6f4efbf::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit149e6f8eeaef8d46113f09e1e8d4e757::$classMap; $loader->classMap = ComposerStaticInite5e52722a3dd923332bc7708a6f4efbf::$classMap;
}, null, ClassLoader::class); }, null, ClassLoader::class);
} }

View file

@ -1,5 +1,52 @@
{ {
"packages": [], "packages": [
{
"name": "woocommerce/action-scheduler",
"version": "3.9.3",
"version_normalized": "3.9.3.0",
"source": {
"type": "git",
"url": "https://github.com/woocommerce/action-scheduler.git",
"reference": "c58cdbab17651303d406cd3b22cf9d75c71c986c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/woocommerce/action-scheduler/zipball/c58cdbab17651303d406cd3b22cf9d75c71c986c",
"reference": "c58cdbab17651303d406cd3b22cf9d75c71c986c",
"shasum": ""
},
"require": {
"php": ">=7.2"
},
"require-dev": {
"phpunit/phpunit": "^8.5",
"woocommerce/woocommerce-sniffs": "0.1.0",
"wp-cli/wp-cli": "~2.5.0",
"yoast/phpunit-polyfills": "^2.0"
},
"time": "2025-07-15T09:32:30+00:00",
"type": "wordpress-plugin",
"extra": {
"scripts-description": {
"test": "Run unit tests",
"phpcs": "Analyze code against the WordPress coding standards with PHP_CodeSniffer",
"phpcbf": "Fix coding standards warnings/errors automatically with PHP Code Beautifier"
}
},
"installation-source": "dist",
"notification-url": "https://packagist.org/downloads/",
"license": [
"GPL-3.0-or-later"
],
"description": "Action Scheduler for WordPress and WooCommerce",
"homepage": "https://actionscheduler.org/",
"support": {
"issues": "https://github.com/woocommerce/action-scheduler/issues",
"source": "https://github.com/woocommerce/action-scheduler/tree/3.9.3"
},
"install-path": "../woocommerce/action-scheduler"
}
],
"dev": false, "dev": false,
"dev-package-names": [] "dev-package-names": []
} }

View file

@ -19,5 +19,14 @@
'aliases' => array(), 'aliases' => array(),
'dev_requirement' => false, 'dev_requirement' => false,
), ),
'woocommerce/action-scheduler' => array(
'pretty_version' => '3.9.3',
'version' => '3.9.3.0',
'reference' => 'c58cdbab17651303d406cd3b22cf9d75c71c986c',
'type' => 'wordpress-plugin',
'install_path' => __DIR__ . '/../woocommerce/action-scheduler',
'aliases' => array(),
'dev_requirement' => false,
),
), ),
); );

View file

@ -0,0 +1,35 @@
# Action Scheduler - Job Queue for WordPress [![Build Status](https://travis-ci.org/woocommerce/action-scheduler.png?branch=master)](https://travis-ci.org/woocommerce/action-scheduler) [![codecov](https://codecov.io/gh/woocommerce/action-scheduler/branch/master/graph/badge.svg)](https://codecov.io/gh/woocommerce/action-scheduler)
Action Scheduler is a scalable, traceable job queue for background processing large sets of actions in WordPress. It's specially designed to be distributed in WordPress plugins.
Action Scheduler works by triggering an action hook to run at some time in the future. Each hook can be scheduled with unique data, to allow callbacks to perform operations on that data. The hook can also be scheduled to run on one or more occasions.
Think of it like an extension to `do_action()` which adds the ability to delay and repeat a hook.
## Battle-Tested Background Processing
Every month, Action Scheduler processes millions of payments for [Subscriptions](https://woocommerce.com/products/woocommerce-subscriptions/), webhooks for [WooCommerce](https://wordpress.org/plugins/woocommerce/), as well as emails and other events for a range of other plugins.
It's been seen on live sites processing queues in excess of 50,000 jobs and doing resource intensive operations, like processing payments and creating orders, at a sustained rate of over 10,000 / hour without negatively impacting normal site operations.
This is all on infrastructure and WordPress sites outside the control of the plugin author.
If your plugin needs background processing, especially of large sets of tasks, Action Scheduler can help.
## Learn More
To learn more about how to Action Scheduler works, and how to use it in your plugin, check out the docs on [ActionScheduler.org](https://actionscheduler.org).
There you will find:
* [Usage guide](https://actionscheduler.org/usage/): instructions on installing and using Action Scheduler
* [WP CLI guide](https://actionscheduler.org/wp-cli/): instructions on running Action Scheduler at scale via WP CLI
* [API Reference](https://actionscheduler.org/api/): complete reference guide for all API functions
* [Administration Guide](https://actionscheduler.org/admin/): guide to managing scheduled actions via the administration screen
* [Guide to Background Processing at Scale](https://actionscheduler.org/perf/): instructions for running Action Scheduler at scale via the default WP Cron queue runner
## Credits
Action Scheduler is developed and maintained by [Automattic](http://automattic.com/) with significant early development completed by [Flightless](https://flightless.us/).
Collaboration is cool. We'd love to work with you to improve Action Scheduler. [Pull Requests](https://github.com/woocommerce/action-scheduler/pulls) welcome.

View file

@ -0,0 +1,70 @@
<?php
/**
* Plugin Name: Action Scheduler
* Plugin URI: https://actionscheduler.org
* Description: A robust scheduling library for use in WordPress plugins.
* Author: Automattic
* Author URI: https://automattic.com/
* Version: 3.9.3
* License: GPLv3
* Requires at least: 6.5
* Tested up to: 6.8
* Requires PHP: 7.2
*
* Copyright 2019 Automattic, Inc. (https://automattic.com/contact/)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* @package ActionScheduler
*/
if ( ! function_exists( 'action_scheduler_register_3_dot_9_dot_3' ) && function_exists( 'add_action' ) ) { // WRCS: DEFINED_VERSION.
if ( ! class_exists( 'ActionScheduler_Versions', false ) ) {
require_once __DIR__ . '/classes/ActionScheduler_Versions.php';
add_action( 'plugins_loaded', array( 'ActionScheduler_Versions', 'initialize_latest_version' ), 1, 0 );
}
add_action( 'plugins_loaded', 'action_scheduler_register_3_dot_9_dot_3', 0, 0 ); // WRCS: DEFINED_VERSION.
// phpcs:disable Generic.Functions.OpeningFunctionBraceKernighanRitchie.ContentAfterBrace
/**
* Registers this version of Action Scheduler.
*/
function action_scheduler_register_3_dot_9_dot_3() { // WRCS: DEFINED_VERSION.
$versions = ActionScheduler_Versions::instance();
$versions->register( '3.9.3', 'action_scheduler_initialize_3_dot_9_dot_3' ); // WRCS: DEFINED_VERSION.
}
// phpcs:disable Generic.Functions.OpeningFunctionBraceKernighanRitchie.ContentAfterBrace
/**
* Initializes this version of Action Scheduler.
*/
function action_scheduler_initialize_3_dot_9_dot_3() { // WRCS: DEFINED_VERSION.
// A final safety check is required even here, because historic versions of Action Scheduler
// followed a different pattern (in some unusual cases, we could reach this point and the
// ActionScheduler class is already defined—so we need to guard against that).
if ( ! class_exists( 'ActionScheduler', false ) ) {
require_once __DIR__ . '/classes/abstracts/ActionScheduler.php';
ActionScheduler::init( __FILE__ );
}
}
// Support usage in themes - load this version if no plugin has loaded a version yet.
if ( did_action( 'plugins_loaded' ) && ! doing_action( 'plugins_loaded' ) && ! class_exists( 'ActionScheduler', false ) ) {
action_scheduler_initialize_3_dot_9_dot_3(); // WRCS: DEFINED_VERSION.
do_action( 'action_scheduler_pre_theme_init' );
ActionScheduler_Versions::initialize_latest_version();
}
}

View file

@ -0,0 +1,200 @@
*** Changelog ***
= 3.9.3 - 2025-07-15 =
* Add hook 'action_scheduler_ensure_recurring_actions' specifically for scheduling recurring actions.
* Assume an action is valid until proven otherwise.
* Implement SKIP LOCKED during action claiming.
* Import `get_flag_value()` from `WP_CLI\Utils` before using.
* Make `$unique` available to all pre-creation/short-circuit hooks.
* Make version/source information available via new class.
* Only release claims on pending actions.
* Tweak - WP 6.8 compatibility.
* Update minimum supported php and phpunit versions.
* Update readme.txt.
* WP CLI get action command: correct parentheses/nesting of conditional checks.
= 3.9.2 - 2025-02-03 =
* Fixed fatal errors by moving version info methods to a new class and deprecating conflicting ones in ActionScheduler_Versions
= 3.9.1 - 2025-01-21 =
* A number of new WP CLI commands have been added, making it easier to manage actions in the terminal and from scripts.
* New wp action-scheduler source command to help determine how Action Scheduler is being loaded.
* Additional information about the active instance of Action Scheduler is now available in the Help pull-down drawer.
* Make some other nullable parameters explicitly nullable.
* Set option value to `no` rather than deleting.
= 3.9.0 - 2024-11-14 =
* Minimum required version of PHP is now 7.1.
* Performance improvements for the `as_pending_actions_due()` function.
* Existing filter hook `action_scheduler_claim_actions_order_by` enhanced to provide callbacks with additional information.
* Improved compatibility with PHP 8.4, specifically by making implicitly nullable parameters explicitly nullable.
* A large number of coding standards-enhancements, to help reduce friction when submitting plugins to marketplaces and plugin directories. Special props @crstauf for this effort.
* Minor documentation tweaks and improvements.
= 3.8.2 - 2024-09-12 =
* Add missing parameter to the `pre_as_enqueue_async_action` hook.
* Bump minimum PHP version to 7.0.
* Bump minimum WordPress version to 6.4.
* Make the batch size adjustable during processing.
= 3.8.1 - 2024-06-20 =
* Fix typos.
* Improve the messaging in our unidentified action exceptions.
= 3.8.0 - 2024-05-22 =
* Documentation - Fixed typos in perf.md.
* Update - We now require WordPress 6.3 or higher.
* Update - We now require PHP 7.0 or higher.
= 3.7.4 - 2024-04-05 =
* Give a clear description of how the $unique parameter works.
* Preserve the tab field if set.
* Tweak - WP 6.5 compatibility.
= 3.7.3 - 2024-03-20 =
* Do not iterate over all of GET when building form in list table.
* Fix a few issues reported by PCP (Plugin Check Plugin).
* Try to save actions as unique even when the store doesn't support it.
* Tweak - WP 6.4 compatibility.
* Update "Tested up to" tag to WordPress 6.5.
* update version in package-lock.json.
= 3.7.2 - 2024-02-14 =
* No longer user variables in `_n()` translation function.
= 3.7.1 - 2023-12-13 =
* update semver to 5.7.2 because of a security vulnerability in 5.7.1.
= 3.7.0 - 2023-11-20 =
* Important: starting with this release, Action Scheduler follows an L-2 version policy (WordPress, and consequently PHP).
* Add extended indexes for hook_status_scheduled_date_gmt and status_scheduled_date_gmt.
* Catch and log exceptions thrown when actions can't be created, e.g. under a corrupt database schema.
* Tweak - WP 6.4 compatibility.
* Update unit tests for upcoming dependency version policy.
* make sure hook action_scheduler_failed_execution can access original exception object.
* mention dependency version policy in usage.md.
= 3.6.4 - 2023-10-11 =
* Performance improvements when bulk cancelling actions.
* Dev-related fixes.
= 3.6.3 - 2023-09-13 =
* Use `_doing_it_wrong` in initialization check.
= 3.6.2 - 2023-08-09 =
* Add guidance about passing arguments.
* Atomic option locking.
* Improve bulk delete handling.
* Include database error in the exception message.
* Tweak - WP 6.3 compatibility.
= 3.6.1 - 2023-06-14 =
* Document new optional `$priority` arg for various API functions.
* Document the new `--exclude-groups` WP CLI option.
* Document the new `action_scheduler_init` hook.
* Ensure actions within each claim are executed in the expected order.
* Fix incorrect text domain.
* Remove SHOW TABLES usage when checking if tables exist.
= 3.6.0 - 2023-05-10 =
* Add $unique parameter to function signatures.
* Add a cast-to-int for extra safety before forming new DateTime object.
* Add a hook allowing exceptions for consistently failing recurring actions.
* Add action priorities.
* Add init hook.
* Always raise the time limit.
* Bump minimatch from 3.0.4 to 3.0.8.
* Bump yaml from 2.2.1 to 2.2.2.
* Defensive coding relating to gaps in declared schedule types.
* Do not process an action if it cannot be set to `in-progress`.
* Filter view labels (status names) should be translatable | #919.
* Fix WPCLI progress messages.
* Improve data-store initialization flow.
* Improve error handling across all supported PHP versions.
* Improve logic for flushing the runtime cache.
* Support exclusion of multiple groups.
* Update lint-staged and Node/NPM requirements.
* add CLI clean command.
* add CLI exclude-group filter.
* exclude past-due from list table all filter count.
* throwing an exception if as_schedule_recurring_action interval param is not of type integer.
= 3.5.4 - 2023-01-17 =
* Add pre filters during action registration.
* Async scheduling.
* Calculate timeouts based on total actions.
* Correctly order the parameters for `ActionScheduler_ActionFactory`'s calls to `single_unique`.
* Fetch action in memory first before releasing claim to avoid deadlock.
* PHP 8.2: declare property to fix creation of dynamic property warning.
* PHP 8.2: fix "Using ${var} in strings is deprecated, use {$var} instead".
* Prevent `undefined variable` warning for `$num_pastdue_actions`.
= 3.5.3 - 2022-11-09 =
* Query actions with partial match.
= 3.5.2 - 2022-09-16 =
* Fix - erroneous 3.5.1 release.
= 3.5.1 - 2022-09-13 =
* Maintenance on A/S docs.
* fix: PHP 8.2 deprecated notice.
= 3.5.0 - 2022-08-25 =
* Add - The active view link within the "Tools > Scheduled Actions" screen is now clickable.
* Add - A warning when there are past-due actions.
* Enhancement - Added the ability to schedule unique actions via an atomic operation.
* Enhancement - Improvements to cache invalidation when processing batches (when running on WordPress 6.0+).
* Enhancement - If a recurring action is found to be consistently failing, it will stop being rescheduled.
* Enhancement - Adds a new "Past Due" view to the scheduled actions list table.
= 3.4.2 - 2022-06-08 =
* Fix - Change the include for better linting.
* Fix - update: Added Action scheduler completed action hook.
= 3.4.1 - 2022-05-24 =
* Fix - Change the include for better linting.
* Fix - Fix the documented return type.
= 3.4.0 - 2021-10-29 =
* Enhancement - Number of items per page can now be set for the Scheduled Actions view (props @ovidiul). #771
* Fix - Do not lower the max_execution_time if it is already set to 0 (unlimited) (props @barryhughes). #755
* Fix - Avoid triggering autoloaders during the version resolution process (props @olegabr). #731 & #776
* Dev - ActionScheduler_wcSystemStatus PHPCS fixes (props @ovidiul). #761
* Dev - ActionScheduler_DBLogger.php PHPCS fixes (props @ovidiul). #768
* Dev - Fixed phpcs for ActionScheduler_Schedule_Deprecated (props @ovidiul). #762
* Dev - Improve actions table indices (props @glagonikas). #774 & #777
* Dev - PHPCS fixes for ActionScheduler_DBStore.php (props @ovidiul). #769 & #778
* Dev - PHPCS Fixes for ActionScheduler_Abstract_ListTable (props @ovidiul). #763 & #779
* Dev - Adds new filter action_scheduler_claim_actions_order_by to allow tuning of the claim query (props @glagonikas). #773
* Dev - PHPCS fixes for ActionScheduler_WpPostStore class (props @ovidiul). #780
= 3.3.0 - 2021-09-15 =
* Enhancement - Adds as_has_scheduled_action() to provide a performant way to test for existing actions. #645
* Fix - Improves compatibility with environments where NO_ZERO_DATE is enabled. #519
* Fix - Adds safety checks to guard against errors when our database tables cannot be created. #645
* Dev - Now supports queries that use multiple statuses. #649
* Dev - Minimum requirements for WordPress and PHP bumped (to 5.2 and 5.6 respectively). #723
= 3.2.1 - 2021-06-21 =
* Fix - Add extra safety/account for different versions of AS and different loading patterns. #714
* Fix - Handle hidden columns (Tools → Scheduled Actions) | #600.
= 3.2.0 - 2021-06-03 =
* Fix - Add "no ordering" option to as_next_scheduled_action().
* Fix - Add secondary scheduled date checks when claiming actions (DBStore) | #634.
* Fix - Add secondary scheduled date checks when claiming actions (wpPostStore) | #634.
* Fix - Adds a new index to the action table, reducing the potential for deadlocks (props: @glagonikas).
* Fix - Fix unit tests infrastructure and adapt tests to PHP 8.
* Fix - Identify in-use data store.
* Fix - Improve test_migration_is_scheduled.
* Fix - PHP notice on list table.
* Fix - Speed up clean up and batch selects.
* Fix - Update pending dependencies.
* Fix - [PHP 8.0] Only pass action arg values through to do_action_ref_array().
* Fix - [PHP 8] Set the PHP version to 7.1 in composer.json for PHP 8 compatibility.
* Fix - add is_initialized() to docs.
* Fix - fix file permissions.
* Fix - fixes #664 by replacing __ with esc_html__.
= 3.1.6 - 2020-05-12 =
* Change log starts.

View file

@ -0,0 +1,45 @@
<?php
/**
* Class ActionScheduler_ActionClaim
*/
class ActionScheduler_ActionClaim {
/**
* Claim ID.
*
* @var string
*/
private $id = '';
/**
* Claimed action IDs.
*
* @var int[]
*/
private $action_ids = array();
/**
* Construct.
*
* @param string $id Claim ID.
* @param int[] $action_ids Action IDs.
*/
public function __construct( $id, array $action_ids ) {
$this->id = $id;
$this->action_ids = $action_ids;
}
/**
* Get claim ID.
*/
public function get_id() {
return $this->id;
}
/**
* Get IDs of claimed actions.
*/
public function get_actions() {
return $this->action_ids;
}
}

View file

@ -0,0 +1,378 @@
<?php
/**
* Class ActionScheduler_ActionFactory
*/
class ActionScheduler_ActionFactory {
/**
* Return stored actions for given params.
*
* @param string $status The action's status in the data store.
* @param string $hook The hook to trigger when this action runs.
* @param array $args Args to pass to callbacks when the hook is triggered.
* @param ActionScheduler_Schedule|null $schedule The action's schedule.
* @param string $group A group to put the action in.
* phpcs:ignore Squiz.Commenting.FunctionComment.ExtraParamComment
* @param int $priority The action priority.
*
* @return ActionScheduler_Action An instance of the stored action.
*/
public function get_stored_action( $status, $hook, array $args = array(), ?ActionScheduler_Schedule $schedule = null, $group = '' ) {
// The 6th parameter ($priority) is not formally declared in the method signature to maintain compatibility with
// third-party subclasses created before this param was added.
$priority = func_num_args() >= 6 ? (int) func_get_arg( 5 ) : 10;
switch ( $status ) {
case ActionScheduler_Store::STATUS_PENDING:
$action_class = 'ActionScheduler_Action';
break;
case ActionScheduler_Store::STATUS_CANCELED:
$action_class = 'ActionScheduler_CanceledAction';
if ( ! is_null( $schedule ) && ! is_a( $schedule, 'ActionScheduler_CanceledSchedule' ) && ! is_a( $schedule, 'ActionScheduler_NullSchedule' ) ) {
$schedule = new ActionScheduler_CanceledSchedule( $schedule->get_date() );
}
break;
default:
$action_class = 'ActionScheduler_FinishedAction';
break;
}
$action_class = apply_filters( 'action_scheduler_stored_action_class', $action_class, $status, $hook, $args, $schedule, $group );
$action = new $action_class( $hook, $args, $schedule, $group );
$action->set_priority( $priority );
/**
* Allow 3rd party code to change the instantiated action for a given hook, args, schedule and group.
*
* @param ActionScheduler_Action $action The instantiated action.
* @param string $hook The instantiated action's hook.
* @param array $args The instantiated action's args.
* @param ActionScheduler_Schedule $schedule The instantiated action's schedule.
* @param string $group The instantiated action's group.
* @param int $priority The action priority.
*/
return apply_filters( 'action_scheduler_stored_action_instance', $action, $hook, $args, $schedule, $group, $priority );
}
/**
* Enqueue an action to run one time, as soon as possible (rather a specific scheduled time).
*
* This method creates a new action using the NullSchedule. In practice, this results in an action scheduled to
* execute "now". Therefore, it will generally run as soon as possible but is not prioritized ahead of other actions
* that are already past-due.
*
* @param string $hook The hook to trigger when this action runs.
* @param array $args Args to pass when the hook is triggered.
* @param string $group A group to put the action in.
*
* @return int The ID of the stored action.
*/
public function async( $hook, $args = array(), $group = '' ) {
return $this->async_unique( $hook, $args, $group, false );
}
/**
* Same as async, but also supports $unique param.
*
* @param string $hook The hook to trigger when this action runs.
* @param array $args Args to pass when the hook is triggered.
* @param string $group A group to put the action in.
* @param bool $unique Whether to ensure the action is unique.
*
* @return int The ID of the stored action.
*/
public function async_unique( $hook, $args = array(), $group = '', $unique = true ) {
$schedule = new ActionScheduler_NullSchedule();
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
return $unique ? $this->store_unique_action( $action, $unique ) : $this->store( $action );
}
/**
* Create single action.
*
* @param string $hook The hook to trigger when this action runs.
* @param array $args Args to pass when the hook is triggered.
* @param int $when Unix timestamp when the action will run.
* @param string $group A group to put the action in.
*
* @return int The ID of the stored action.
*/
public function single( $hook, $args = array(), $when = null, $group = '' ) {
return $this->single_unique( $hook, $args, $when, $group, false );
}
/**
* Create single action only if there is no pending or running action with same name and params.
*
* @param string $hook The hook to trigger when this action runs.
* @param array $args Args to pass when the hook is triggered.
* @param int $when Unix timestamp when the action will run.
* @param string $group A group to put the action in.
* @param bool $unique Whether action scheduled should be unique.
*
* @return int The ID of the stored action.
*/
public function single_unique( $hook, $args = array(), $when = null, $group = '', $unique = true ) {
$date = as_get_datetime_object( $when );
$schedule = new ActionScheduler_SimpleSchedule( $date );
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
return $unique ? $this->store_unique_action( $action ) : $this->store( $action );
}
/**
* Create the first instance of an action recurring on a given interval.
*
* @param string $hook The hook to trigger when this action runs.
* @param array $args Args to pass when the hook is triggered.
* @param int $first Unix timestamp for the first run.
* @param int $interval Seconds between runs.
* @param string $group A group to put the action in.
*
* @return int The ID of the stored action.
*/
public function recurring( $hook, $args = array(), $first = null, $interval = null, $group = '' ) {
return $this->recurring_unique( $hook, $args, $first, $interval, $group, false );
}
/**
* Create the first instance of an action recurring on a given interval only if there is no pending or running action with same name and params.
*
* @param string $hook The hook to trigger when this action runs.
* @param array $args Args to pass when the hook is triggered.
* @param int $first Unix timestamp for the first run.
* @param int $interval Seconds between runs.
* @param string $group A group to put the action in.
* @param bool $unique Whether action scheduled should be unique.
*
* @return int The ID of the stored action.
*/
public function recurring_unique( $hook, $args = array(), $first = null, $interval = null, $group = '', $unique = true ) {
if ( empty( $interval ) ) {
return $this->single_unique( $hook, $args, $first, $group, $unique );
}
$date = as_get_datetime_object( $first );
$schedule = new ActionScheduler_IntervalSchedule( $date, $interval );
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
return $unique ? $this->store_unique_action( $action ) : $this->store( $action );
}
/**
* Create the first instance of an action recurring on a Cron schedule.
*
* @param string $hook The hook to trigger when this action runs.
* @param array $args Args to pass when the hook is triggered.
* @param int $base_timestamp The first instance of the action will be scheduled
* to run at a time calculated after this timestamp matching the cron
* expression. This can be used to delay the first instance of the action.
* @param int $schedule A cron definition string.
* @param string $group A group to put the action in.
*
* @return int The ID of the stored action.
*/
public function cron( $hook, $args = array(), $base_timestamp = null, $schedule = null, $group = '' ) {
return $this->cron_unique( $hook, $args, $base_timestamp, $schedule, $group, false );
}
/**
* Create the first instance of an action recurring on a Cron schedule only if there is no pending or running action with same name and params.
*
* @param string $hook The hook to trigger when this action runs.
* @param array $args Args to pass when the hook is triggered.
* @param int $base_timestamp The first instance of the action will be scheduled
* to run at a time calculated after this timestamp matching the cron
* expression. This can be used to delay the first instance of the action.
* @param int $schedule A cron definition string.
* @param string $group A group to put the action in.
* @param bool $unique Whether action scheduled should be unique.
*
* @return int The ID of the stored action.
**/
public function cron_unique( $hook, $args = array(), $base_timestamp = null, $schedule = null, $group = '', $unique = true ) {
if ( empty( $schedule ) ) {
return $this->single_unique( $hook, $args, $base_timestamp, $group, $unique );
}
$date = as_get_datetime_object( $base_timestamp );
$cron = CronExpression::factory( $schedule );
$schedule = new ActionScheduler_CronSchedule( $date, $cron );
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
return $unique ? $this->store_unique_action( $action ) : $this->store( $action );
}
/**
* Create a successive instance of a recurring or cron action.
*
* Importantly, the action will be rescheduled to run based on the current date/time.
* That means when the action is scheduled to run in the past, the next scheduled date
* will be pushed forward. For example, if a recurring action set to run every hour
* was scheduled to run 5 seconds ago, it will be next scheduled for 1 hour in the
* future, which is 1 hour and 5 seconds from when it was last scheduled to run.
*
* Alternatively, if the action is scheduled to run in the future, and is run early,
* likely via manual intervention, then its schedule will change based on the time now.
* For example, if a recurring action set to run every day, and is run 12 hours early,
* it will run again in 24 hours, not 36 hours.
*
* This slippage is less of an issue with Cron actions, as the specific run time can
* be set for them to run, e.g. 1am each day. In those cases, and entire period would
* need to be missed before there was any change is scheduled, e.g. in the case of an
* action scheduled for 1am each day, the action would need to run an entire day late.
*
* @param ActionScheduler_Action $action The existing action.
*
* @return string The ID of the stored action
* @throws InvalidArgumentException If $action is not a recurring action.
*/
public function repeat( $action ) {
$schedule = $action->get_schedule();
$next = $schedule->get_next( as_get_datetime_object() );
if ( is_null( $next ) || ! $schedule->is_recurring() ) {
throw new InvalidArgumentException( __( 'Invalid action - must be a recurring action.', 'action-scheduler' ) );
}
$schedule_class = get_class( $schedule );
$new_schedule = new $schedule( $next, $schedule->get_recurrence(), $schedule->get_first_date() );
$new_action = new ActionScheduler_Action( $action->get_hook(), $action->get_args(), $new_schedule, $action->get_group() );
$new_action->set_priority( $action->get_priority() );
return $this->store( $new_action );
}
/**
* Creates a scheduled action.
*
* This general purpose method can be used in place of specific methods such as async(),
* async_unique(), single() or single_unique(), etc.
*
* @internal Not intended for public use, should not be overridden by subclasses.
*
* @param array $options {
* Describes the action we wish to schedule.
*
* @type string $type Must be one of 'async', 'cron', 'recurring', or 'single'.
* @type string $hook The hook to be executed.
* @type array $arguments Arguments to be passed to the callback.
* @type string $group The action group.
* @type bool $unique If the action should be unique.
* @type int $when Timestamp. Indicates when the action, or first instance of the action in the case
* of recurring or cron actions, becomes due.
* @type int|string $pattern Recurrence pattern. This is either an interval in seconds for recurring actions
* or a cron expression for cron actions.
* @type int $priority Lower values means higher priority. Should be in the range 0-255.
* }
*
* @return int The action ID. Zero if there was an error scheduling the action.
*/
public function create( array $options = array() ) {
$defaults = array(
'type' => 'single',
'hook' => '',
'arguments' => array(),
'group' => '',
'unique' => false,
'when' => time(),
'pattern' => null,
'priority' => 10,
);
$options = array_merge( $defaults, $options );
// Cron/recurring actions without a pattern are treated as single actions (this gives calling code the ability
// to use functions like as_schedule_recurring_action() to schedule recurring as well as single actions).
if ( ( 'cron' === $options['type'] || 'recurring' === $options['type'] ) && empty( $options['pattern'] ) ) {
$options['type'] = 'single';
}
switch ( $options['type'] ) {
case 'async':
$schedule = new ActionScheduler_NullSchedule();
break;
case 'cron':
$date = as_get_datetime_object( $options['when'] );
$cron = CronExpression::factory( $options['pattern'] );
$schedule = new ActionScheduler_CronSchedule( $date, $cron );
break;
case 'recurring':
$date = as_get_datetime_object( $options['when'] );
$schedule = new ActionScheduler_IntervalSchedule( $date, $options['pattern'] );
break;
case 'single':
$date = as_get_datetime_object( $options['when'] );
$schedule = new ActionScheduler_SimpleSchedule( $date );
break;
default:
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log( "Unknown action type '{$options['type']}' specified when trying to create an action for '{$options['hook']}'." );
return 0;
}
$action = new ActionScheduler_Action( $options['hook'], $options['arguments'], $schedule, $options['group'] );
$action->set_priority( $options['priority'] );
$action_id = 0;
try {
$action_id = $options['unique'] ? $this->store_unique_action( $action ) : $this->store( $action );
} catch ( Exception $e ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log(
sprintf(
/* translators: %1$s is the name of the hook to be enqueued, %2$s is the exception message. */
__( 'Caught exception while enqueuing action "%1$s": %2$s', 'action-scheduler' ),
$options['hook'],
$e->getMessage()
)
);
}
return $action_id;
}
/**
* Save action to database.
*
* @param ActionScheduler_Action $action Action object to save.
*
* @return int The ID of the stored action
*/
protected function store( ActionScheduler_Action $action ) {
$store = ActionScheduler_Store::instance();
return $store->save_action( $action );
}
/**
* Store action if it's unique.
*
* @param ActionScheduler_Action $action Action object to store.
*
* @return int ID of the created action. Will be 0 if action was not created.
*/
protected function store_unique_action( ActionScheduler_Action $action ) {
$store = ActionScheduler_Store::instance();
if ( method_exists( $store, 'save_unique_action' ) ) {
return $store->save_unique_action( $action );
} else {
/**
* Fallback to non-unique action if the store doesn't support unique actions.
* We try to save the action as unique, accepting that there might be a race condition.
* This is likely still better than giving up on unique actions entirely.
*/
$existing_action_id = (int) $store->find_action(
$action->get_hook(),
array(
'args' => $action->get_args(),
'status' => ActionScheduler_Store::STATUS_PENDING,
'group' => $action->get_group(),
)
);
if ( $existing_action_id > 0 ) {
return 0;
}
return $store->save_action( $action );
}
}
}

View file

@ -0,0 +1,311 @@
<?php
/**
* Class ActionScheduler_AdminView
*
* @codeCoverageIgnore
*/
class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {
/**
* Instance.
*
* @var null|self
*/
private static $admin_view = null;
/**
* Screen ID.
*
* @var string
*/
private static $screen_id = 'tools_page_action-scheduler';
/**
* ActionScheduler_ListTable instance.
*
* @var ActionScheduler_ListTable
*/
protected $list_table;
/**
* Get instance.
*
* @return ActionScheduler_AdminView
* @codeCoverageIgnore
*/
public static function instance() {
if ( empty( self::$admin_view ) ) {
$class = apply_filters( 'action_scheduler_admin_view_class', 'ActionScheduler_AdminView' );
self::$admin_view = new $class();
}
return self::$admin_view;
}
/**
* Initialize.
*
* @codeCoverageIgnore
*/
public function init() {
if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) ) {
if ( class_exists( 'WooCommerce' ) ) {
add_action( 'woocommerce_admin_status_content_action-scheduler', array( $this, 'render_admin_ui' ) );
add_action( 'woocommerce_system_status_report', array( $this, 'system_status_report' ) );
add_filter( 'woocommerce_admin_status_tabs', array( $this, 'register_system_status_tab' ) );
}
add_action( 'admin_menu', array( $this, 'register_menu' ) );
add_action( 'admin_notices', array( $this, 'maybe_check_pastdue_actions' ) );
add_action( 'current_screen', array( $this, 'add_help_tabs' ) );
}
}
/**
* Print system status report.
*/
public function system_status_report() {
$table = new ActionScheduler_wcSystemStatus( ActionScheduler::store() );
$table->render();
}
/**
* Registers action-scheduler into WooCommerce > System status.
*
* @param array $tabs An associative array of tab key => label.
* @return array $tabs An associative array of tab key => label, including Action Scheduler's tabs
*/
public function register_system_status_tab( array $tabs ) {
$tabs['action-scheduler'] = __( 'Scheduled Actions', 'action-scheduler' );
return $tabs;
}
/**
* Include Action Scheduler's administration under the Tools menu.
*
* A menu under the Tools menu is important for backward compatibility (as that's
* where it started), and also provides more convenient access than the WooCommerce
* System Status page, and for sites where WooCommerce isn't active.
*/
public function register_menu() {
$hook_suffix = add_submenu_page(
'tools.php',
__( 'Scheduled Actions', 'action-scheduler' ),
__( 'Scheduled Actions', 'action-scheduler' ),
'manage_options',
'action-scheduler',
array( $this, 'render_admin_ui' )
);
add_action( 'load-' . $hook_suffix, array( $this, 'process_admin_ui' ) );
}
/**
* Triggers processing of any pending actions.
*/
public function process_admin_ui() {
$this->get_list_table();
}
/**
* Renders the Admin UI
*/
public function render_admin_ui() {
$table = $this->get_list_table();
$table->display_page();
}
/**
* Get the admin UI object and process any requested actions.
*
* @return ActionScheduler_ListTable
*/
protected function get_list_table() {
if ( null === $this->list_table ) {
$this->list_table = new ActionScheduler_ListTable( ActionScheduler::store(), ActionScheduler::logger(), ActionScheduler::runner() );
$this->list_table->process_actions();
}
return $this->list_table;
}
/**
* Action: admin_notices
*
* Maybe check past-due actions, and print notice.
*
* @uses $this->check_pastdue_actions()
*/
public function maybe_check_pastdue_actions() {
// Filter to prevent checking actions (ex: inappropriate user).
if ( ! apply_filters( 'action_scheduler_check_pastdue_actions', current_user_can( 'manage_options' ) ) ) {
return;
}
// Get last check transient.
$last_check = get_transient( 'action_scheduler_last_pastdue_actions_check' );
// If transient exists, we're within interval, so bail.
if ( ! empty( $last_check ) ) {
return;
}
// Perform the check.
$this->check_pastdue_actions();
}
/**
* Check past-due actions, and print notice.
*/
protected function check_pastdue_actions() {
// Set thresholds.
$threshold_seconds = (int) apply_filters( 'action_scheduler_pastdue_actions_seconds', DAY_IN_SECONDS );
$threshold_min = (int) apply_filters( 'action_scheduler_pastdue_actions_min', 1 );
// Set fallback value for past-due actions count.
$num_pastdue_actions = 0;
// Allow third-parties to preempt the default check logic.
$check = apply_filters( 'action_scheduler_pastdue_actions_check_pre', null );
// If no third-party preempted and there are no past-due actions, return early.
if ( ! is_null( $check ) ) {
return;
}
// Scheduled actions query arguments.
$query_args = array(
'date' => as_get_datetime_object( time() - $threshold_seconds ),
'status' => ActionScheduler_Store::STATUS_PENDING,
'per_page' => $threshold_min,
);
// If no third-party preempted, run default check.
if ( is_null( $check ) ) {
$store = ActionScheduler_Store::instance();
$num_pastdue_actions = (int) $store->query_actions( $query_args, 'count' );
// Check if past-due actions count is greater than or equal to threshold.
$check = ( $num_pastdue_actions >= $threshold_min );
$check = (bool) apply_filters( 'action_scheduler_pastdue_actions_check', $check, $num_pastdue_actions, $threshold_seconds, $threshold_min );
}
// If check failed, set transient and abort.
if ( ! boolval( $check ) ) {
$interval = apply_filters( 'action_scheduler_pastdue_actions_check_interval', round( $threshold_seconds / 4 ), $threshold_seconds );
set_transient( 'action_scheduler_last_pastdue_actions_check', time(), $interval );
return;
}
$actions_url = add_query_arg(
array(
'page' => 'action-scheduler',
'status' => 'past-due',
'order' => 'asc',
),
admin_url( 'tools.php' )
);
// Print notice.
echo '<div class="notice notice-warning"><p>';
printf(
wp_kses(
// translators: 1) is the number of affected actions, 2) is a link to an admin screen.
_n(
'<strong>Action Scheduler:</strong> %1$d <a href="%2$s">past-due action</a> found; something may be wrong. <a href="https://actionscheduler.org/faq/#my-site-has-past-due-actions-what-can-i-do" target="_blank">Read documentation &raquo;</a>',
'<strong>Action Scheduler:</strong> %1$d <a href="%2$s">past-due actions</a> found; something may be wrong. <a href="https://actionscheduler.org/faq/#my-site-has-past-due-actions-what-can-i-do" target="_blank">Read documentation &raquo;</a>',
$num_pastdue_actions,
'action-scheduler'
),
array(
'strong' => array(),
'a' => array(
'href' => true,
'target' => true,
),
)
),
absint( $num_pastdue_actions ),
esc_attr( esc_url( $actions_url ) )
);
echo '</p></div>';
// Facilitate third-parties to evaluate and print notices.
do_action( 'action_scheduler_pastdue_actions_extra_notices', $query_args );
}
/**
* Provide more information about the screen and its data in the help tab.
*/
public function add_help_tabs() {
$screen = get_current_screen();
if ( ! $screen || self::$screen_id !== $screen->id ) {
return;
}
$as_version = ActionScheduler_Versions::instance()->latest_version();
$as_source = ActionScheduler_SystemInformation::active_source();
$as_source_path = ActionScheduler_SystemInformation::active_source_path();
$as_source_markup = sprintf( '<code>%s</code>', esc_html( $as_source_path ) );
if ( ! empty( $as_source ) ) {
$as_source_markup = sprintf(
'%s: <abbr title="%s">%s</abbr>',
ucfirst( $as_source['type'] ),
esc_attr( $as_source_path ),
esc_html( $as_source['name'] )
);
}
$screen->add_help_tab(
array(
'id' => 'action_scheduler_about',
'title' => __( 'About', 'action-scheduler' ),
'content' =>
// translators: %s is the Action Scheduler version.
'<h2>' . sprintf( __( 'About Action Scheduler %s', 'action-scheduler' ), $as_version ) . '</h2>' .
'<p>' .
__( 'Action Scheduler is a scalable, traceable job queue for background processing large sets of actions. Action Scheduler works by triggering an action hook to run at some time in the future. Scheduled actions can also be scheduled to run on a recurring schedule.', 'action-scheduler' ) .
'</p>' .
'<h3>' . esc_html__( 'Source', 'action-scheduler' ) . '</h3>' .
'<p>' .
esc_html__( 'Action Scheduler is currently being loaded from the following location. This can be useful when debugging, or if requested by the support team.', 'action-scheduler' ) .
'</p>' .
'<p>' . $as_source_markup . '</p>' .
'<h3>' . esc_html__( 'WP CLI', 'action-scheduler' ) . '</h3>' .
'<p>' .
sprintf(
/* translators: %1$s is WP CLI command (not translatable) */
esc_html__( 'WP CLI commands are available: execute %1$s for a list of available commands.', 'action-scheduler' ),
'<code>wp help action-scheduler</code>'
) .
'</p>',
)
);
$screen->add_help_tab(
array(
'id' => 'action_scheduler_columns',
'title' => __( 'Columns', 'action-scheduler' ),
'content' =>
'<h2>' . __( 'Scheduled Action Columns', 'action-scheduler' ) . '</h2>' .
'<ul>' .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Hook', 'action-scheduler' ), __( 'Name of the action hook that will be triggered.', 'action-scheduler' ) ) .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Status', 'action-scheduler' ), __( 'Action statuses are Pending, Complete, Canceled, Failed', 'action-scheduler' ) ) .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Arguments', 'action-scheduler' ), __( 'Optional data array passed to the action hook.', 'action-scheduler' ) ) .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Group', 'action-scheduler' ), __( 'Optional action group.', 'action-scheduler' ) ) .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Recurrence', 'action-scheduler' ), __( 'The action\'s schedule frequency.', 'action-scheduler' ) ) .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Scheduled', 'action-scheduler' ), __( 'The date/time the action is/was scheduled to run.', 'action-scheduler' ) ) .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Log', 'action-scheduler' ), __( 'Activity log for the action.', 'action-scheduler' ) ) .
'</ul>',
)
);
}
}

View file

@ -0,0 +1,93 @@
<?php
defined( 'ABSPATH' ) || exit;
/**
* ActionScheduler_AsyncRequest_QueueRunner class.
*/
class ActionScheduler_AsyncRequest_QueueRunner extends WP_Async_Request {
/**
* Data store for querying actions
*
* @var ActionScheduler_Store
*/
protected $store;
/**
* Prefix for ajax hooks
*
* @var string
*/
protected $prefix = 'as';
/**
* Action for ajax hooks
*
* @var string
*/
protected $action = 'async_request_queue_runner';
/**
* Initiate new async request.
*
* @param ActionScheduler_Store $store Store object.
*/
public function __construct( ActionScheduler_Store $store ) {
parent::__construct();
$this->store = $store;
}
/**
* Handle async requests
*
* Run a queue, and maybe dispatch another async request to run another queue
* if there are still pending actions after completing a queue in this request.
*/
protected function handle() {
do_action( 'action_scheduler_run_queue', 'Async Request' ); // run a queue in the same way as WP Cron, but declare the Async Request context.
$sleep_seconds = $this->get_sleep_seconds();
if ( $sleep_seconds ) {
sleep( $sleep_seconds );
}
$this->maybe_dispatch();
}
/**
* If the async request runner is needed and allowed to run, dispatch a request.
*/
public function maybe_dispatch() {
if ( ! $this->allow() ) {
return;
}
$this->dispatch();
ActionScheduler_QueueRunner::instance()->unhook_dispatch_async_request();
}
/**
* Only allow async requests when needed.
*
* Also allow 3rd party code to disable running actions via async requests.
*/
protected function allow() {
if ( ! has_action( 'action_scheduler_run_queue' ) || ActionScheduler::runner()->has_maximum_concurrent_batches() || ! $this->store->has_pending_actions_due() ) {
$allow = false;
} else {
$allow = true;
}
return apply_filters( 'action_scheduler_allow_async_request_runner', $allow );
}
/**
* Chaining async requests can crash MySQL. A brief sleep call in PHP prevents that.
*/
protected function get_sleep_seconds() {
return apply_filters( 'action_scheduler_async_request_sleep_seconds', 5, $this );
}
}

View file

@ -0,0 +1,111 @@
<?php
/**
* Class ActionScheduler_Compatibility
*/
class ActionScheduler_Compatibility {
/**
* Converts a shorthand byte value to an integer byte value.
*
* Wrapper for wp_convert_hr_to_bytes(), moved to load.php in WordPress 4.6 from media.php
*
* @link https://secure.php.net/manual/en/function.ini-get.php
* @link https://secure.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
*
* @param string $value A (PHP ini) byte value, either shorthand or ordinary.
* @return int An integer byte value.
*/
public static function convert_hr_to_bytes( $value ) {
if ( function_exists( 'wp_convert_hr_to_bytes' ) ) {
return wp_convert_hr_to_bytes( $value );
}
$value = strtolower( trim( $value ) );
$bytes = (int) $value;
if ( false !== strpos( $value, 'g' ) ) {
$bytes *= GB_IN_BYTES;
} elseif ( false !== strpos( $value, 'm' ) ) {
$bytes *= MB_IN_BYTES;
} elseif ( false !== strpos( $value, 'k' ) ) {
$bytes *= KB_IN_BYTES;
}
// Deal with large (float) values which run into the maximum integer size.
return min( $bytes, PHP_INT_MAX );
}
/**
* Attempts to raise the PHP memory limit for memory intensive processes.
*
* Only allows raising the existing limit and prevents lowering it.
*
* Wrapper for wp_raise_memory_limit(), added in WordPress v4.6.0
*
* @return bool|int|string The limit that was set or false on failure.
*/
public static function raise_memory_limit() {
if ( function_exists( 'wp_raise_memory_limit' ) ) {
return wp_raise_memory_limit( 'admin' );
}
$current_limit = @ini_get( 'memory_limit' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
$current_limit_int = self::convert_hr_to_bytes( $current_limit );
if ( -1 === $current_limit_int ) {
return false;
}
$wp_max_limit = WP_MAX_MEMORY_LIMIT;
$wp_max_limit_int = self::convert_hr_to_bytes( $wp_max_limit );
$filtered_limit = apply_filters( 'admin_memory_limit', $wp_max_limit );
$filtered_limit_int = self::convert_hr_to_bytes( $filtered_limit );
// phpcs:disable WordPress.PHP.IniSet.memory_limit_Blacklisted
// phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
if ( -1 === $filtered_limit_int || ( $filtered_limit_int > $wp_max_limit_int && $filtered_limit_int > $current_limit_int ) ) {
if ( false !== @ini_set( 'memory_limit', $filtered_limit ) ) {
return $filtered_limit;
} else {
return false;
}
} elseif ( -1 === $wp_max_limit_int || $wp_max_limit_int > $current_limit_int ) {
if ( false !== @ini_set( 'memory_limit', $wp_max_limit ) ) {
return $wp_max_limit;
} else {
return false;
}
}
// phpcs:enable
return false;
}
/**
* Attempts to raise the PHP timeout for time intensive processes.
*
* Only allows raising the existing limit and prevents lowering it. Wrapper for wc_set_time_limit(), when available.
*
* @param int $limit The time limit in seconds.
*/
public static function raise_time_limit( $limit = 0 ) {
$limit = (int) $limit;
$max_execution_time = (int) ini_get( 'max_execution_time' );
// If the max execution time is already set to zero (unlimited), there is no reason to make a further change.
if ( 0 === $max_execution_time ) {
return;
}
// Whichever of $max_execution_time or $limit is higher is the amount by which we raise the time limit.
$raise_by = 0 === $limit || $limit > $max_execution_time ? $limit : $max_execution_time;
if ( function_exists( 'wc_set_time_limit' ) ) {
wc_set_time_limit( $raise_by );
} elseif ( function_exists( 'set_time_limit' ) && false === strpos( ini_get( 'disable_functions' ), 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) { // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.safe_modeDeprecatedRemoved
@set_time_limit( $raise_by ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
}
}
}

View file

@ -0,0 +1,210 @@
<?php
use Action_Scheduler\Migration\Controller;
/**
* Class ActionScheduler_DataController
*
* The main plugin/initialization class for the data stores.
*
* Responsible for hooking everything up with WordPress.
*
* @package Action_Scheduler
*
* @since 3.0.0
*/
class ActionScheduler_DataController {
/** Action data store class name. */
const DATASTORE_CLASS = 'ActionScheduler_DBStore';
/** Logger data store class name. */
const LOGGER_CLASS = 'ActionScheduler_DBLogger';
/** Migration status option name. */
const STATUS_FLAG = 'action_scheduler_migration_status';
/** Migration status option value. */
const STATUS_COMPLETE = 'complete';
/** Migration minimum required PHP version. */
const MIN_PHP_VERSION = '5.5';
/**
* Instance.
*
* @var ActionScheduler_DataController
*/
private static $instance;
/**
* Sleep time in seconds.
*
* @var int
*/
private static $sleep_time = 0;
/**
* Tick count required for freeing memory.
*
* @var int
*/
private static $free_ticks = 50;
/**
* Get a flag indicating whether the migration environment dependencies are met.
*
* @return bool
*/
public static function dependencies_met() {
$php_support = version_compare( PHP_VERSION, self::MIN_PHP_VERSION, '>=' );
return $php_support && apply_filters( 'action_scheduler_migration_dependencies_met', true );
}
/**
* Get a flag indicating whether the migration is complete.
*
* @return bool Whether the flag has been set marking the migration as complete
*/
public static function is_migration_complete() {
return get_option( self::STATUS_FLAG ) === self::STATUS_COMPLETE;
}
/**
* Mark the migration as complete.
*/
public static function mark_migration_complete() {
update_option( self::STATUS_FLAG, self::STATUS_COMPLETE );
}
/**
* Unmark migration when a plugin is de-activated. Will not work in case of silent activation, for example in an update.
* We do this to mitigate the bug of lost actions which happens if there was an AS 2.x to AS 3.x migration in the past, but that plugin is now
* deactivated and the site was running on AS 2.x again.
*/
public static function mark_migration_incomplete() {
delete_option( self::STATUS_FLAG );
}
/**
* Set the action store class name.
*
* @param string $class Classname of the store class.
*
* @return string
*/
public static function set_store_class( $class ) {
return self::DATASTORE_CLASS;
}
/**
* Set the action logger class name.
*
* @param string $class Classname of the logger class.
*
* @return string
*/
public static function set_logger_class( $class ) {
return self::LOGGER_CLASS;
}
/**
* Set the sleep time in seconds.
*
* @param integer $sleep_time The number of seconds to pause before resuming operation.
*/
public static function set_sleep_time( $sleep_time ) {
self::$sleep_time = (int) $sleep_time;
}
/**
* Set the tick count required for freeing memory.
*
* @param integer $free_ticks The number of ticks to free memory on.
*/
public static function set_free_ticks( $free_ticks ) {
self::$free_ticks = (int) $free_ticks;
}
/**
* Free memory if conditions are met.
*
* @param int $ticks Current tick count.
*/
public static function maybe_free_memory( $ticks ) {
if ( self::$free_ticks && 0 === $ticks % self::$free_ticks ) {
self::free_memory();
}
}
/**
* Reduce memory footprint by clearing the database query and object caches.
*/
public static function free_memory() {
if ( 0 < self::$sleep_time ) {
/* translators: %d: amount of time */
\WP_CLI::warning( sprintf( _n( 'Stopped the insanity for %d second', 'Stopped the insanity for %d seconds', self::$sleep_time, 'action-scheduler' ), self::$sleep_time ) );
sleep( self::$sleep_time );
}
\WP_CLI::warning( __( 'Attempting to reduce used memory...', 'action-scheduler' ) );
/**
* Globals.
*
* @var $wpdb \wpdb
* @var $wp_object_cache \WP_Object_Cache
*/
global $wpdb, $wp_object_cache;
$wpdb->queries = array();
if ( ! is_a( $wp_object_cache, 'WP_Object_Cache' ) ) {
return;
}
// Not all drop-ins support these props, however, there may be existing installations that rely on these being cleared.
if ( property_exists( $wp_object_cache, 'group_ops' ) ) {
$wp_object_cache->group_ops = array();
}
if ( property_exists( $wp_object_cache, 'stats' ) ) {
$wp_object_cache->stats = array();
}
if ( property_exists( $wp_object_cache, 'memcache_debug' ) ) {
$wp_object_cache->memcache_debug = array();
}
if ( property_exists( $wp_object_cache, 'cache' ) ) {
$wp_object_cache->cache = array();
}
if ( is_callable( array( $wp_object_cache, '__remoteset' ) ) ) {
call_user_func( array( $wp_object_cache, '__remoteset' ) ); // important!
}
}
/**
* Connect to table datastores if migration is complete.
* Otherwise, proceed with the migration if the dependencies have been met.
*/
public static function init() {
if ( self::is_migration_complete() ) {
add_filter( 'action_scheduler_store_class', array( 'ActionScheduler_DataController', 'set_store_class' ), 100 );
add_filter( 'action_scheduler_logger_class', array( 'ActionScheduler_DataController', 'set_logger_class' ), 100 );
add_action( 'deactivate_plugin', array( 'ActionScheduler_DataController', 'mark_migration_incomplete' ) );
} elseif ( self::dependencies_met() ) {
Controller::init();
}
add_action( 'action_scheduler/progress_tick', array( 'ActionScheduler_DataController', 'maybe_free_memory' ) );
}
/**
* Singleton factory.
*/
public static function instance() {
if ( ! isset( self::$instance ) ) {
self::$instance = new static();
}
return self::$instance;
}
}

View file

@ -0,0 +1,79 @@
<?php
/**
* ActionScheduler DateTime class.
*
* This is a custom extension to DateTime that
*/
class ActionScheduler_DateTime extends DateTime {
/**
* UTC offset.
*
* Only used when a timezone is not set. When a timezone string is
* used, this will be set to 0.
*
* @var int
*/
protected $utcOffset = 0; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.PropertyNotSnakeCase
/**
* Get the unix timestamp of the current object.
*
* Missing in PHP 5.2 so just here so it can be supported consistently.
*
* @return int
*/
#[\ReturnTypeWillChange]
public function getTimestamp() {
return method_exists( 'DateTime', 'getTimestamp' ) ? parent::getTimestamp() : $this->format( 'U' );
}
/**
* Set the UTC offset.
*
* This represents a fixed offset instead of a timezone setting.
*
* @param string|int $offset UTC offset value.
*/
public function setUtcOffset( $offset ) {
$this->utcOffset = intval( $offset ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
}
/**
* Returns the timezone offset.
*
* @return int
* @link http://php.net/manual/en/datetime.getoffset.php
*/
#[\ReturnTypeWillChange]
public function getOffset() {
return $this->utcOffset ? $this->utcOffset : parent::getOffset(); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
}
/**
* Set the TimeZone associated with the DateTime
*
* @param DateTimeZone $timezone Timezone object.
*
* @return static
* @link http://php.net/manual/en/datetime.settimezone.php
*/
#[\ReturnTypeWillChange]
public function setTimezone( $timezone ) {
$this->utcOffset = 0; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
parent::setTimezone( $timezone );
return $this;
}
/**
* Get the timestamp with the WordPress timezone offset added or subtracted.
*
* @since 3.0.0
* @return int
*/
public function getOffsetTimestamp() {
return $this->getTimestamp() + $this->getOffset();
}
}

Some files were not shown because too many files have changed in this diff Show more