Merge commit '10c4a515e40b9d3f5903b15e97376bb153e38c61' as 'includes/libraries/action-scheduler'
This commit is contained in:
commit
cfb1239c3b
|
@ -0,0 +1,3 @@
|
||||||
|
phpunit.xml
|
||||||
|
vendor
|
||||||
|
.idea
|
|
@ -0,0 +1,37 @@
|
||||||
|
# Travis CI Configuration File
|
||||||
|
|
||||||
|
# Tell Travis CI we're using PHP
|
||||||
|
language: php
|
||||||
|
|
||||||
|
# We nee to use Precise, not Trusty, to test against PHP 5.3, see https://github.com/travis-ci/travis-ci/issues/8219
|
||||||
|
dist: precise
|
||||||
|
|
||||||
|
# Versions of PHP to test against
|
||||||
|
php:
|
||||||
|
- "5.3"
|
||||||
|
- "5.4"
|
||||||
|
- "5.5"
|
||||||
|
- "5.6"
|
||||||
|
- "7.0"
|
||||||
|
- "7.1"
|
||||||
|
|
||||||
|
# Specify versions of WordPress to test against
|
||||||
|
# WP_VERSION = WordPress version number (use "master" for SVN trunk)
|
||||||
|
# WP_MULTISITE = whether to test multisite (use either "0" or "1")
|
||||||
|
env:
|
||||||
|
- WP_VERSION=4.8 WP_MULTISITE=0
|
||||||
|
- WP_VERSION=4.7 WP_MULTISITE=0
|
||||||
|
- WP_VERSION=4.6 WP_MULTISITE=0
|
||||||
|
- WP_VERSION=4.8 WP_MULTISITE=1
|
||||||
|
- WP_VERSION=4.7 WP_MULTISITE=1
|
||||||
|
- WP_VERSION=4.6 WP_MULTISITE=1
|
||||||
|
|
||||||
|
# Grab the setup script and execute
|
||||||
|
before_script:
|
||||||
|
- source tests/travis/setup.sh $TRAVIS_PHP_VERSION
|
||||||
|
|
||||||
|
script:
|
||||||
|
- if [[ "$TRAVIS_PHP_VERSION" == "7.1" ]] && [[ "$WP_VERSION" == "4.8" ]] && [[ "$WP_MULTISITE" == "0" ]] && [[ "$TRAVIS_BRANCH" == "master" ]]; then phpunit --configuration tests/phpunit.xml.dist --coverage-clover clover.xml; else phpunit --configuration tests/phpunit.xml.dist; fi
|
||||||
|
|
||||||
|
after_script:
|
||||||
|
- bash <(curl -s https://codecov.io/bash)
|
|
@ -0,0 +1,433 @@
|
||||||
|
# Action Scheduler [![Build Status](https://travis-ci.org/Prospress/action-scheduler.png?branch=master)](https://travis-ci.org/Prospress/action-scheduler) [![codecov](https://codecov.io/gh/Prospress/action-scheduler/branch/master/graph/badge.svg)](https://codecov.io/gh/Prospress/action-scheduler)
|
||||||
|
|
||||||
|
A robust scheduling library for use in WordPress plugins.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Action Scheduler uses a WordPress [custom post type](http://codex.wordpress.org/Post_Types), creatively named `scheduled-action`, to store the hook name, arguments and scheduled date for an action that should be triggered at some time in the future.
|
||||||
|
|
||||||
|
The scheduler will run every minute by attaching itself as a callback to the `'action_scheduler_run_schedule'` hook, which is scheduled using WordPress's built-in [WP-Cron](http://codex.wordpress.org/Function_Reference/wp_cron) system.
|
||||||
|
|
||||||
|
When triggered, Action Scheduler will check for posts of the `scheduled-action` type that have a `post_date` at or before this point in time i.e. actions scheduled to run now or at sometime in the past.
|
||||||
|
|
||||||
|
### Batch Processing
|
||||||
|
|
||||||
|
If there are actions to be processed, Action Scheduler will stake a unique claim for a batch of 20 actions and begin processing that batch. The PHP process spawned to run the batch will then continue processing batches of 20 actions until it times out or exhausts available memory.
|
||||||
|
|
||||||
|
If your site has a large number of actions scheduled to run at the same time, Action Scheduler will process more than one batch at a time. Specifically, when the `'action_scheduler_run_schedule'` hook is triggered approximately one minute after the first batch began processing, a new PHP process will stake a new claim to a batch of actions which were not claimed by the previous process. It will then begin to process that batch.
|
||||||
|
|
||||||
|
This will continue until all actions are processed using a maximum of 5 concurrent queues.
|
||||||
|
|
||||||
|
### Housekeeping
|
||||||
|
|
||||||
|
Before processing a batch, the scheduler will remove any existing claims on actions which have been sitting in a queue for more than five minutes.
|
||||||
|
|
||||||
|
Action Scheduler will also trash any actions which were completed more than a month ago.
|
||||||
|
|
||||||
|
If an action runs for more than 5 minutes, Action Scheduler will assume the action has timed out and will mark it as failed. However, if all callbacks attached to the action were to successfully complete sometime after that 5 minute timeout, its status would later be updated to completed.
|
||||||
|
|
||||||
|
### Record Keeping
|
||||||
|
|
||||||
|
Events for each action will be also logged in the [comments table](http://codex.wordpress.org/Database_Description#Table_Overview).
|
||||||
|
|
||||||
|
The events logged by default include when an action:
|
||||||
|
* is created
|
||||||
|
* starts
|
||||||
|
* completes
|
||||||
|
* fails
|
||||||
|
|
||||||
|
Actions can also be grouped together using a custom taxonomy named `action-group`.
|
||||||
|
|
||||||
|
## Managing Scheduled Actions
|
||||||
|
|
||||||
|
Action Scheduler has a built in administration screen for monitoring, debugging and manually triggering scheduled actions.
|
||||||
|
|
||||||
|
The administration interface is accesible through both:
|
||||||
|
|
||||||
|
1. **Tools > Scheduled Actions**
|
||||||
|
1. **WooCommerce > Status > Scheduled Actions**, when WooCommerce is installed.
|
||||||
|
|
||||||
|
![](https://cldup.com/5BA2BNB1sw.png)
|
||||||
|
|
||||||
|
Among other tasks, from the admin screen you can:
|
||||||
|
|
||||||
|
* run a pending action
|
||||||
|
* view the scheduled actions with a specific status, like the all actions which have failed or are in-progress (https://cldup.com/NNTwE88Xl8.png).
|
||||||
|
* view the log entries for a specific action to find out why it failed.
|
||||||
|
* sort scheduled actions by hook name, scheduled date, claim ID or group name.
|
||||||
|
|
||||||
|
Still have questions? Check out the [FAQ below](#faq).
|
||||||
|
|
||||||
|
## WP CLI
|
||||||
|
|
||||||
|
Action Scheduler has custom [WP CLI](http://wp-cli.org) commands available for processing actions.
|
||||||
|
|
||||||
|
For many sites, WP CLI is a much better choice for running queues of actions than the default WP Cron runner. These are some common cases where WP CLI is a better option:
|
||||||
|
|
||||||
|
* long-running tasks - Tasks that take a significant amount of time to run
|
||||||
|
* large queues - A large number of tasks will naturally take a longer time
|
||||||
|
* other plugins with extensive WP Cron usage - WP Cron's limited resources are spread across more tasks
|
||||||
|
|
||||||
|
With a regular web request, you may have to deal with script timeouts enforced by hosts, or other restraints that make it more challenging to run Action Scheduler tasks. Utilizing WP CLI to run commands directly on the server give you more freedom. This means that you typically don't have the same constraints of a normal web request.
|
||||||
|
|
||||||
|
If you choose to utilize WP CLI exclusively, you can disable the normal WP CLI queue runner by installing the [Action Scheduler - Disable Default Queue Runner](https://github.com/Prospress/action-scheduler-disable-default-runner) plugin. Note that if you do this, you **must** run Action Scheduler manually.
|
||||||
|
|
||||||
|
### Commands
|
||||||
|
|
||||||
|
These are the commands available to use with Action Scheduler:
|
||||||
|
|
||||||
|
* `action-scheduler run`
|
||||||
|
|
||||||
|
Options:
|
||||||
|
* `--batch-size` - This is the number of actions to run in a single batch. The default is `100`.
|
||||||
|
* `--batches` - This is the number of batches to run. Using 0 means that batches will continue running until there are no more actions to run.
|
||||||
|
* `--hooks` - Process only actions with specific hook or hooks, like `'woocommerce_scheduled_subscription_payment'`. By default, actions with any hook will be processed. Define multiple hooks as a comma separated string (without spaces), e.g. `--hooks=woocommerce_scheduled_subscription_trial_end,woocommerce_scheduled_subscription_payment,woocommerce_scheduled_subscription_expiration`
|
||||||
|
* `--group` - Process only actions in a specific group, like `'woocommerce-memberships'`. By default, actions in any group (or no group) will be processed.
|
||||||
|
* `--force` - By default, Action Scheduler limits the number of concurrent batches that can be run at once to ensure the server does not get overwhelmed. Using the `--force` flag overrides this behavior to force the WP CLI queue to run.
|
||||||
|
|
||||||
|
The best way to get a full list of commands and their available options is to use WP CLI itself. This can be done by running `wp action-scheduler` to list all Action Scheduler commands, or by including the `--help` flag with any of the individual commands. This will provide all relevant parameters and flags for the command.
|
||||||
|
|
||||||
|
### Improving Performance with `--group`
|
||||||
|
|
||||||
|
Being able to run queues for specific groups of actions is valuable at scale. Why? Because it means you can restrict the concurrency for similar actions.
|
||||||
|
|
||||||
|
For example, let's say you have 300,000 actions queued up comprised of:
|
||||||
|
|
||||||
|
* 100,000 renewals payments
|
||||||
|
* 100,000 email notifications
|
||||||
|
* 100,000 membership status updates
|
||||||
|
|
||||||
|
Action Scheduler's default WP Cron queue runner will process them all together. e.g. when it claims a batch of actions, some may be emails, some membership updates and some renewals.
|
||||||
|
|
||||||
|
When you add concurrency to that, you can end up with issues. For example, if you have 3 queues running, they may all be attempting to process similar actions at the same time, which can lead to querying the same database tables with similar queries. Depending on the code/queries running, this can lead to database locks or other issues.
|
||||||
|
|
||||||
|
If you can batch based on each action's group, then you can improve performance by processing like actions consecutively, but still processing the full set of actions concurrently.
|
||||||
|
|
||||||
|
For example, if one queue is created to process emails, another to process membership updates, and another to process renewal payments, then the same queries won't be run at the same time, and 3 separate queues will be able to run more efficiently.
|
||||||
|
|
||||||
|
The WP CLI runner can achieve this using the `--group` option.
|
||||||
|
|
||||||
|
## API Functions
|
||||||
|
|
||||||
|
### Action Scheduler API vs. WP-Cron API
|
||||||
|
|
||||||
|
The Action Scheduler API functions are designed to mirror the WordPress [WP-Cron API functions](http://codex.wordpress.org/Category:WP-Cron_Functions).
|
||||||
|
|
||||||
|
Functions return similar values and accept similar arguments to their WP-Cron counterparts. The notable differences are:
|
||||||
|
|
||||||
|
* `wc_schedule_single_action()` & `wc_schedule_recurring_action()` will return the post ID of the scheduled action rather than boolean indicating whether the event was scheduled
|
||||||
|
* `wc_schedule_recurring_action()` takes an interval in seconds as the recurring interval rather than an arbitrary string
|
||||||
|
* `wc_schedule_single_action()` & `wc_schedule_recurring_action()` can accept a `$group` parameter to group different actions for the one plugin together.
|
||||||
|
* the `wp_` prefix is substituted with `wc_` and the term `event` is replaced with `action`
|
||||||
|
|
||||||
|
|
||||||
|
#### Function Reference / `wc_schedule_single_action()`
|
||||||
|
|
||||||
|
##### Description
|
||||||
|
|
||||||
|
Schedule an action to run one time.
|
||||||
|
|
||||||
|
##### Usage
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php wc_schedule_single_action( $timestamp, $hook, $args, $group ); ?>
|
||||||
|
````
|
||||||
|
|
||||||
|
##### Parameters
|
||||||
|
|
||||||
|
- **$timestamp** (integer)(required) The Unix timestamp representing the date you want the action to run. Default: _none_.
|
||||||
|
- **$hook** (string)(required) Name of the action hook. Default: _none_.
|
||||||
|
- **$args** (array) Arguments to pass to callbacks when the hook triggers. Default: _`array()`_.
|
||||||
|
- **$group** (array) The group to assign this job to. Default: _''_.
|
||||||
|
|
||||||
|
##### Return value
|
||||||
|
|
||||||
|
(integer) the action's ID in the [posts](http://codex.wordpress.org/Database_Description#Table_Overview) table.
|
||||||
|
|
||||||
|
|
||||||
|
#### Function Reference / `wc_schedule_recurring_action()`
|
||||||
|
|
||||||
|
##### Description
|
||||||
|
|
||||||
|
Schedule an action to run repeatedly with a specified interval in seconds.
|
||||||
|
|
||||||
|
##### Usage
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php wc_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args, $group ); ?>
|
||||||
|
````
|
||||||
|
|
||||||
|
##### Parameters
|
||||||
|
|
||||||
|
- **$timestamp** (integer)(required) The Unix timestamp representing the date you want the action to run. Default: _none_.
|
||||||
|
- **$interval_in_seconds** (integer)(required) How long to wait between runs. Default: _none_.
|
||||||
|
- **$hook** (string)(required) Name of the action hook. Default: _none_.
|
||||||
|
- **$args** (array) Arguments to pass to callbacks when the hook triggers. Default: _`array()`_.
|
||||||
|
- **$group** (array) The group to assign this job to. Default: _''_.
|
||||||
|
|
||||||
|
##### Return value
|
||||||
|
|
||||||
|
(integer) the action's ID in the [posts](http://codex.wordpress.org/Database_Description#Table_Overview) table.
|
||||||
|
|
||||||
|
|
||||||
|
#### Function Reference / `wc_schedule_cron_action()`
|
||||||
|
|
||||||
|
##### Description
|
||||||
|
|
||||||
|
Schedule an action that recurs on a cron-like schedule.
|
||||||
|
|
||||||
|
##### Usage
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php wc_schedule_cron_action( $timestamp, $schedule, $hook, $args, $group ); ?>
|
||||||
|
````
|
||||||
|
|
||||||
|
##### Parameters
|
||||||
|
|
||||||
|
- **$timestamp** (integer)(required) The Unix timestamp representing the date you want the action to run. Default: _none_.
|
||||||
|
- **$schedule** (string)(required) $schedule A cron-link schedule string, see http://en.wikipedia.org/wiki/Cron. Default: _none_.
|
||||||
|
- **$hook** (string)(required) Name of the action hook. Default: _none_.
|
||||||
|
- **$args** (array) Arguments to pass to callbacks when the hook triggers. Default: _`array()`_.
|
||||||
|
- **$group** (array) The group to assign this job to. Default: _''_.
|
||||||
|
|
||||||
|
##### Return value
|
||||||
|
|
||||||
|
(integer) the action's ID in the [posts](http://codex.wordpress.org/Database_Description#Table_Overview) table.
|
||||||
|
|
||||||
|
|
||||||
|
#### Function Reference / `wc_unschedule_action()`
|
||||||
|
|
||||||
|
##### Description
|
||||||
|
|
||||||
|
Cancel the next occurrence of a job.
|
||||||
|
|
||||||
|
##### Usage
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php wc_unschedule_action( $hook, $args, $group ); ?>
|
||||||
|
````
|
||||||
|
|
||||||
|
##### Parameters
|
||||||
|
|
||||||
|
- **$hook** (string)(required) Name of the action hook. Default: _none_.
|
||||||
|
- **$args** (array) Arguments to pass to callbacks when the hook triggers. Default: _`array()`_.
|
||||||
|
- **$group** (array) The group to assign this job to. Default: _''_.
|
||||||
|
|
||||||
|
##### Return value
|
||||||
|
|
||||||
|
(null)
|
||||||
|
|
||||||
|
|
||||||
|
#### Function Reference / `wc_next_scheduled_action()`
|
||||||
|
|
||||||
|
##### Description
|
||||||
|
|
||||||
|
Returns the next timestamp for a scheduled action.
|
||||||
|
|
||||||
|
##### Usage
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php wc_next_scheduled_action( $hook, $args, $group ); ?>
|
||||||
|
````
|
||||||
|
|
||||||
|
##### Parameters
|
||||||
|
|
||||||
|
- **$hook** (string)(required) Name of the action hook. Default: _none_.
|
||||||
|
- **$args** (array) Arguments to pass to callbacks when the hook triggers. Default: _`array()`_.
|
||||||
|
- **$group** (array) The group to assign this job to. Default: _''_.
|
||||||
|
|
||||||
|
##### Return value
|
||||||
|
|
||||||
|
(integer|boolean) The timestamp for the next occurrence, or false if nothing was found.
|
||||||
|
|
||||||
|
|
||||||
|
#### Function Reference / `wc_get_scheduled_actions()`
|
||||||
|
|
||||||
|
##### Description
|
||||||
|
|
||||||
|
Find scheduled actions.
|
||||||
|
|
||||||
|
##### Usage
|
||||||
|
|
||||||
|
```php
|
||||||
|
<?php wc_get_scheduled_actions( $args, $return_format ); ?>
|
||||||
|
````
|
||||||
|
|
||||||
|
##### Parameters
|
||||||
|
|
||||||
|
- **$args** (array) Arguments to search and filter results by. Possible arguments, with their default values:
|
||||||
|
* `'hook' => ''` - the name of the action that will be triggered
|
||||||
|
* `'args' => NULL` - the args array that will be passed with the action
|
||||||
|
* `'date' => NULL` - the scheduled date of the action. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime().
|
||||||
|
* `'date_compare' => '<=`' - operator for testing "date". accepted values are '!=', '>', '>=', '<', '<=', '='
|
||||||
|
* `'modified' => NULL` - the date the action was last updated. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime().
|
||||||
|
* `'modified_compare' => '<='` - operator for testing "modified". accepted values are '!=', '>', '>=', '<', '<=', '='
|
||||||
|
* `'group' => ''` - the group the action belongs to
|
||||||
|
* `'status' => ''` - ActionScheduler_Store::STATUS_COMPLETE or ActionScheduler_Store::STATUS_PENDING
|
||||||
|
* `'claimed' => NULL` - TRUE to find claimed actions, FALSE to find unclaimed actions, a string to find a specific claim ID
|
||||||
|
* `'per_page' => 5` - Number of results to return
|
||||||
|
* `'offset' => 0`
|
||||||
|
* `'orderby' => 'date'` - accepted values are 'hook', 'group', 'modified', or 'date'
|
||||||
|
* `'order' => 'ASC'`
|
||||||
|
- **$return_format** (string) The format in which to return the scheduled actions: 'OBJECT', 'ARRAY_A', or 'ids'. Default: _'OBJECT'_.
|
||||||
|
|
||||||
|
##### Return value
|
||||||
|
|
||||||
|
(array) Array of the actions matching the criteria specified with `$args`.
|
||||||
|
|
||||||
|
|
||||||
|
## Performance Tuning
|
||||||
|
|
||||||
|
By default, Action Scheduler will process a minimum of 1,200 actions per hour. On servers which allow long running PHP processes, this will be significantly higher as processes will be able loop over queues indefinitely.
|
||||||
|
|
||||||
|
The batch size and number of concurrent queues that may be processed simultaneously is low by default to ensure the scheduler runs on low powered servers; however, you can configure these settings to increase performance on your site.
|
||||||
|
|
||||||
|
#### Increasing Batch Size
|
||||||
|
|
||||||
|
By default, Action Scheduler will claim a batch of 20 actions. This small batch size is to minimise the risk of causing a fatal error due to memory exhaustion.
|
||||||
|
|
||||||
|
If you know the callbacks attached to your actions use very little memory, or you've tested the number of actions you can process before memory limits are exceeded, you can increase the batch size using the `'action_scheduler_queue_runner_batch_size'` filter.
|
||||||
|
|
||||||
|
For example, to increase the batch size to 100, we can use the following function:
|
||||||
|
|
||||||
|
```
|
||||||
|
<?php
|
||||||
|
function eg_increase_action_scheduler_batch_size( $batch_size ) {
|
||||||
|
return 100;
|
||||||
|
}
|
||||||
|
add_filter( 'action_scheduler_queue_runner_batch_size', 'eg_increase_action_scheduler_batch_size' );
|
||||||
|
?>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Increasing Concurrent Batches
|
||||||
|
|
||||||
|
By default, Action Scheduler will run up to 5 concurrent batches of actions. This is to prevent consuming all the available connections or processes on your webserver.
|
||||||
|
|
||||||
|
However, your server may allow a large number of connection, for example, because it has a high value for Apache's `MaxClients` setting or PHP-FPM's `pm.max_children` setting.
|
||||||
|
|
||||||
|
If this is the case, you can use the `'action_scheduler_queue_runner_concurrent_batches'` filter to increase the number of conncurrent batches allowed, and therefore speed up processing large numbers of actions scheduled to be processed simultaneously.
|
||||||
|
|
||||||
|
For example, to increase the allowed number of concurrent queues to 25, we can use the following code:
|
||||||
|
|
||||||
|
```
|
||||||
|
<?php
|
||||||
|
function eg_increase_action_scheduler_concurrent_batches( $concurrent_batches ) {
|
||||||
|
return 25;
|
||||||
|
}
|
||||||
|
add_filter( 'action_scheduler_queue_runner_concurrent_batches', 'eg_increase_action_scheduler_concurrent_batches' );
|
||||||
|
?>
|
||||||
|
```
|
||||||
|
|
||||||
|
## FAQ
|
||||||
|
|
||||||
|
### Is it safe to release Action Scheduler in my plugin? Won't its functions conflict with another copy of the library?
|
||||||
|
|
||||||
|
Action Scheduler is designed to be used and released in plugins. It avoids redeclaring public API functions when more than one copy of the library is being loaded by different plugins. It will also load only the most recent version of itself (by checking registered versions after all plugins are loaded on the `'plugins_loaded'` hook).
|
||||||
|
|
||||||
|
To use it in your plugin, simply require the `action-scheduler/action-scheduler.php` file. Action Scheduler will take care of the rest.
|
||||||
|
|
||||||
|
### I don't want to use WP-Cron. Does Action Scheduler depend on WP-Cron?
|
||||||
|
|
||||||
|
By default, Action Scheduler is initiated by WP-Cron. However, it has no dependency on the WP-Cron system. You can initiate the Action Scheduler queue in other ways with just one or two lines of code.
|
||||||
|
|
||||||
|
For example, you can start a queue directly by calling:
|
||||||
|
|
||||||
|
```php
|
||||||
|
ActionScheduler::runner()->run();
|
||||||
|
```
|
||||||
|
|
||||||
|
Or trigger the `'action_scheduler_run_queue'` hook and let Action Scheduler do it for you:
|
||||||
|
|
||||||
|
```php
|
||||||
|
do_action( 'action_scheduler_run_queue' );
|
||||||
|
```
|
||||||
|
|
||||||
|
Further customization can be done by extending the `ActionScheduler_Abstract_QueueRunner` class to create a custom Queue Runner. For an example of a customized queue runner, see the [`ActionScheduler_WPCLI_QueueRunner`](https://github.com/Prospress/action-scheduler/blob/master/classes/ActionScheduler_WPCLI_QueueRunner.php), which is used when running WP CLI.
|
||||||
|
|
||||||
|
Want to create some other method for initiating Action Scheduler? [Open a new issue](https://github.com/Prospress/action-scheduler/issues/new), we'd love to help you with it.
|
||||||
|
|
||||||
|
### I don't want to use WP-Cron, ever. Does Action Scheduler replace WP-Cron?
|
||||||
|
|
||||||
|
By default, Action Scheduler is designed to work alongside WP-Cron and not change any of its behaviour. This helps avoid unexpectedly overriding WP-Cron on sites installing your plugin, which may have nothing to do with WP-Cron.
|
||||||
|
|
||||||
|
However, we can understand why you might want to replace WP-Cron completely in environments within you control, especially as it gets you the advantages of Action Scheduler. This should be possible without too much code.
|
||||||
|
|
||||||
|
You could use the `'schedule_event'` hook in WordPress to use Action Scheduler for only newly scheduled WP-Cron jobs and map the `$event` param to Action Scheduler API functions.
|
||||||
|
|
||||||
|
Alternatively, you can use a combination of the `'pre_update_option_cron'` and `'pre_option_cron'` hooks to override all new and previously scheduled WP-Cron jobs (similar to the way [Cavalcade](https://github.com/humanmade/Cavalcade) does it).
|
||||||
|
|
||||||
|
If you'd like to create a plugin to do this automatically and want to share your work with others, [open a new issue to let us know](https://github.com/Prospress/action-scheduler/issues/new), we'd love to help you with it.
|
||||||
|
|
||||||
|
### Eww gross, Custom Post Types! That's _so_ 2010. Can I use a different storage scheme?
|
||||||
|
|
||||||
|
Of course! Action Scheduler data storage is completely swappable, and always has been.
|
||||||
|
|
||||||
|
You can store scheduled actions in custom tables in the WordPress site's database. Some sites using it already are. You can actually store them anywhere for that matter, like in a remote storage service from Amazon Web Services.
|
||||||
|
|
||||||
|
To implement a custom store:
|
||||||
|
|
||||||
|
1. extend the abstract `ActionScheduler_Store` class, being careful to implement each of its methods
|
||||||
|
2. attach a callback to `'action_scheduler_store_class'` to tell Action Scheduler your class is the one which should be used to manage storage, e.g.
|
||||||
|
|
||||||
|
```
|
||||||
|
function eg_define_custom_store( $existing_storage_class ) {
|
||||||
|
return 'My_Radical_Action_Scheduler_Store';
|
||||||
|
}
|
||||||
|
add_filter( 'action_scheduler_store_class', 'eg_define_custom_store', 10, 1 );
|
||||||
|
```
|
||||||
|
|
||||||
|
Take a look at the `ActionScheduler_wpPostStore` class for an example implementation of `ActionScheduler_Store`.
|
||||||
|
|
||||||
|
If you'd like to create a plugin to do this automatically and release it publicly to help others, [open a new issue to let us know](https://github.com/Prospress/action-scheduler/issues/new), we'd love to help you with it.
|
||||||
|
|
||||||
|
> Note: we're also moving Action Scheduler itself to use [custom tables for better scalability](https://github.com/Prospress/action-scheduler/issues/77).
|
||||||
|
|
||||||
|
### Can I use a different storage scheme just for logging?
|
||||||
|
|
||||||
|
Of course! Action Scheduler's logger is completely swappable, and always has been. You can also customise where logs are stored, and the storage mechanism.
|
||||||
|
|
||||||
|
To implement a custom logger:
|
||||||
|
|
||||||
|
1. extend the abstract `ActionScheduler_Logger` class, being careful to implement each of its methods
|
||||||
|
2. attach a callback to `'action_scheduler_logger_class'` to tell Action Scheduler your class is the one which should be used to manage logging, e.g.
|
||||||
|
|
||||||
|
```
|
||||||
|
function eg_define_custom_logger( $existing_storage_class ) {
|
||||||
|
return 'My_Radical_Action_Scheduler_Logger';
|
||||||
|
}
|
||||||
|
add_filter( 'action_scheduler_logger_class', 'eg_define_custom_logger', 10, 1 );
|
||||||
|
```
|
||||||
|
|
||||||
|
Take a look at the `ActionScheduler_wpCommentLogger` class for an example implementation of `ActionScheduler_Logger`.
|
||||||
|
|
||||||
|
### I want to run Action Scheduler only on a dedicated application server in my cluster. Can I do that?
|
||||||
|
|
||||||
|
Wow, now you're really asking the tough questions. In theory, yes, this is possible. The `ActionScheduler_QueueRunner` class, which is responsible for running queues, is swappable via the `'action_scheduler_queue_runner_class'` filter.
|
||||||
|
|
||||||
|
Because of this, you can effectively customise queue running however you need. Whether that means tweaking minor things, like not using WP-Cron at all to initiate queues by overriding `ActionScheduler_QueueRunner::init()`, or completely changing how and where queues are run, by overriding `ActionScheduler_QueueRunner::run()`.
|
||||||
|
|
||||||
|
### Is Action Scheduler safe to use on my production site?
|
||||||
|
|
||||||
|
Yes, absolutely! Action Scheduler is actively used on tens of thousands of production sites already. Right now it's responsible for scheduling everything from emails to payments.
|
||||||
|
|
||||||
|
In fact, every month, Action Scheduler processes millions of payments as part of the [WooCommerce Subscriptions](https://woocommerce.com/products/woocommerce-subscriptions/) extension.
|
||||||
|
|
||||||
|
It requires no setup, and won't override any WordPress APIs (unless you want it to).
|
||||||
|
|
||||||
|
### How does Action Scheduler work on WordPress Multisite?
|
||||||
|
|
||||||
|
Action Scheduler is designed to manage the scheduled actions on a single site. It has no special handling for running queues across multiple sites in a multisite network. That said, because it's storage and Queue Runner are completely swappable, it would be possible to write multisite handling classes to use with it.
|
||||||
|
|
||||||
|
If you'd like to create a multisite plugin to do this and release it publicly to help others, [open a new issue to let us know](https://github.com/Prospress/action-scheduler/issues/new), we'd love to help you with it.
|
||||||
|
|
||||||
|
## Credits
|
||||||
|
|
||||||
|
This extension is developed and maintained as a collaboration between the teams at [Prospress](http://prospress.com/) and [Flightless](https://flightless.us/).
|
||||||
|
|
||||||
|
Collaboration is cool. We'd love to work with you to improve Action Scheduler. Pull Requests welcome.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="https://cloud.githubusercontent.com/assets/235523/11986380/bb6a0958-a983-11e5-8e9b-b9781d37c64a.png" width="160">
|
||||||
|
</p>
|
|
@ -0,0 +1,47 @@
|
||||||
|
<?php
|
||||||
|
/*
|
||||||
|
* Plugin Name: Action Scheduler
|
||||||
|
* Plugin URI: https://github.com/prospress/action-scheduler
|
||||||
|
* Description: A robust scheduling library for use in WordPress plugins.
|
||||||
|
* Author: Prospress
|
||||||
|
* Author URI: http://prospress.com/
|
||||||
|
* Version: 2.0.0
|
||||||
|
* License: GPLv3
|
||||||
|
*
|
||||||
|
* Copyright 2018 Prospress, Inc. (email : freedoms@prospress.com)
|
||||||
|
*
|
||||||
|
* 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 <http://www.gnu.org/licenses/>.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
if ( ! function_exists( 'action_scheduler_register_2_dot_0_dot_0' ) ) {
|
||||||
|
|
||||||
|
if ( ! class_exists( 'ActionScheduler_Versions' ) ) {
|
||||||
|
require_once( 'classes/ActionScheduler_Versions.php' );
|
||||||
|
add_action( 'plugins_loaded', array( 'ActionScheduler_Versions', 'initialize_latest_version' ), 1, 0 );
|
||||||
|
}
|
||||||
|
|
||||||
|
add_action( 'plugins_loaded', 'action_scheduler_register_2_dot_0_dot_0', 0, 0 );
|
||||||
|
|
||||||
|
function action_scheduler_register_2_dot_0_dot_0() {
|
||||||
|
$versions = ActionScheduler_Versions::instance();
|
||||||
|
$versions->register( '2.0.0', 'action_scheduler_initialize_2_dot_0_dot_0' );
|
||||||
|
}
|
||||||
|
|
||||||
|
function action_scheduler_initialize_2_dot_0_dot_0() {
|
||||||
|
require_once( 'classes/ActionScheduler.php' );
|
||||||
|
ActionScheduler::init( __FILE__ );
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,122 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
abstract class ActionScheduler {
|
||||||
|
private static $plugin_file = '';
|
||||||
|
/** @var ActionScheduler_ActionFactory */
|
||||||
|
private static $factory = NULL;
|
||||||
|
|
||||||
|
public static function factory() {
|
||||||
|
if ( !isset(self::$factory) ) {
|
||||||
|
self::$factory = new ActionScheduler_ActionFactory();
|
||||||
|
}
|
||||||
|
return self::$factory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function store() {
|
||||||
|
return ActionScheduler_Store::instance();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function logger() {
|
||||||
|
return ActionScheduler_Logger::instance();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function runner() {
|
||||||
|
return ActionScheduler_QueueRunner::instance();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function admin_view() {
|
||||||
|
return ActionScheduler_AdminView::instance();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the absolute system path to the plugin directory, or a file therein
|
||||||
|
* @static
|
||||||
|
* @param string $path
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public static function plugin_path( $path ) {
|
||||||
|
$base = dirname(self::$plugin_file);
|
||||||
|
if ( $path ) {
|
||||||
|
return trailingslashit($base).$path;
|
||||||
|
} else {
|
||||||
|
return untrailingslashit($base);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the absolute URL to the plugin directory, or a file therein
|
||||||
|
* @static
|
||||||
|
* @param string $path
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public static function plugin_url( $path ) {
|
||||||
|
return plugins_url($path, self::$plugin_file);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function autoload( $class ) {
|
||||||
|
$d = DIRECTORY_SEPARATOR;
|
||||||
|
if ( strpos( $class, 'ActionScheduler' ) === 0 ) {
|
||||||
|
$dir = self::plugin_path('classes'.$d);
|
||||||
|
} elseif ( strpos( $class, 'CronExpression' ) === 0 ) {
|
||||||
|
$dir = self::plugin_path('lib'.$d.'cron-expression'.$d);
|
||||||
|
} else {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( file_exists( $dir.$class.'.php' ) ) {
|
||||||
|
include( $dir.$class.'.php' );
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize the plugin
|
||||||
|
*
|
||||||
|
* @static
|
||||||
|
* @param string $plugin_file
|
||||||
|
*/
|
||||||
|
public static function init( $plugin_file ) {
|
||||||
|
self::$plugin_file = $plugin_file;
|
||||||
|
spl_autoload_register( array( __CLASS__, 'autoload' ) );
|
||||||
|
|
||||||
|
$store = self::store();
|
||||||
|
add_action( 'init', array( $store, 'init' ), 1, 0 );
|
||||||
|
|
||||||
|
$logger = self::logger();
|
||||||
|
add_action( 'init', array( $logger, 'init' ), 1, 0 );
|
||||||
|
|
||||||
|
$runner = self::runner();
|
||||||
|
add_action( 'init', array( $runner, 'init' ), 1, 0 );
|
||||||
|
|
||||||
|
$admin_view = self::admin_view();
|
||||||
|
add_action( 'init', array( $admin_view, 'init' ), 0, 0 ); // run before $store::init()
|
||||||
|
|
||||||
|
require_once( self::plugin_path('functions.php') );
|
||||||
|
|
||||||
|
if ( defined( 'WP_CLI' ) && WP_CLI ) {
|
||||||
|
WP_CLI::add_command( 'action-scheduler', 'ActionScheduler_WPCLI_Scheduler_command' );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
final public function __clone() {
|
||||||
|
trigger_error("Singleton. No cloning allowed!", E_USER_ERROR);
|
||||||
|
}
|
||||||
|
|
||||||
|
final public function __wakeup() {
|
||||||
|
trigger_error("Singleton. No serialization allowed!", E_USER_ERROR);
|
||||||
|
}
|
||||||
|
|
||||||
|
final private function __construct() {}
|
||||||
|
|
||||||
|
/** Deprecated **/
|
||||||
|
|
||||||
|
public static function get_datetime_object( $when = null, $timezone = 'UTC' ) {
|
||||||
|
_deprecated_function( __METHOD__, '2.0', 'wcs_add_months()' );
|
||||||
|
return as_get_datetime_object( $when, $timezone );
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,656 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
if ( ! class_exists( 'WP_List_Table' ) ) {
|
||||||
|
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Action Scheduler Abstract List Table class
|
||||||
|
*
|
||||||
|
* This abstract class enhances WP_List_Table making it ready to use.
|
||||||
|
*
|
||||||
|
* By extending this class we can focus on describing how our table looks like,
|
||||||
|
* which columns needs to be shown, filter, ordered by and more and forget about the details.
|
||||||
|
*
|
||||||
|
* This class supports:
|
||||||
|
* - Bulk actions
|
||||||
|
* - Search
|
||||||
|
* - Sortable columns
|
||||||
|
* - Automatic translations of the columns
|
||||||
|
*
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
* @since 2.0.0
|
||||||
|
*/
|
||||||
|
abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The table name
|
||||||
|
*/
|
||||||
|
protected $table_name;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Package name, used in translations
|
||||||
|
*/
|
||||||
|
protected $package;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How many items do we render per page?
|
||||||
|
*/
|
||||||
|
protected $items_per_page = 10;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enables search in this table listing. If this array
|
||||||
|
* is empty it means the listing is not searchable.
|
||||||
|
*/
|
||||||
|
protected $search_by = array();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Columns to show in the table listing. It is a key => value pair. The
|
||||||
|
* key must much the table column name and the value is the label, which is
|
||||||
|
* automatically translated.
|
||||||
|
*/
|
||||||
|
protected $columns = array();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Defines the row-actions. It expects an array where the key
|
||||||
|
* is the column name and the value is an array of actions.
|
||||||
|
*
|
||||||
|
* The array of actions are key => value, where key is the method name
|
||||||
|
* (with the prefix row_action_<key>) and the value is the label
|
||||||
|
* and title.
|
||||||
|
*/
|
||||||
|
protected $row_actions = array();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Primary key of our table
|
||||||
|
*/
|
||||||
|
protected $ID = 'ID';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enables sorting, it expects an array
|
||||||
|
* of columns (the column names are the values)
|
||||||
|
*/
|
||||||
|
protected $sort_by = array();
|
||||||
|
|
||||||
|
protected $filter_by = array();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array The status name => count combinations for this table's items. Used to display status filters.
|
||||||
|
*/
|
||||||
|
protected $status_counts = array();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array Notices to display when loading the table. Array of arrays of form array( 'class' => {updated|error}, 'message' => 'This is the notice text display.' ).
|
||||||
|
*/
|
||||||
|
protected $admin_notices = array();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var string Localised string displayed in the <h1> element above the able.
|
||||||
|
*/
|
||||||
|
protected $table_header;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enables bulk actions. It must be an array where the key is the action name
|
||||||
|
* and the value is the label (which is translated automatically). It is important
|
||||||
|
* to notice that it will check that the method exists (`bulk_$name`) and will throw
|
||||||
|
* an exception if it does not exists.
|
||||||
|
*
|
||||||
|
* This class will automatically check if the current request has a bulk action, will do the
|
||||||
|
* validations and afterwards will execute the bulk method, with two arguments. The first argument
|
||||||
|
* is the array with primary keys, the second argument is a string with a list of the primary keys,
|
||||||
|
* escaped and ready to use (with `IN`).
|
||||||
|
*/
|
||||||
|
protected $bulk_actions = array();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Makes translation easier, it basically just wraps
|
||||||
|
* `_x` with some default (the package name)
|
||||||
|
*/
|
||||||
|
protected function translate( $text, $context = '' ) {
|
||||||
|
return _x( $text, $context, $this->package );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads `$this->bulk_actions` and returns an array that WP_List_Table understands. It
|
||||||
|
* also validates that the bulk method handler exists. It throws an exception because
|
||||||
|
* this is a library meant for developers and missing a bulk method is a development-time error.
|
||||||
|
*/
|
||||||
|
protected function get_bulk_actions() {
|
||||||
|
$actions = array();
|
||||||
|
|
||||||
|
foreach ( $this->bulk_actions as $action => $label ) {
|
||||||
|
if ( ! is_callable( array( $this, 'bulk_' . $action ) ) ) {
|
||||||
|
throw new RuntimeException( "The bulk action $action does not have a callback method" );
|
||||||
|
}
|
||||||
|
|
||||||
|
$actions[ $action ] = $this->translate( $label );
|
||||||
|
}
|
||||||
|
|
||||||
|
return $actions;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if the current request has a bulk action. If that is the case it will validate and will
|
||||||
|
* execute the bulk method handler. Regardless if the action is valid or not it will redirect to
|
||||||
|
* the previous page removing the current arguments that makes this request a bulk action.
|
||||||
|
*/
|
||||||
|
protected function process_bulk_action() {
|
||||||
|
global $wpdb;
|
||||||
|
// Detect when a bulk action is being triggered.
|
||||||
|
$action = $this->current_action();
|
||||||
|
|
||||||
|
if ( ! $action ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
check_admin_referer( 'bulk-' . $this->_args['plural'] );
|
||||||
|
|
||||||
|
$method = 'bulk_' . $action;
|
||||||
|
if ( array_key_exists( $action, $this->bulk_actions ) && is_callable( array( $this, $method ) ) && ! empty( $_GET['ID'] ) && is_array( $_GET['ID'] ) ) {
|
||||||
|
$ids_sql = '(' . implode( ',', array_fill( 0, count( $_GET['ID'] ), '%s' ) ) . ')';
|
||||||
|
$this->$method( $_GET['ID'], $wpdb->prepare( $ids_sql, $_GET['ID'] ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
wp_redirect( remove_query_arg(
|
||||||
|
array( '_wp_http_referer', '_wpnonce', 'ID', 'action', 'action2' ),
|
||||||
|
wp_unslash( $_SERVER['REQUEST_URI'] )
|
||||||
|
) );
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default code for deleting entries. We trust ids_sql because it is
|
||||||
|
* validated already by process_bulk_action()
|
||||||
|
*/
|
||||||
|
protected function bulk_delete( array $ids, $ids_sql ) {
|
||||||
|
global $wpdb;
|
||||||
|
|
||||||
|
$wpdb->query( "DELETE FROM {$this->table_name} WHERE {$this->ID} IN $ids_sql" );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepares the _column_headers property which is used by WP_Table_List at rendering.
|
||||||
|
* It merges the columns and the sortable columns.
|
||||||
|
*/
|
||||||
|
protected function prepare_column_headers() {
|
||||||
|
$this->_column_headers = array(
|
||||||
|
$this->get_columns(),
|
||||||
|
array(),
|
||||||
|
$this->get_sortable_columns(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads $this->sort_by and returns the columns name in a format that WP_Table_List
|
||||||
|
* expects
|
||||||
|
*/
|
||||||
|
public function get_sortable_columns() {
|
||||||
|
$sort_by = array();
|
||||||
|
foreach ( $this->sort_by as $column ) {
|
||||||
|
$sort_by[ $column ] = array( $column, true );
|
||||||
|
}
|
||||||
|
return $sort_by;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the columns names for rendering. It adds a checkbox for selecting everything
|
||||||
|
* as the first column
|
||||||
|
*/
|
||||||
|
public function get_columns() {
|
||||||
|
$columns = array_merge(
|
||||||
|
array( 'cb' => '<input type="checkbox" />' ),
|
||||||
|
array_map( array( $this, 'translate' ), $this->columns )
|
||||||
|
);
|
||||||
|
|
||||||
|
return $columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get prepared LIMIT clause for items query
|
||||||
|
*
|
||||||
|
* @global wpdb $wpdb
|
||||||
|
*
|
||||||
|
* @return string Prepared LIMIT clause for items query.
|
||||||
|
*/
|
||||||
|
protected function get_items_query_limit() {
|
||||||
|
global $wpdb;
|
||||||
|
|
||||||
|
$per_page = $this->get_items_per_page( $this->package . '_items_per_page', $this->items_per_page );
|
||||||
|
return $wpdb->prepare( 'LIMIT %d', $per_page );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the number of items to offset/skip for this current view.
|
||||||
|
*
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
protected function get_items_offset() {
|
||||||
|
$per_page = $this->get_items_per_page( $this->package . '_items_per_page', $this->items_per_page );
|
||||||
|
$current_page = $this->get_pagenum();
|
||||||
|
if ( 1 < $current_page ) {
|
||||||
|
$offset = $per_page * ( $current_page - 1 );
|
||||||
|
} else {
|
||||||
|
$offset = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get prepared OFFSET clause for items query
|
||||||
|
*
|
||||||
|
* @global wpdb $wpdb
|
||||||
|
*
|
||||||
|
* @return string Prepared OFFSET clause for items query.
|
||||||
|
*/
|
||||||
|
protected function get_items_query_offset() {
|
||||||
|
global $wpdb;
|
||||||
|
|
||||||
|
return $wpdb->prepare( 'OFFSET %d', $this->get_items_offset() );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepares the ORDER BY sql statement. It uses `$this->sort_by` to know which
|
||||||
|
* columns are sortable. This requests validates the orderby $_GET parameter is a valid
|
||||||
|
* column and sortable. It will also use order (ASC|DESC) using DESC by default.
|
||||||
|
*/
|
||||||
|
protected function get_items_query_order() {
|
||||||
|
if ( empty( $this->sort_by ) ) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
$orderby = esc_sql( $this->get_request_orderby() );
|
||||||
|
$order = esc_sql( $this->get_request_order() );
|
||||||
|
|
||||||
|
return "ORDER BY {$orderby} {$order}";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the sortable column specified for this request to order the results by, if any.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function get_request_orderby() {
|
||||||
|
|
||||||
|
$valid_sortable_columns = array_values( $this->sort_by );
|
||||||
|
|
||||||
|
if ( ! empty( $_GET['orderby'] ) && in_array( $_GET['orderby'], $valid_sortable_columns ) ) {
|
||||||
|
$orderby = wc_clean( $_GET['orderby'] );
|
||||||
|
} else {
|
||||||
|
$orderby = $valid_sortable_columns[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $orderby;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the sortable column order specified for this request.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function get_request_order() {
|
||||||
|
|
||||||
|
if ( ! empty( $_GET['order'] ) && 'desc' === strtolower( $_GET['order'] ) ) {
|
||||||
|
$order = 'DESC';
|
||||||
|
} else {
|
||||||
|
$order = 'ASC';
|
||||||
|
}
|
||||||
|
|
||||||
|
return $order;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the status filter for this request, if any.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function get_request_status() {
|
||||||
|
$status = ( ! empty( $_GET['status'] ) ) ? $_GET['status'] : '';
|
||||||
|
return $status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the search filter for this request, if any.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function get_request_search_query() {
|
||||||
|
$search_query = ( ! empty( $_GET['s'] ) ) ? $_GET['s'] : '';
|
||||||
|
return $search_query;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process and return the columns name. This is meant for using with SQL, this means it
|
||||||
|
* always includes the primary key.
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
protected function get_table_columns() {
|
||||||
|
$columns = array_keys( $this->columns );
|
||||||
|
if ( ! in_array( $this->ID, $columns ) ) {
|
||||||
|
$columns[] = $this->ID;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the current request is doing a "full text" search. If that is the case
|
||||||
|
* prepares the SQL to search texts using LIKE.
|
||||||
|
*
|
||||||
|
* If the current request does not have any search or if this list table does not support
|
||||||
|
* that feature it will return an empty string.
|
||||||
|
*
|
||||||
|
* TODO:
|
||||||
|
* - Improve search doing LIKE by word rather than by phrases.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function get_items_query_search() {
|
||||||
|
global $wpdb;
|
||||||
|
|
||||||
|
if ( empty( $_GET['s'] ) || empty( $this->search_by ) ) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
$filter = array();
|
||||||
|
foreach ( $this->search_by as $column ) {
|
||||||
|
$filter[] = '`' . $column . '` like "%' . $wpdb->esc_like( $_GET['s'] ) . '%"';
|
||||||
|
}
|
||||||
|
return implode( ' OR ', $filter );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepares the SQL to filter rows by the options defined at `$this->filter_by`. Before trusting
|
||||||
|
* any data sent by the user it validates that it is a valid option.
|
||||||
|
*/
|
||||||
|
protected function get_items_query_filters() {
|
||||||
|
global $wpdb;
|
||||||
|
|
||||||
|
if ( ! $this->filter_by || empty( $_GET['filter_by'] ) || ! is_array( $_GET['filter_by'] ) ) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
$filter = array();
|
||||||
|
|
||||||
|
foreach ( $this->filter_by as $column => $options ) {
|
||||||
|
if ( empty( $_GET['filter_by'][ $column ] ) || empty( $options[ $_GET['filter_by'][ $column ] ] ) ) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$filter[] = $wpdb->prepare( "`$column` = %s", $_GET['filter_by'][ $column ] );
|
||||||
|
}
|
||||||
|
|
||||||
|
return implode( ' AND ', $filter );
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prepares the data to feed WP_Table_List.
|
||||||
|
*
|
||||||
|
* This has the core for selecting, sorting and filting data. To keep the code simple
|
||||||
|
* its logic is split among many methods (get_items_query_*).
|
||||||
|
*
|
||||||
|
* Beside populating the items this function will also count all the records that matches
|
||||||
|
* the filtering criteria and will do fill the pagination variables.
|
||||||
|
*/
|
||||||
|
public function prepare_items() {
|
||||||
|
global $wpdb;
|
||||||
|
|
||||||
|
$this->process_bulk_action();
|
||||||
|
|
||||||
|
$this->process_row_actions();
|
||||||
|
|
||||||
|
if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
|
||||||
|
// _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter
|
||||||
|
wp_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->prepare_column_headers();
|
||||||
|
|
||||||
|
$limit = $this->get_items_query_limit();
|
||||||
|
$offset = $this->get_items_query_offset();
|
||||||
|
$order = $this->get_items_query_order();
|
||||||
|
$where = array_filter(array(
|
||||||
|
$this->get_items_query_search(),
|
||||||
|
$this->get_items_query_filters(),
|
||||||
|
));
|
||||||
|
$columns = '`' . implode( '`, `', $this->get_table_columns() ) . '`';
|
||||||
|
|
||||||
|
if ( ! empty( $where ) ) {
|
||||||
|
$where = 'WHERE ('. implode( ') AND (', $where ) . ')';
|
||||||
|
} else {
|
||||||
|
$where = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
$sql = "SELECT $columns FROM {$this->table_name} {$where} {$order} {$limit} {$offset}";
|
||||||
|
|
||||||
|
$this->set_items( $wpdb->get_results( $sql, ARRAY_A ) );
|
||||||
|
|
||||||
|
$query_count = "SELECT COUNT({$this->ID}) FROM {$this->table_name} {$where}";
|
||||||
|
$total_items = $wpdb->get_var( $query_count );
|
||||||
|
$per_page = $this->get_items_per_page( $this->package . '_items_per_page', $this->items_per_page );
|
||||||
|
$this->set_pagination_args( array(
|
||||||
|
'total_items' => $total_items,
|
||||||
|
'per_page' => $per_page,
|
||||||
|
'total_pages' => ceil( $total_items / $per_page ),
|
||||||
|
) );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function extra_tablenav( $which ) {
|
||||||
|
if ( ! $this->filter_by || 'top' !== $which ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
echo '<div class="alignleft actions">';
|
||||||
|
|
||||||
|
foreach ( $this->filter_by as $id => $options ) {
|
||||||
|
$default = ! empty( $_GET['filter_by'][ $id ] ) ? $_GET['filter_by'][ $id ] : '';
|
||||||
|
if ( empty( $options[ $default ] ) ) {
|
||||||
|
$default = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
echo '<select name="filter_by[' . esc_attr( $id ) . ']" class="first" id="filter-by-' . esc_attr( $id ) . '">';
|
||||||
|
|
||||||
|
foreach ( $options as $value => $label ) {
|
||||||
|
echo '<option value="' . esc_attr( $value ) . '" ' . esc_html( $value == $default ? 'selected' : '' ) .'>'
|
||||||
|
. esc_html( $this->translate( $label ) )
|
||||||
|
. '</option>';
|
||||||
|
}
|
||||||
|
|
||||||
|
echo '</select>';
|
||||||
|
}
|
||||||
|
|
||||||
|
submit_button( $this->translate( 'Filter' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
|
||||||
|
echo '</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the data for displaying. It will attempt to unserialize (There is a chance that some columns
|
||||||
|
* are serialized). This can be override in child classes for futher data transformation.
|
||||||
|
*/
|
||||||
|
protected function set_items( array $items ) {
|
||||||
|
$this->items = array();
|
||||||
|
foreach ( $items as $item ) {
|
||||||
|
$this->items[ $item[ $this->ID ] ] = array_map( 'maybe_unserialize', $item );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders the checkbox for each row, this is the first column and it is named ID regardless
|
||||||
|
* of how the primary key is named (to keep the code simpler). The bulk actions will do the proper
|
||||||
|
* name transformation though using `$this->ID`.
|
||||||
|
*/
|
||||||
|
public function column_cb( $row ) {
|
||||||
|
return '<input name="ID[]" type="checkbox" value="' . esc_attr( $row[ $this->ID ] ) .'" />';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders the row-actions.
|
||||||
|
*
|
||||||
|
* This method renders the action menu, it reads the definition from the $row_actions property,
|
||||||
|
* and it checks that the row action method exists before rendering it.
|
||||||
|
*
|
||||||
|
* @param array $row Row to render
|
||||||
|
* @param $column_name Current row
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
protected function maybe_render_actions( $row, $column_name ) {
|
||||||
|
if ( empty( $this->row_actions[ $column_name ] ) ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$row_id = $row[ $this->ID ];
|
||||||
|
|
||||||
|
$actions = '<div class="row-actions">';
|
||||||
|
$action_count = 0;
|
||||||
|
foreach ( $this->row_actions[ $column_name ] as $action_key => $action ) {
|
||||||
|
|
||||||
|
$action_count++;
|
||||||
|
|
||||||
|
if ( ! method_exists( $this, 'row_action_' . $action_key ) ) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$action_link = ! empty( $action['link'] ) ? $action['link'] : add_query_arg( array( 'row_action' => $action_key, 'row_id' => $row_id, 'nonce' => wp_create_nonce( $action_key . '::' . $row_id ) ) );
|
||||||
|
$span_class = ! empty( $action['class'] ) ? $action['class'] : $action_key;
|
||||||
|
$separator = ( $action_count < count( $this->row_actions[ $column_name ] ) ) ? ' | ' : '';
|
||||||
|
|
||||||
|
$actions .= sprintf( '<span class="%s">', esc_attr( $span_class ) );
|
||||||
|
$actions .= sprintf( '<a href="%1$s" title="%2$s">%3$s</a>', esc_url( $action_link ), esc_attr( $action['desc'] ), esc_html( $action['name'] ) );
|
||||||
|
$actions .= sprintf( '%s</span>', $separator );
|
||||||
|
}
|
||||||
|
$actions .= '</div>';
|
||||||
|
return $actions;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function process_row_actions() {
|
||||||
|
$parameters = array( 'row_action', 'row_id', 'nonce' );
|
||||||
|
foreach ( $parameters as $parameter ) {
|
||||||
|
if ( empty( $_REQUEST[ $parameter ] ) ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$method = 'row_action_' . $_REQUEST['row_action'];
|
||||||
|
|
||||||
|
if ( $_REQUEST['nonce'] === wp_create_nonce( $_REQUEST[ 'row_action' ] . '::' . $_REQUEST[ 'row_id' ] ) && method_exists( $this, $method ) ) {
|
||||||
|
$this->$method( $_REQUEST['row_id'] );
|
||||||
|
}
|
||||||
|
|
||||||
|
wp_redirect( remove_query_arg(
|
||||||
|
array( 'row_id', 'row_action', 'nonce' ),
|
||||||
|
wp_unslash( $_SERVER['REQUEST_URI'] )
|
||||||
|
) );
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default column formatting, it will escape everythig for security.
|
||||||
|
*/
|
||||||
|
public function column_default( $item, $column_name ) {
|
||||||
|
$column_html = esc_html( $item[ $column_name ] );
|
||||||
|
$column_html .= $this->maybe_render_actions( $item, $column_name );
|
||||||
|
return $column_html;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Display the table heading and search query, if any
|
||||||
|
*/
|
||||||
|
protected function display_header() {
|
||||||
|
echo '<h1 class="wp-heading-inline">' . esc_attr( $this->table_header ) . '</h1>';
|
||||||
|
if ( $this->get_request_search_query() ) {
|
||||||
|
echo '<span class="subtitle">' . esc_attr( $this->translate( sprintf( 'Search results for "%s"', $this->get_request_search_query() ) ) ) . '</span>';
|
||||||
|
}
|
||||||
|
echo '<hr class="wp-header-end">';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Display the table heading and search query, if any
|
||||||
|
*/
|
||||||
|
protected function display_admin_notices() {
|
||||||
|
foreach ( $this->admin_notices as $notice ) {
|
||||||
|
echo '<div id="message" class="' . $notice['class'] . '">';
|
||||||
|
echo ' <p>' . wp_kses_post( $notice['message'] ) . '</p>';
|
||||||
|
echo '</div>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prints the available statuses so the user can click to filter.
|
||||||
|
*/
|
||||||
|
protected function display_filter_by_status() {
|
||||||
|
|
||||||
|
$status_list_items = array();
|
||||||
|
$request_status = $this->get_request_status();
|
||||||
|
|
||||||
|
// Helper to set 'all' filter when not set on status counts passed in
|
||||||
|
if ( ! isset( $this->status_counts['all'] ) ) {
|
||||||
|
$this->status_counts = array( 'all' => array_sum( $this->status_counts ) ) + $this->status_counts;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ( $this->status_counts as $status_name => $count ) {
|
||||||
|
|
||||||
|
if ( 0 === $count ) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( $status_name === $request_status || ( empty( $request_status ) && 'all' === $status_name ) ) {
|
||||||
|
$status_list_item = '<li class="%1$s"><strong>%3$s</strong> (%4$d)</li>';
|
||||||
|
} else {
|
||||||
|
$status_list_item = '<li class="%1$s"><a href="%2$s">%3$s</a> (%4$d)</li>';
|
||||||
|
}
|
||||||
|
|
||||||
|
$status_filter_url = ( 'all' === $status_name ) ? remove_query_arg( 'status' ) : add_query_arg( 'status', $status_name );
|
||||||
|
$status_list_items[] = sprintf( $status_list_item, esc_attr( $status_name ), esc_url( $status_filter_url ), esc_html( ucfirst( $status_name ) ), absint( $count ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( $status_list_items ) {
|
||||||
|
echo '<ul class="subsubsub">';
|
||||||
|
echo implode( " | \n", $status_list_items );
|
||||||
|
echo '</ul>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders the table list, we override the original class to render the table inside a form
|
||||||
|
* and to render any needed HTML (like the search box). By doing so the callee of a function can simple
|
||||||
|
* forget about any extra HTML.
|
||||||
|
*/
|
||||||
|
protected function display_table() {
|
||||||
|
echo '<form id="' . esc_attr( $this->_args['plural'] ) . '-filter" method="get">';
|
||||||
|
foreach ( $_GET as $key => $value ) {
|
||||||
|
if ( '_' === $key[0] || 'paged' === $key ) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
echo '<input type="hidden" name="' . esc_attr( $key ) . '" value="' . esc_attr( $value ) . '" />';
|
||||||
|
}
|
||||||
|
if ( ! empty( $this->search_by ) ) {
|
||||||
|
echo $this->search_box( $this->get_search_box_button_text(), 'plugin' ); // WPCS: XSS OK
|
||||||
|
}
|
||||||
|
parent::display();
|
||||||
|
echo '</form>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render the list table page, including header, notices, status filters and table.
|
||||||
|
*/
|
||||||
|
public function display_page() {
|
||||||
|
$this->prepare_items();
|
||||||
|
|
||||||
|
echo '<div class="wrap">';
|
||||||
|
$this->display_header();
|
||||||
|
$this->display_admin_notices();
|
||||||
|
$this->display_filter_by_status();
|
||||||
|
$this->display_table();
|
||||||
|
echo '</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the text to display in the search box on the list table.
|
||||||
|
*/
|
||||||
|
protected function get_search_box_placeholder() {
|
||||||
|
return $this->translate( 'Search' );
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,89 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Abstract class with common Queue Cleaner functionality.
|
||||||
|
*/
|
||||||
|
abstract class ActionScheduler_Abstract_QueueRunner {
|
||||||
|
|
||||||
|
/** @var ActionScheduler_QueueCleaner */
|
||||||
|
protected $cleaner;
|
||||||
|
|
||||||
|
/** @var ActionScheduler_FatalErrorMonitor */
|
||||||
|
protected $monitor;
|
||||||
|
|
||||||
|
/** @var ActionScheduler_Store */
|
||||||
|
protected $store;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ActionScheduler_Abstract_QueueRunner constructor.
|
||||||
|
*
|
||||||
|
* @param ActionScheduler_Store $store
|
||||||
|
* @param ActionScheduler_FatalErrorMonitor $monitor
|
||||||
|
* @param ActionScheduler_QueueCleaner $cleaner
|
||||||
|
*/
|
||||||
|
public function __construct( ActionScheduler_Store $store = null, ActionScheduler_FatalErrorMonitor $monitor = null, ActionScheduler_QueueCleaner $cleaner = null ) {
|
||||||
|
$this->store = $store ? $store : ActionScheduler_Store::instance();
|
||||||
|
$this->monitor = $monitor ? $monitor : new ActionScheduler_FatalErrorMonitor( $this->store );
|
||||||
|
$this->cleaner = $cleaner ? $cleaner : new ActionScheduler_QueueCleaner( $this->store );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process an individual action.
|
||||||
|
*
|
||||||
|
* @param int $action_id The action ID to process.
|
||||||
|
*/
|
||||||
|
public function process_action( $action_id ) {
|
||||||
|
try {
|
||||||
|
do_action( 'action_scheduler_before_execute', $action_id );
|
||||||
|
$action = $this->store->fetch_action( $action_id );
|
||||||
|
$this->store->log_execution( $action_id );
|
||||||
|
$action->execute();
|
||||||
|
do_action( 'action_scheduler_after_execute', $action_id );
|
||||||
|
$this->store->mark_complete( $action_id );
|
||||||
|
} catch ( Exception $e ) {
|
||||||
|
$this->store->mark_failure( $action_id );
|
||||||
|
do_action( 'action_scheduler_failed_execution', $action_id, $e );
|
||||||
|
}
|
||||||
|
$this->schedule_next_instance( $action );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedule the next instance of the action if necessary.
|
||||||
|
*
|
||||||
|
* @param ActionScheduler_Action $action
|
||||||
|
*/
|
||||||
|
protected function schedule_next_instance( ActionScheduler_Action $action ) {
|
||||||
|
$schedule = $action->get_schedule();
|
||||||
|
$next = $schedule->next( as_get_datetime_object() );
|
||||||
|
|
||||||
|
if ( ! is_null( $next ) && $schedule->is_recurring() ) {
|
||||||
|
$this->store->save_action( $action, $next );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run the queue cleaner.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
*/
|
||||||
|
protected function run_cleanup() {
|
||||||
|
$this->cleaner->clean();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the number of concurrent batches a runner allows.
|
||||||
|
*
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
public function get_allowed_concurrent_batches() {
|
||||||
|
return apply_filters( 'action_scheduler_queue_runner_concurrent_batches', 5 );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process actions in the queue.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
* @return int The number of actions processed.
|
||||||
|
*/
|
||||||
|
abstract public function run();
|
||||||
|
}
|
|
@ -0,0 +1,75 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_Action
|
||||||
|
*/
|
||||||
|
class ActionScheduler_Action {
|
||||||
|
protected $hook = '';
|
||||||
|
protected $args = array();
|
||||||
|
/** @var ActionScheduler_Schedule */
|
||||||
|
protected $schedule = NULL;
|
||||||
|
protected $group = '';
|
||||||
|
|
||||||
|
public function __construct( $hook, array $args = array(), ActionScheduler_Schedule $schedule = NULL, $group = '' ) {
|
||||||
|
$schedule = empty( $schedule ) ? new ActionScheduler_NullSchedule() : $schedule;
|
||||||
|
$this->set_hook($hook);
|
||||||
|
$this->set_schedule($schedule);
|
||||||
|
$this->set_args($args);
|
||||||
|
$this->set_group($group);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function execute() {
|
||||||
|
return do_action_ref_array($this->get_hook(), $this->get_args());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $hook
|
||||||
|
*/
|
||||||
|
protected function set_hook( $hook ) {
|
||||||
|
$this->hook = $hook;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function get_hook() {
|
||||||
|
return $this->hook;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function set_schedule( ActionScheduler_Schedule $schedule ) {
|
||||||
|
$this->schedule = $schedule;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return ActionScheduler_Schedule
|
||||||
|
*/
|
||||||
|
public function get_schedule() {
|
||||||
|
return $this->schedule;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function set_args( array $args ) {
|
||||||
|
$this->args = $args;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function get_args() {
|
||||||
|
return $this->args;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $group
|
||||||
|
*/
|
||||||
|
protected function set_group( $group ) {
|
||||||
|
$this->group = $group;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function get_group() {
|
||||||
|
return $this->group;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return bool If the action has been finished
|
||||||
|
*/
|
||||||
|
public function is_finished() {
|
||||||
|
return FALSE;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,23 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_ActionClaim
|
||||||
|
*/
|
||||||
|
class ActionScheduler_ActionClaim {
|
||||||
|
private $id = '';
|
||||||
|
private $action_ids = array();
|
||||||
|
|
||||||
|
public function __construct( $id, array $action_ids ) {
|
||||||
|
$this->id = $id;
|
||||||
|
$this->action_ids = $action_ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function get_id() {
|
||||||
|
return $this->id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function get_actions() {
|
||||||
|
return $this->action_ids;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,111 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_ActionFactory
|
||||||
|
*/
|
||||||
|
class ActionScheduler_ActionFactory {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @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 $schedule The action's schedule
|
||||||
|
* @param string $group A group to put the action in
|
||||||
|
*
|
||||||
|
* @return ActionScheduler_Action An instance of the stored action
|
||||||
|
*/
|
||||||
|
public function get_stored_action( $status, $hook, array $args = array(), ActionScheduler_Schedule $schedule = null, $group = '' ) {
|
||||||
|
|
||||||
|
switch ( $status ) {
|
||||||
|
case ActionScheduler_Store::STATUS_PENDING :
|
||||||
|
$action_class = 'ActionScheduler_Action';
|
||||||
|
break;
|
||||||
|
case ActionScheduler_Store::STATUS_CANCELED :
|
||||||
|
$action_class = 'ActionScheduler_CanceledAction';
|
||||||
|
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 );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
return apply_filters( 'action_scheduler_stored_action_instance', $action, $hook, $args, $schedule, $group );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @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 string The ID of the stored action
|
||||||
|
*/
|
||||||
|
public function single( $hook, $args = array(), $when = null, $group = '' ) {
|
||||||
|
$date = as_get_datetime_object( $when );
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule( $date );
|
||||||
|
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
|
||||||
|
return $this->store( $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 $first Unix timestamp for the first run
|
||||||
|
* @param int $interval Seconds between runs
|
||||||
|
* @param string $group A group to put the action in
|
||||||
|
*
|
||||||
|
* @return string The ID of the stored action
|
||||||
|
*/
|
||||||
|
public function recurring( $hook, $args = array(), $first = null, $interval = null, $group = '' ) {
|
||||||
|
if ( empty($interval) ) {
|
||||||
|
return $this->single( $hook, $args, $first, $group );
|
||||||
|
}
|
||||||
|
$date = as_get_datetime_object( $first );
|
||||||
|
$schedule = new ActionScheduler_IntervalSchedule( $date, $interval );
|
||||||
|
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
|
||||||
|
return $this->store( $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 $first Unix timestamp for the first run
|
||||||
|
* @param int $schedule A cron definition string
|
||||||
|
* @param string $group A group to put the action in
|
||||||
|
*
|
||||||
|
* @return string The ID of the stored action
|
||||||
|
*/
|
||||||
|
public function cron( $hook, $args = array(), $first = null, $schedule = null, $group = '' ) {
|
||||||
|
if ( empty($schedule) ) {
|
||||||
|
return $this->single( $hook, $args, $first, $group );
|
||||||
|
}
|
||||||
|
$date = as_get_datetime_object( $first );
|
||||||
|
$cron = CronExpression::factory( $schedule );
|
||||||
|
$schedule = new ActionScheduler_CronSchedule( $date, $cron );
|
||||||
|
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
|
||||||
|
return $this->store( $action );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param ActionScheduler_Action $action
|
||||||
|
*
|
||||||
|
* @return string The ID of the stored action
|
||||||
|
*/
|
||||||
|
protected function store( ActionScheduler_Action $action ) {
|
||||||
|
$store = ActionScheduler_Store::instance();
|
||||||
|
return $store->save_action( $action );
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,78 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_AdminView
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {
|
||||||
|
|
||||||
|
private static $admin_view = NULL;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return ActionScheduler_QueueRunner
|
||||||
|
* @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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
public function init() {
|
||||||
|
if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || false == DOING_AJAX ) ) {
|
||||||
|
|
||||||
|
if ( class_exists( 'WooCommerce' ) ) {
|
||||||
|
add_action( 'woocommerce_admin_status_content_action-scheduler', array( $this, 'render_admin_ui' ) );
|
||||||
|
add_filter( 'woocommerce_admin_status_tabs', array( $this, 'register_system_status_tab' ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
add_action( 'admin_menu', array( $this, 'register_menu' ) );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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() {
|
||||||
|
add_submenu_page(
|
||||||
|
'tools.php',
|
||||||
|
__( 'Scheduled Actions', 'action-scheduler' ),
|
||||||
|
__( 'Scheduled Actions', 'action-scheduler' ),
|
||||||
|
'manage_options',
|
||||||
|
'action-scheduler',
|
||||||
|
array( $this, 'render_admin_ui' )
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders the Admin UI
|
||||||
|
*/
|
||||||
|
public function render_admin_ui() {
|
||||||
|
$table = new ActionScheduler_ListTable( ActionScheduler::store(), ActionScheduler::logger(), ActionScheduler::runner() );
|
||||||
|
$table->display_page();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,147 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_AdminView_Deprecated
|
||||||
|
*
|
||||||
|
* Store deprecated public functions previously found in the ActionScheduler_AdminView class.
|
||||||
|
* Keeps them out of the way of the main class.
|
||||||
|
*
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
class ActionScheduler_AdminView_Deprecated {
|
||||||
|
|
||||||
|
public function action_scheduler_post_type_args( $args ) {
|
||||||
|
_deprecated_function( __METHOD__, '2.0.0' );
|
||||||
|
return $args;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Customise the post status related views displayed on the Scheduled Actions administration screen.
|
||||||
|
*
|
||||||
|
* @param array $views An associative array of views and view labels which can be used to filter the 'scheduled-action' posts displayed on the Scheduled Actions administration screen.
|
||||||
|
* @return array $views An associative array of views and view labels which can be used to filter the 'scheduled-action' posts displayed on the Scheduled Actions administration screen.
|
||||||
|
*/
|
||||||
|
public function list_table_views( $views ) {
|
||||||
|
_deprecated_function( __METHOD__, '2.0.0' );
|
||||||
|
return $views;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Do not include the "Edit" action for the Scheduled Actions administration screen.
|
||||||
|
*
|
||||||
|
* Hooked to the 'bulk_actions-edit-action-scheduler' filter.
|
||||||
|
*
|
||||||
|
* @param array $actions An associative array of actions which can be performed on the 'scheduled-action' post type.
|
||||||
|
* @return array $actions An associative array of actions which can be performed on the 'scheduled-action' post type.
|
||||||
|
*/
|
||||||
|
public function bulk_actions( $actions ) {
|
||||||
|
_deprecated_function( __METHOD__, '2.0.0' );
|
||||||
|
return $actions;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Completely customer the columns displayed on the Scheduled Actions administration screen.
|
||||||
|
*
|
||||||
|
* Because we can't filter the content of the default title and date columns, we need to recreate our own
|
||||||
|
* custom columns for displaying those post fields. For the column content, @see self::list_table_column_content().
|
||||||
|
*
|
||||||
|
* @param array $columns An associative array of columns that are use for the table on the Scheduled Actions administration screen.
|
||||||
|
* @return array $columns An associative array of columns that are use for the table on the Scheduled Actions administration screen.
|
||||||
|
*/
|
||||||
|
public function list_table_columns( $columns ) {
|
||||||
|
_deprecated_function( __METHOD__, '2.0.0' );
|
||||||
|
return $columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Make our custom title & date columns use defaulting title & date sorting.
|
||||||
|
*
|
||||||
|
* @param array $columns An associative array of columns that can be used to sort the table on the Scheduled Actions administration screen.
|
||||||
|
* @return array $columns An associative array of columns that can be used to sort the table on the Scheduled Actions administration screen.
|
||||||
|
*/
|
||||||
|
public static function list_table_sortable_columns( $columns ) {
|
||||||
|
_deprecated_function( __METHOD__, '2.0.0' );
|
||||||
|
return $columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Print the content for our custom columns.
|
||||||
|
*
|
||||||
|
* @param string $column_name The key for the column for which we should output our content.
|
||||||
|
* @param int $post_id The ID of the 'scheduled-action' post for which this row relates.
|
||||||
|
*/
|
||||||
|
public static function list_table_column_content( $column_name, $post_id ) {
|
||||||
|
_deprecated_function( __METHOD__, '2.0.0' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hide the inline "Edit" action for all 'scheduled-action' posts.
|
||||||
|
*
|
||||||
|
* Hooked to the 'post_row_actions' filter.
|
||||||
|
*
|
||||||
|
* @param array $actions An associative array of actions which can be performed on the 'scheduled-action' post type.
|
||||||
|
* @return array $actions An associative array of actions which can be performed on the 'scheduled-action' post type.
|
||||||
|
*/
|
||||||
|
public static function row_actions( $actions, $post ) {
|
||||||
|
_deprecated_function( __METHOD__, '2.0.0' );
|
||||||
|
return $actions;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run an action when triggered from the Action Scheduler administration screen.
|
||||||
|
*
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
public static function maybe_execute_action() {
|
||||||
|
_deprecated_function( __METHOD__, '2.0.0' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert an interval of seconds into a two part human friendly string.
|
||||||
|
*
|
||||||
|
* The WordPress human_time_diff() function only calculates the time difference to one degree, meaning
|
||||||
|
* even if an action is 1 day and 11 hours away, it will display "1 day". This funciton goes one step
|
||||||
|
* further to display two degrees of accuracy.
|
||||||
|
*
|
||||||
|
* Based on Crontrol::interval() function by Edward Dale: https://wordpress.org/plugins/wp-crontrol/
|
||||||
|
*
|
||||||
|
* @param int $interval A interval in seconds.
|
||||||
|
* @return string A human friendly string representation of the interval.
|
||||||
|
*/
|
||||||
|
public static function admin_notices() {
|
||||||
|
_deprecated_function( __METHOD__, '2.0.0' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Filter search queries to allow searching by Claim ID (i.e. post_password).
|
||||||
|
*
|
||||||
|
* @param string $orderby MySQL orderby string.
|
||||||
|
* @param WP_Query $query Instance of a WP_Query object
|
||||||
|
* @return string MySQL orderby string.
|
||||||
|
*/
|
||||||
|
public function custom_orderby( $orderby, $query ){
|
||||||
|
_deprecated_function( __METHOD__, '2.0.0' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Filter search queries to allow searching by Claim ID (i.e. post_password).
|
||||||
|
*
|
||||||
|
* @param string $search MySQL search string.
|
||||||
|
* @param WP_Query $query Instance of a WP_Query object
|
||||||
|
* @return string MySQL search string.
|
||||||
|
*/
|
||||||
|
public function search_post_password( $search, $query ) {
|
||||||
|
_deprecated_function( __METHOD__, '2.0.0' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Change messages when a scheduled action is updated.
|
||||||
|
*
|
||||||
|
* @param array $messages
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function post_updated_messages( $messages ) {
|
||||||
|
_deprecated_function( __METHOD__, '2.0.0' );
|
||||||
|
return $messages;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,21 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_CanceledAction
|
||||||
|
*
|
||||||
|
* Stored action which was canceled and therefore acts like a finished action but should always return a null schedule,
|
||||||
|
* regardless of schedule passed to its constructor.
|
||||||
|
*/
|
||||||
|
class ActionScheduler_CanceledAction extends ActionScheduler_FinishedAction {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $hook
|
||||||
|
* @param array $args
|
||||||
|
* @param ActionScheduler_Schedule $schedule
|
||||||
|
* @param string $group
|
||||||
|
*/
|
||||||
|
public function __construct( $hook, array $args = array(), ActionScheduler_Schedule $schedule = null, $group = '' ) {
|
||||||
|
parent::__construct( $hook, $args, $schedule, $group );
|
||||||
|
$this->set_schedule( new ActionScheduler_NullSchedule() );
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,50 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_CronSchedule
|
||||||
|
*/
|
||||||
|
class ActionScheduler_CronSchedule implements ActionScheduler_Schedule {
|
||||||
|
/** @var DateTime */
|
||||||
|
private $start = NULL;
|
||||||
|
private $start_timestamp = 0;
|
||||||
|
/** @var CronExpression */
|
||||||
|
private $cron = NULL;
|
||||||
|
|
||||||
|
public function __construct( DateTime $start, CronExpression $cron ) {
|
||||||
|
$this->start = $start;
|
||||||
|
$this->cron = $cron;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param DateTime $after
|
||||||
|
* @return DateTime|null
|
||||||
|
*/
|
||||||
|
public function next( DateTime $after = NULL ) {
|
||||||
|
$after = empty($after) ? clone $this->start : clone $after;
|
||||||
|
return $this->cron->getNextRunDate($after, 0, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function is_recurring() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* For PHP 5.2 compat, since DateTime objects can't be serialized
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function __sleep() {
|
||||||
|
$this->start_timestamp = $this->start->getTimestamp();
|
||||||
|
return array(
|
||||||
|
'start_timestamp',
|
||||||
|
'cron'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __wakeup() {
|
||||||
|
$this->start = as_get_datetime_object($this->start_timestamp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,20 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ActionScheduler DateTime class.
|
||||||
|
*
|
||||||
|
* This is a custom extension to DateTime that
|
||||||
|
*/
|
||||||
|
class ActionScheduler_DateTime extends DateTime {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the unix timestamp of the current object.
|
||||||
|
*
|
||||||
|
* Missing in PHP 5.2 so just here so it can be supported consistently.
|
||||||
|
*
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
public function getTimestamp() {
|
||||||
|
return method_exists( 'DateTime', 'getTimestamp' ) ? parent::getTimestamp() : $this->format( 'U' );
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,54 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_FatalErrorMonitor
|
||||||
|
*/
|
||||||
|
class ActionScheduler_FatalErrorMonitor {
|
||||||
|
/** @var ActionScheduler_ActionClaim */
|
||||||
|
private $claim = NULL;
|
||||||
|
/** @var ActionScheduler_Store */
|
||||||
|
private $store = NULL;
|
||||||
|
private $action_id = 0;
|
||||||
|
|
||||||
|
public function __construct( ActionScheduler_Store $store ) {
|
||||||
|
$this->store = $store;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function attach( ActionScheduler_ActionClaim $claim ) {
|
||||||
|
$this->claim = $claim;
|
||||||
|
add_action( 'shutdown', array( $this, 'handle_unexpected_shutdown' ) );
|
||||||
|
add_action( 'action_scheduler_before_execute', array( $this, 'track_current_action' ), 0, 1 );
|
||||||
|
add_action( 'action_scheduler_after_execute', array( $this, 'untrack_action' ), 0, 0 );
|
||||||
|
add_action( 'action_scheduler_failed_execution', array( $this, 'untrack_action' ), 0, 0 );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function detach() {
|
||||||
|
$this->claim = NULL;
|
||||||
|
$this->untrack_action();
|
||||||
|
remove_action( 'shutdown', array( $this, 'handle_unexpected_shutdown' ) );
|
||||||
|
remove_action( 'action_scheduler_before_execute', array( $this, 'track_current_action' ), 0, 1 );
|
||||||
|
remove_action( 'action_scheduler_after_execute', array( $this, 'untrack_action' ), 0, 0 );
|
||||||
|
remove_action( 'action_scheduler_failed_execution', array( $this, 'untrack_action' ), 0, 0 );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function track_current_action( $action_id ) {
|
||||||
|
$this->action_id = $action_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function untrack_action() {
|
||||||
|
$this->action_id = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle_unexpected_shutdown() {
|
||||||
|
if ( $error = error_get_last() ) {
|
||||||
|
if ( in_array( $error['type'], array( E_ERROR, E_PARSE, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR ) ) ) {
|
||||||
|
if ( !empty($this->action_id) ) {
|
||||||
|
$this->store->mark_failure( $this->action_id );
|
||||||
|
do_action( 'action_scheduler_unexpected_shutdown', $this->action_id, $error );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$this->store->release_claim( $this->claim );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,16 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_FinishedAction
|
||||||
|
*/
|
||||||
|
class ActionScheduler_FinishedAction extends ActionScheduler_Action {
|
||||||
|
|
||||||
|
public function execute() {
|
||||||
|
// don't execute
|
||||||
|
}
|
||||||
|
|
||||||
|
public function is_finished() {
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,62 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_IntervalSchedule
|
||||||
|
*/
|
||||||
|
class ActionScheduler_IntervalSchedule implements ActionScheduler_Schedule {
|
||||||
|
/** @var DateTime */
|
||||||
|
private $start = NULL;
|
||||||
|
private $start_timestamp = 0;
|
||||||
|
private $interval_in_seconds = 0;
|
||||||
|
|
||||||
|
public function __construct( DateTime $start, $interval ) {
|
||||||
|
$this->start = $start;
|
||||||
|
$this->interval_in_seconds = (int)$interval;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param DateTime $after
|
||||||
|
*
|
||||||
|
* @return DateTime|null
|
||||||
|
*/
|
||||||
|
public function next( DateTime $after = NULL ) {
|
||||||
|
$after = empty($after) ? as_get_datetime_object('@0') : clone $after;
|
||||||
|
if ( $after > $this->start ) {
|
||||||
|
$after->modify('+'.$this->interval_in_seconds.' seconds');
|
||||||
|
return $after;
|
||||||
|
}
|
||||||
|
return clone $this->start;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function is_recurring() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param DateTime $after
|
||||||
|
*
|
||||||
|
* @return DateTime|null
|
||||||
|
*/
|
||||||
|
public function interval_in_seconds() {
|
||||||
|
return $this->interval_in_seconds;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* For PHP 5.2 compat, since DateTime objects can't be serialized
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function __sleep() {
|
||||||
|
$this->start_timestamp = $this->start->getTimestamp();
|
||||||
|
return array(
|
||||||
|
'start_timestamp',
|
||||||
|
'interval_in_seconds'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __wakeup() {
|
||||||
|
$this->start = as_get_datetime_object($this->start_timestamp);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,526 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Implements the admin view of the actions.
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The package name.
|
||||||
|
*
|
||||||
|
* @var string
|
||||||
|
*/
|
||||||
|
protected $package = 'action-scheduler';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Columns to show (name => label).
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
protected $columns = array();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Actions (name => label).
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
protected $row_actions = array();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The active data stores
|
||||||
|
*
|
||||||
|
* @var ActionScheduler_Store
|
||||||
|
*/
|
||||||
|
protected $store;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A logger to use for getting action logs to display
|
||||||
|
*
|
||||||
|
* @var ActionScheduler_Logger
|
||||||
|
*/
|
||||||
|
protected $logger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A ActionScheduler_QueueRunner runner instance (or child class)
|
||||||
|
*
|
||||||
|
* @var ActionScheduler_QueueRunner
|
||||||
|
*/
|
||||||
|
protected $runner;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bulk actions. The key of the array is the method name of the implementation:
|
||||||
|
*
|
||||||
|
* bulk_<key>(array $ids, string $sql_in).
|
||||||
|
*
|
||||||
|
* See the comments in the parent class for further details
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
protected $bulk_actions = array();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flag variable to render our notifications, if any, once.
|
||||||
|
*
|
||||||
|
* @var bool
|
||||||
|
*/
|
||||||
|
protected static $did_notification = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Array of seconds for common time periods, like week or month, alongside an internationalised string representation, i.e. "Day" or "Days"
|
||||||
|
*
|
||||||
|
* @var array
|
||||||
|
*/
|
||||||
|
private static $time_periods;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the current data store object into `store->action` and initialises the object.
|
||||||
|
*
|
||||||
|
* @param ActionScheduler_Store $store
|
||||||
|
* @param ActionScheduler_Logger $logger
|
||||||
|
* @param ActionScheduler_QueueRunner $runner
|
||||||
|
*/
|
||||||
|
public function __construct( ActionScheduler_Store $store, ActionScheduler_Logger $logger, ActionScheduler_QueueRunner $runner ) {
|
||||||
|
|
||||||
|
$this->store = $store;
|
||||||
|
$this->logger = $logger;
|
||||||
|
$this->runner = $runner;
|
||||||
|
|
||||||
|
$this->table_header = __( 'Scheduled Actions', 'action-scheduler' );
|
||||||
|
|
||||||
|
$this->bulk_actions = array(
|
||||||
|
'delete' => __( 'Delete', 'action-scheduler' ),
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->columns = array(
|
||||||
|
'hook' => __( 'Hook', 'action-scheduler' ),
|
||||||
|
'status' => __( 'Status', 'action-scheduler' ),
|
||||||
|
'args' => __( 'Arguments', 'action-scheduler' ),
|
||||||
|
'group' => __( 'Group', 'action-scheduler' ),
|
||||||
|
'recurrence' => __( 'Recurrence', 'action-scheduler' ),
|
||||||
|
'schedule' => __( 'Scheduled Date', 'action-scheduler' ),
|
||||||
|
'log_entries' => __( 'Log', 'action-scheduler' ),
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->sort_by = array(
|
||||||
|
'schedule',
|
||||||
|
'hook',
|
||||||
|
'group',
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->search_by = array(
|
||||||
|
'hook',
|
||||||
|
'args',
|
||||||
|
'claim_id',
|
||||||
|
);
|
||||||
|
|
||||||
|
$request_status = $this->get_request_status();
|
||||||
|
|
||||||
|
if ( empty( $request_status ) ) {
|
||||||
|
$this->sort_by[] = 'status';
|
||||||
|
} elseif ( in_array( $request_status, array( 'in-progress', 'failed' ) ) ) {
|
||||||
|
$this->columns += array( 'claim_id' => __( 'Claim ID', 'action-scheduler' ) );
|
||||||
|
$this->sort_by[] = 'claim_id';
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->row_actions = array(
|
||||||
|
'hook' => array(
|
||||||
|
'run' => array(
|
||||||
|
'name' => __( 'Run', 'action-scheduler' ),
|
||||||
|
'desc' => __( 'Process the action now as if it were run as part of a queue', 'action-scheduler' ),
|
||||||
|
),
|
||||||
|
'cancel' => array(
|
||||||
|
'name' => __( 'Cancel', 'action-scheduler' ),
|
||||||
|
'desc' => __( 'Cancel the action now to avoid it being run in future', 'action-scheduler' ),
|
||||||
|
'class' => 'cancel trash',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
self::$time_periods = array(
|
||||||
|
array(
|
||||||
|
'seconds' => YEAR_IN_SECONDS,
|
||||||
|
'names' => _n_noop( '%s year', '%s years', 'action-scheduler' ),
|
||||||
|
),
|
||||||
|
array(
|
||||||
|
'seconds' => MONTH_IN_SECONDS,
|
||||||
|
'names' => _n_noop( '%s month', '%s months', 'action-scheduler' ),
|
||||||
|
),
|
||||||
|
array(
|
||||||
|
'seconds' => WEEK_IN_SECONDS,
|
||||||
|
'names' => _n_noop( '%s week', '%s weeks', 'action-scheduler' ),
|
||||||
|
),
|
||||||
|
array(
|
||||||
|
'seconds' => DAY_IN_SECONDS,
|
||||||
|
'names' => _n_noop( '%s day', '%s days', 'action-scheduler' ),
|
||||||
|
),
|
||||||
|
array(
|
||||||
|
'seconds' => HOUR_IN_SECONDS,
|
||||||
|
'names' => _n_noop( '%s hour', '%s hours', 'action-scheduler' ),
|
||||||
|
),
|
||||||
|
array(
|
||||||
|
'seconds' => MINUTE_IN_SECONDS,
|
||||||
|
'names' => _n_noop( '%s minute', '%s minutes', 'action-scheduler' ),
|
||||||
|
),
|
||||||
|
array(
|
||||||
|
'seconds' => 1,
|
||||||
|
'names' => _n_noop( '%s second', '%s seconds', 'action-scheduler' ),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
parent::__construct( array(
|
||||||
|
'singular' => 'action-scheduler',
|
||||||
|
'plural' => 'action-scheduler',
|
||||||
|
'ajax' => false,
|
||||||
|
) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert an interval of seconds into a two part human friendly string.
|
||||||
|
*
|
||||||
|
* The WordPress human_time_diff() function only calculates the time difference to one degree, meaning
|
||||||
|
* even if an action is 1 day and 11 hours away, it will display "1 day". This function goes one step
|
||||||
|
* further to display two degrees of accuracy.
|
||||||
|
*
|
||||||
|
* Inspired by the Crontrol::interval() function by Edward Dale: https://wordpress.org/plugins/wp-crontrol/
|
||||||
|
*
|
||||||
|
* @param int $interval A interval in seconds.
|
||||||
|
* @param int $periods_to_include Depth of time periods to include, e.g. for an interval of 70, and $periods_to_include of 2, both minutes and seconds would be included. With a value of 1, only minutes would be included.
|
||||||
|
* @return string A human friendly string representation of the interval.
|
||||||
|
*/
|
||||||
|
private static function human_interval( $interval, $periods_to_include = 2 ) {
|
||||||
|
|
||||||
|
if ( $interval <= 0 ) {
|
||||||
|
return __( 'Now!', 'action-scheduler' );
|
||||||
|
}
|
||||||
|
|
||||||
|
$output = '';
|
||||||
|
|
||||||
|
for ( $time_period_index = 0, $periods_included = 0, $seconds_remaining = $interval; $time_period_index < count( self::$time_periods ) && $seconds_remaining > 0 && $periods_included < $periods_to_include; $time_period_index++ ) {
|
||||||
|
|
||||||
|
$periods_in_interval = floor( $seconds_remaining / self::$time_periods[ $time_period_index ]['seconds'] );
|
||||||
|
|
||||||
|
if ( $periods_in_interval > 0 ) {
|
||||||
|
if ( ! empty( $output ) ) {
|
||||||
|
$output .= ' ';
|
||||||
|
}
|
||||||
|
$output .= sprintf( _n( self::$time_periods[ $time_period_index ]['names'][0], self::$time_periods[ $time_period_index ]['names'][1], $periods_in_interval, 'action-scheduler' ), $periods_in_interval );
|
||||||
|
$seconds_remaining -= $periods_in_interval * self::$time_periods[ $time_period_index ]['seconds'];
|
||||||
|
$periods_included++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $output;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the recurrence of an action or 'Non-repeating'. The output is human readable.
|
||||||
|
*
|
||||||
|
* @param ActionScheduler_Action $action
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function get_recurrence( $action ) {
|
||||||
|
$recurrence = $action->get_schedule();
|
||||||
|
if ( method_exists( $recurrence, 'interval_in_seconds' ) ) {
|
||||||
|
return sprintf( __( 'Every %s', 'action-scheduler' ), self::human_interval( $recurrence->interval_in_seconds() ) );
|
||||||
|
}
|
||||||
|
return __( 'Non-repeating', 'action-scheduler' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serializes the argument of an action to render it in a human friendly format.
|
||||||
|
*
|
||||||
|
* @param array $row The array representation of the current row of the table
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function column_args( array $row ) {
|
||||||
|
if ( empty( $row['args'] ) ) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
$row_html = '<ul>';
|
||||||
|
foreach ( $row['args'] as $key => $value ) {
|
||||||
|
$row_html .= sprintf( '<li><code>%s => %s</code></li>', esc_html( $key ), esc_html( $value ) );
|
||||||
|
}
|
||||||
|
$row_html .= '</ul>';
|
||||||
|
|
||||||
|
return apply_filters( 'action_scheduler_list_table_column_args', $row_html, $row );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prints the logs entries inline. We do so to avoid loading Javascript and other hacks to show it in a modal.
|
||||||
|
*
|
||||||
|
* @param array $row Action array.
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function column_log_entries( array $row ) {
|
||||||
|
|
||||||
|
$log_entries_html = '<ol>';
|
||||||
|
|
||||||
|
$timezone = new DateTimezone( 'UTC' );
|
||||||
|
|
||||||
|
foreach ( $row['log_entries'] as $log_entry ) {
|
||||||
|
$log_entries_html .= $this->get_log_entry_html( $log_entry, $timezone );
|
||||||
|
}
|
||||||
|
|
||||||
|
$log_entries_html .= '</ol>';
|
||||||
|
|
||||||
|
return $log_entries_html;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prints the logs entries inline. We do so to avoid loading Javascript and other hacks to show it in a modal.
|
||||||
|
*
|
||||||
|
* @param ActionScheduler_LogEntry $log_entry
|
||||||
|
* @param DateTimezone $timezone
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function get_log_entry_html( ActionScheduler_LogEntry $log_entry, DateTimezone $timezone ) {
|
||||||
|
$date = $log_entry->get_date();
|
||||||
|
$date->setTimezone( $timezone );
|
||||||
|
return sprintf( '<li><strong>%s</strong><br/>%s</li>', esc_html( $date->format( 'Y-m-d H:i:s e' ) ), esc_html( $log_entry->get_message() ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Only display row actions for pending actions.
|
||||||
|
*
|
||||||
|
* @param array $row Row to render
|
||||||
|
* @param string $column_name Current row
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function maybe_render_actions( $row, $column_name ) {
|
||||||
|
if ( 'pending' === strtolower( $row['status'] ) ) {
|
||||||
|
return parent::maybe_render_actions( $row, $column_name );
|
||||||
|
}
|
||||||
|
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders admin notifications
|
||||||
|
*
|
||||||
|
* Notifications:
|
||||||
|
* 1. When the maximum number of tasks are being executed simultaneously
|
||||||
|
* 2. Notifications when a task us manually executed
|
||||||
|
*/
|
||||||
|
public function display_admin_notices() {
|
||||||
|
|
||||||
|
if ( $this->store->get_claim_count() >= $this->runner->get_allowed_concurrent_batches() ) {
|
||||||
|
$this->admin_notices[] = array(
|
||||||
|
'class' => 'updated',
|
||||||
|
'message' => sprintf( __( 'Maximum simultaneous batches already in progress (%s queues). No actions will be processed until the current batches are complete.', 'action-scheduler' ), $this->store->get_claim_count() ),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$notification = get_transient( 'action_scheduler_admin_notice' );
|
||||||
|
|
||||||
|
if ( is_array( $notification ) ) {
|
||||||
|
delete_transient( 'action_scheduler_admin_notice' );
|
||||||
|
|
||||||
|
$action = $this->store->fetch_action( $notification['action_id'] );
|
||||||
|
$action_hook_html = '<strong><code>' . $action->get_hook() . '</code></strong>';
|
||||||
|
if ( 1 == $notification['success'] ) {
|
||||||
|
$class = 'updated';
|
||||||
|
switch ( $notification['row_action_type'] ) {
|
||||||
|
case 'run' :
|
||||||
|
$action_message_html = sprintf( __( 'Successfully executed action: %s', 'action-scheduler' ), $action_hook_html );
|
||||||
|
break;
|
||||||
|
case 'cancel' :
|
||||||
|
$action_message_html = sprintf( __( 'Successfully canceled action: %s', 'action-scheduler' ), $action_hook_html );
|
||||||
|
break;
|
||||||
|
default :
|
||||||
|
$action_message_html = sprintf( __( 'Successfully processed change for action: %s', 'action-scheduler' ), $action_hook_html );
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$class = 'error';
|
||||||
|
$action_message_html = sprintf( __( 'Could not process change for action: "%s" (ID: %d). Error: %s', 'action-scheduler' ), $action_hook_html, esc_html( $notification['action_id'] ), esc_html( $notification['error_message'] ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
$action_message_html = apply_filters( 'action_scheduler_admin_notice_html', $action_message_html, $action, $notification );
|
||||||
|
|
||||||
|
$this->admin_notices[] = array(
|
||||||
|
'class' => $class,
|
||||||
|
'message' => $action_message_html,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
parent::display_admin_notices();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prints the scheduled date in a human friendly format.
|
||||||
|
*
|
||||||
|
* @param array $row The array representation of the current row of the table
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function column_schedule( $row ) {
|
||||||
|
return $this->get_schedule_display_string( $row['schedule'] );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the scheduled date in a human friendly format.
|
||||||
|
*
|
||||||
|
* @param ActionScheduler_Schedule $schedule
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function get_schedule_display_string( ActionScheduler_Schedule $schedule ) {
|
||||||
|
|
||||||
|
$schedule_display_string = '';
|
||||||
|
|
||||||
|
if ( ! $schedule->next() ) {
|
||||||
|
return $schedule_display_string;
|
||||||
|
}
|
||||||
|
|
||||||
|
$next_timestamp = $schedule->next()->getTimestamp();
|
||||||
|
|
||||||
|
$schedule_display_string .= $schedule->next()->format( 'Y-m-d H:i:s e' );
|
||||||
|
$schedule_display_string .= '<br/>';
|
||||||
|
|
||||||
|
if ( gmdate( 'U' ) > $next_timestamp ) {
|
||||||
|
$schedule_display_string .= sprintf( __( ' (%s ago)', 'action-scheduler' ), self::human_interval( gmdate( 'U' ) - $next_timestamp ) );
|
||||||
|
} else {
|
||||||
|
$schedule_display_string .= sprintf( __( ' (%s)', 'action-scheduler' ), self::human_interval( $next_timestamp - gmdate( 'U' ) ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
return $schedule_display_string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bulk delete
|
||||||
|
*
|
||||||
|
* Deletes actions based on their ID. This is the handler for the bulk delete. It assumes the data
|
||||||
|
* properly validated by the callee and it will delete the actions without any extra validation.
|
||||||
|
*
|
||||||
|
* @param array $ids
|
||||||
|
* @param string $ids_sql Inherited and unused
|
||||||
|
*/
|
||||||
|
protected function bulk_delete( array $ids, $ids_sql ) {
|
||||||
|
foreach ( $ids as $id ) {
|
||||||
|
$this->store->delete_action( $id );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Implements the logic behind running an action. ActionScheduler_Abstract_ListTable validates the request and their
|
||||||
|
* parameters are valid.
|
||||||
|
*
|
||||||
|
* @param int $action_id
|
||||||
|
*/
|
||||||
|
protected function row_action_cancel( $action_id ) {
|
||||||
|
$this->process_row_action( $action_id, 'cancel' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Implements the logic behind running an action. ActionScheduler_Abstract_ListTable validates the request and their
|
||||||
|
* parameters are valid.
|
||||||
|
*
|
||||||
|
* @param int $action_id
|
||||||
|
*/
|
||||||
|
protected function row_action_run( $action_id ) {
|
||||||
|
$this->process_row_action( $action_id, 'run' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Implements the logic behind processing an action once an action link is clicked on the list table.
|
||||||
|
*
|
||||||
|
* @param int $action_id
|
||||||
|
* @param string $row_action_type The type of action to perform on the action.
|
||||||
|
*/
|
||||||
|
protected function process_row_action( $action_id, $row_action_type ) {
|
||||||
|
try {
|
||||||
|
switch ( $row_action_type ) {
|
||||||
|
case 'run' :
|
||||||
|
$this->runner->process_action( $action_id );
|
||||||
|
break;
|
||||||
|
case 'cancel' :
|
||||||
|
$this->store->cancel_action( $action_id );
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
$success = 1;
|
||||||
|
$error_message = '';
|
||||||
|
} catch ( Exception $e ) {
|
||||||
|
$success = 0;
|
||||||
|
$error_message = $e->getMessage();
|
||||||
|
}
|
||||||
|
|
||||||
|
set_transient( 'action_scheduler_admin_notice', compact( 'action_id', 'success', 'error_message', 'row_action_type' ), 30 );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritDoc}
|
||||||
|
*/
|
||||||
|
public function prepare_items() {
|
||||||
|
$this->process_bulk_action();
|
||||||
|
|
||||||
|
$this->process_row_actions();
|
||||||
|
|
||||||
|
if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
|
||||||
|
// _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter
|
||||||
|
wp_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->prepare_column_headers();
|
||||||
|
|
||||||
|
$per_page = $this->get_items_per_page( $this->package . '_items_per_page', $this->items_per_page );
|
||||||
|
$query = array(
|
||||||
|
'per_page' => $per_page,
|
||||||
|
'offset' => $this->get_items_offset(),
|
||||||
|
'status' => $this->get_request_status(),
|
||||||
|
'orderby' => $this->get_request_orderby(),
|
||||||
|
'order' => $this->get_request_order(),
|
||||||
|
'search' => $this->get_request_search_query(),
|
||||||
|
);
|
||||||
|
|
||||||
|
$this->items = array();
|
||||||
|
|
||||||
|
$total_items = $this->store->query_actions( $query, 'count' );
|
||||||
|
|
||||||
|
$status_labels = $this->store->get_status_labels();
|
||||||
|
|
||||||
|
foreach ( $this->store->query_actions( $query ) as $action_id ) {
|
||||||
|
try {
|
||||||
|
$action = $this->store->fetch_action( $action_id );
|
||||||
|
} catch ( Exception $e ) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$this->items[ $action_id ] = array(
|
||||||
|
'ID' => $action_id,
|
||||||
|
'hook' => $action->get_hook(),
|
||||||
|
'status' => $status_labels[ $this->store->get_status( $action_id ) ],
|
||||||
|
'args' => $action->get_args(),
|
||||||
|
'group' => $action->get_group(),
|
||||||
|
'log_entries' => $this->logger->get_logs( $action_id ),
|
||||||
|
'claim_id' => $this->store->get_claim_id( $action_id ),
|
||||||
|
'recurrence' => $this->get_recurrence( $action ),
|
||||||
|
'schedule' => $action->get_schedule(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->set_pagination_args( array(
|
||||||
|
'total_items' => $total_items,
|
||||||
|
'per_page' => $per_page,
|
||||||
|
'total_pages' => ceil( $total_items / $per_page ),
|
||||||
|
) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prints the available statuses so the user can click to filter.
|
||||||
|
*/
|
||||||
|
protected function display_filter_by_status() {
|
||||||
|
$this->status_counts = $this->store->action_counts();
|
||||||
|
parent::display_filter_by_status();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the text to display in the search box on the list table.
|
||||||
|
*/
|
||||||
|
protected function get_search_box_button_text() {
|
||||||
|
return __( 'Search hook, args and claim ID', 'action-scheduler' );
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,67 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_LogEntry
|
||||||
|
*/
|
||||||
|
class ActionScheduler_LogEntry {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var int $action_id
|
||||||
|
*/
|
||||||
|
protected $action_id = '';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var string $message
|
||||||
|
*/
|
||||||
|
protected $message = '';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var Datetime $date
|
||||||
|
*/
|
||||||
|
protected $date;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructor
|
||||||
|
*
|
||||||
|
* @param mixed $action_id Action ID
|
||||||
|
* @param string $message Message
|
||||||
|
* @param Datetime $date Datetime object with the time when this log entry was created. If this parameter is
|
||||||
|
* not provided a new Datetime object (with current time) will be created.
|
||||||
|
*/
|
||||||
|
public function __construct( $action_id, $message, $date = null ) {
|
||||||
|
|
||||||
|
/*
|
||||||
|
* ActionScheduler_wpCommentLogger::get_entry() previously passed a 3rd param of $comment->comment_type
|
||||||
|
* to ActionScheduler_LogEntry::__construct(), goodness knows why, and the Follow-up Emails plugin
|
||||||
|
* hard-codes loading its own version of ActionScheduler_wpCommentLogger with that out-dated method,
|
||||||
|
* goodness knows why, so we need to guard against that here instead of using a DateTime type declaration
|
||||||
|
* for the constructor's 3rd param of $date and causing a fatal error with older versions of FUE.
|
||||||
|
*/
|
||||||
|
if ( null !== $date && ! is_a( $date, 'DateTime' ) ) {
|
||||||
|
_doing_it_wrong( __METHOD__, 'The third parameter must be a valid DateTime instance, or null.', '2.0.0' );
|
||||||
|
$date = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->action_id = $action_id;
|
||||||
|
$this->message = $message;
|
||||||
|
$this->date = $date ? $date : new Datetime;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the date when this log entry was created
|
||||||
|
*
|
||||||
|
* @return Datetime
|
||||||
|
*/
|
||||||
|
public function get_date() {
|
||||||
|
return $this->date;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function get_action_id() {
|
||||||
|
return $this->action_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function get_message() {
|
||||||
|
return $this->message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,47 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_Logger
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
abstract class ActionScheduler_Logger {
|
||||||
|
private static $logger = NULL;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return ActionScheduler_Logger
|
||||||
|
*/
|
||||||
|
public static function instance() {
|
||||||
|
if ( empty(self::$logger) ) {
|
||||||
|
$class = apply_filters('action_scheduler_logger_class', 'ActionScheduler_wpCommentLogger');
|
||||||
|
self::$logger = new $class();
|
||||||
|
}
|
||||||
|
return self::$logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
* @param string $message
|
||||||
|
* @param DateTime $date
|
||||||
|
*
|
||||||
|
* @return string The log entry ID
|
||||||
|
*/
|
||||||
|
abstract public function log( $action_id, $message, DateTime $date = NULL );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $entry_id
|
||||||
|
*
|
||||||
|
* @return ActionScheduler_LogEntry
|
||||||
|
*/
|
||||||
|
abstract public function get_entry( $entry_id );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*
|
||||||
|
* @return ActionScheduler_LogEntry[]
|
||||||
|
*/
|
||||||
|
abstract public function get_logs( $action_id );
|
||||||
|
|
||||||
|
abstract public function init();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,16 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_NullAction
|
||||||
|
*/
|
||||||
|
class ActionScheduler_NullAction extends ActionScheduler_Action {
|
||||||
|
|
||||||
|
public function __construct( $hook = '', array $args = array(), ActionScheduler_Schedule $schedule = NULL ) {
|
||||||
|
$this->set_schedule( new ActionScheduler_NullSchedule() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function execute() {
|
||||||
|
// don't execute
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,11 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_NullLogEntry
|
||||||
|
*/
|
||||||
|
class ActionScheduler_NullLogEntry extends ActionScheduler_LogEntry {
|
||||||
|
public function __construct( $action_id = '', $message = '' ) {
|
||||||
|
// nothing to see here
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,19 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_NullSchedule
|
||||||
|
*/
|
||||||
|
class ActionScheduler_NullSchedule implements ActionScheduler_Schedule {
|
||||||
|
|
||||||
|
public function next( DateTime $after = NULL ) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function is_recurring() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,144 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_QueueCleaner
|
||||||
|
*/
|
||||||
|
class ActionScheduler_QueueCleaner {
|
||||||
|
|
||||||
|
/** @var int */
|
||||||
|
protected $batch_size;
|
||||||
|
|
||||||
|
/** @var ActionScheduler_Store */
|
||||||
|
private $store = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 31 days in seconds.
|
||||||
|
*
|
||||||
|
* @var int
|
||||||
|
*/
|
||||||
|
private $month_in_seconds = 2678400;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Five minutes in seconds
|
||||||
|
*
|
||||||
|
* @var int
|
||||||
|
*/
|
||||||
|
private $five_minutes = 300;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ActionScheduler_QueueCleaner constructor.
|
||||||
|
*
|
||||||
|
* @param ActionScheduler_Store $store The store instance.
|
||||||
|
* @param int $batch_size The batch size.
|
||||||
|
*/
|
||||||
|
public function __construct( ActionScheduler_Store $store = null, $batch_size = 20 ) {
|
||||||
|
$this->store = $store ? $store : ActionScheduler_Store::instance();
|
||||||
|
$this->batch_size = $batch_size;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function delete_old_actions() {
|
||||||
|
$lifespan = apply_filters( 'action_scheduler_retention_period', $this->month_in_seconds );
|
||||||
|
$cutoff = as_get_datetime_object($lifespan.' seconds ago');
|
||||||
|
|
||||||
|
$statuses_to_purge = array(
|
||||||
|
ActionScheduler_Store::STATUS_COMPLETE,
|
||||||
|
ActionScheduler_Store::STATUS_CANCELED,
|
||||||
|
);
|
||||||
|
|
||||||
|
foreach ( $statuses_to_purge as $status ) {
|
||||||
|
$actions_to_delete = $this->store->query_actions( array(
|
||||||
|
'status' => $status,
|
||||||
|
'modified' => $cutoff,
|
||||||
|
'modified_compare' => '<=',
|
||||||
|
'per_page' => $this->get_batch_size(),
|
||||||
|
) );
|
||||||
|
|
||||||
|
foreach ( $actions_to_delete as $action_id ) {
|
||||||
|
try {
|
||||||
|
$this->store->delete_action( $action_id );
|
||||||
|
} catch ( Exception $e ) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Notify 3rd party code of exceptions when deleting a completed action older than the retention period
|
||||||
|
*
|
||||||
|
* This hook provides a way for 3rd party code to log or otherwise handle exceptions relating to their
|
||||||
|
* actions.
|
||||||
|
*
|
||||||
|
* @since 2.0.0
|
||||||
|
*
|
||||||
|
* @param int $action_id The scheduled actions ID in the data store
|
||||||
|
* @param Exception $e The exception thrown when attempting to delete the action from the data store
|
||||||
|
* @param int $lifespan The retention period, in seconds, for old actions
|
||||||
|
* @param int $count_of_actions_to_delete The number of old actions being deleted in this batch
|
||||||
|
*/
|
||||||
|
do_action( 'action_scheduler_failed_old_action_deletion', $action_id, $e, $lifespan, count( $actions_to_delete ) );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function reset_timeouts() {
|
||||||
|
$timeout = apply_filters( 'action_scheduler_timeout_period', $this->five_minutes );
|
||||||
|
if ( $timeout < 0 ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$cutoff = as_get_datetime_object($timeout.' seconds ago');
|
||||||
|
$actions_to_reset = $this->store->query_actions( array(
|
||||||
|
'status' => ActionScheduler_Store::STATUS_PENDING,
|
||||||
|
'modified' => $cutoff,
|
||||||
|
'modified_compare' => '<=',
|
||||||
|
'claimed' => true,
|
||||||
|
'per_page' => $this->get_batch_size(),
|
||||||
|
) );
|
||||||
|
|
||||||
|
foreach ( $actions_to_reset as $action_id ) {
|
||||||
|
$this->store->unclaim_action( $action_id );
|
||||||
|
do_action( 'action_scheduler_reset_action', $action_id );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function mark_failures() {
|
||||||
|
$timeout = apply_filters( 'action_scheduler_failure_period', $this->five_minutes );
|
||||||
|
if ( $timeout < 0 ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$cutoff = as_get_datetime_object($timeout.' seconds ago');
|
||||||
|
$actions_to_reset = $this->store->query_actions( array(
|
||||||
|
'status' => ActionScheduler_Store::STATUS_RUNNING,
|
||||||
|
'modified' => $cutoff,
|
||||||
|
'modified_compare' => '<=',
|
||||||
|
'per_page' => $this->get_batch_size(),
|
||||||
|
) );
|
||||||
|
|
||||||
|
foreach ( $actions_to_reset as $action_id ) {
|
||||||
|
$this->store->mark_failure( $action_id );
|
||||||
|
do_action( 'action_scheduler_failed_action', $action_id, $timeout );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Do all of the cleaning actions.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
*/
|
||||||
|
public function clean() {
|
||||||
|
$this->delete_old_actions();
|
||||||
|
$this->reset_timeouts();
|
||||||
|
$this->mark_failures();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the batch size for cleaning the queue.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
protected function get_batch_size() {
|
||||||
|
/**
|
||||||
|
* Filter the batch size when cleaning the queue.
|
||||||
|
*
|
||||||
|
* @param int $batch_size The number of actions to clean in one batch.
|
||||||
|
*/
|
||||||
|
return absint( apply_filters( 'action_scheduler_cleanup_batch_size', $this->batch_size ) );
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,169 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_QueueRunner
|
||||||
|
*/
|
||||||
|
class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
|
||||||
|
const WP_CRON_HOOK = 'action_scheduler_run_queue';
|
||||||
|
|
||||||
|
const WP_CRON_SCHEDULE = 'every_minute';
|
||||||
|
|
||||||
|
/** @var ActionScheduler_QueueRunner */
|
||||||
|
private static $runner = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The created time.
|
||||||
|
*
|
||||||
|
* Represents when the queue runner was constructed and used when calculating how long a PHP request has been running.
|
||||||
|
* For this reason it should be as close as possible to the PHP request start time.
|
||||||
|
*
|
||||||
|
* @var int
|
||||||
|
*/
|
||||||
|
private $created_time;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return ActionScheduler_QueueRunner
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
public static function instance() {
|
||||||
|
if ( empty(self::$runner) ) {
|
||||||
|
$class = apply_filters('action_scheduler_queue_runner_class', 'ActionScheduler_QueueRunner');
|
||||||
|
self::$runner = new $class();
|
||||||
|
}
|
||||||
|
return self::$runner;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ActionScheduler_QueueRunner constructor.
|
||||||
|
*
|
||||||
|
* @param ActionScheduler_Store $store
|
||||||
|
* @param ActionScheduler_FatalErrorMonitor $monitor
|
||||||
|
* @param ActionScheduler_QueueCleaner $cleaner
|
||||||
|
*/
|
||||||
|
public function __construct( ActionScheduler_Store $store = null, ActionScheduler_FatalErrorMonitor $monitor = null, ActionScheduler_QueueCleaner $cleaner = null ) {
|
||||||
|
parent::__construct( $store, $monitor, $cleaner );
|
||||||
|
$this->created_time = microtime( true );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
public function init() {
|
||||||
|
|
||||||
|
add_filter( 'cron_schedules', array( self::instance(), 'add_wp_cron_schedule' ) );
|
||||||
|
|
||||||
|
if ( !wp_next_scheduled(self::WP_CRON_HOOK) ) {
|
||||||
|
$schedule = apply_filters( 'action_scheduler_run_schedule', self::WP_CRON_SCHEDULE );
|
||||||
|
wp_schedule_event( time(), $schedule, self::WP_CRON_HOOK );
|
||||||
|
}
|
||||||
|
|
||||||
|
add_action( self::WP_CRON_HOOK, array( self::instance(), 'run' ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function run() {
|
||||||
|
@ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) );
|
||||||
|
@set_time_limit( apply_filters( 'action_scheduler_queue_runner_time_limit', 600 ) );
|
||||||
|
do_action( 'action_scheduler_before_process_queue' );
|
||||||
|
$this->run_cleanup();
|
||||||
|
$count = 0;
|
||||||
|
if ( $this->store->get_claim_count() < $this->get_allowed_concurrent_batches() ) {
|
||||||
|
$batch_size = apply_filters( 'action_scheduler_queue_runner_batch_size', 25 );
|
||||||
|
$count = $this->do_batch( $batch_size );
|
||||||
|
}
|
||||||
|
|
||||||
|
do_action( 'action_scheduler_after_process_queue' );
|
||||||
|
return $count;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function do_batch( $size = 100 ) {
|
||||||
|
$claim = $this->store->stake_claim($size);
|
||||||
|
$this->monitor->attach($claim);
|
||||||
|
$processed_actions = 0;
|
||||||
|
$maximum_execution_time = $this->get_maximum_execution_time();
|
||||||
|
|
||||||
|
foreach ( $claim->get_actions() as $action_id ) {
|
||||||
|
if ( 0 !== $processed_actions ) {
|
||||||
|
$time_elapsed = $this->get_execution_time();
|
||||||
|
$average_processing_time = $time_elapsed / $processed_actions;
|
||||||
|
|
||||||
|
// Bail early if the time it has taken to process this batch is approaching the maximum execution time.
|
||||||
|
if ( $time_elapsed + ( $average_processing_time * 2 ) > $maximum_execution_time ) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// bail if we lost the claim
|
||||||
|
if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $claim->get_id() ) ) ) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
$this->process_action( $action_id );
|
||||||
|
$processed_actions++;
|
||||||
|
}
|
||||||
|
$this->store->release_claim($claim);
|
||||||
|
$this->monitor->detach();
|
||||||
|
$this->clear_caches();
|
||||||
|
return $processed_actions;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Running large batches can eat up memory, as WP adds data to its object cache.
|
||||||
|
*
|
||||||
|
* If using a persistent object store, this has the side effect of flushing that
|
||||||
|
* as well, so this is disabled by default. To enable:
|
||||||
|
*
|
||||||
|
* add_filter( 'action_scheduler_queue_runner_flush_cache', '__return_true' );
|
||||||
|
*/
|
||||||
|
protected function clear_caches() {
|
||||||
|
if ( ! wp_using_ext_object_cache() || apply_filters( 'action_scheduler_queue_runner_flush_cache', false ) ) {
|
||||||
|
wp_cache_flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function add_wp_cron_schedule( $schedules ) {
|
||||||
|
$schedules['every_minute'] = array(
|
||||||
|
'interval' => 60, // in seconds
|
||||||
|
'display' => __( 'Every minute' ),
|
||||||
|
);
|
||||||
|
|
||||||
|
return $schedules;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the maximum number of seconds a batch can run for.
|
||||||
|
*
|
||||||
|
* @return int The number of seconds.
|
||||||
|
*/
|
||||||
|
protected function get_maximum_execution_time() {
|
||||||
|
|
||||||
|
// There are known hosts with a strict 60 second execution time.
|
||||||
|
if ( defined( 'WPENGINE_ACCOUNT' ) || defined( 'PANTHEON_ENVIRONMENT' ) ) {
|
||||||
|
$maximum_execution_time = 60;
|
||||||
|
} elseif ( false !== strpos( getenv( 'HOSTNAME' ), '.siteground.' ) ) {
|
||||||
|
$maximum_execution_time = 120;
|
||||||
|
} else {
|
||||||
|
$maximum_execution_time = ini_get( 'max_execution_time' );
|
||||||
|
}
|
||||||
|
|
||||||
|
return absint( apply_filters( 'action_scheduler_maximum_execution_time', $maximum_execution_time ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the number of seconds a batch has run for.
|
||||||
|
*
|
||||||
|
* @return int The number of seconds.
|
||||||
|
*/
|
||||||
|
protected function get_execution_time() {
|
||||||
|
$execution_time = microtime( true ) - $this->created_time;
|
||||||
|
|
||||||
|
// Get the CPU time if the hosting environment uses it rather than wall-clock time to calculate a process's execution time.
|
||||||
|
if ( function_exists( 'getrusage' ) && apply_filters( 'action_scheduler_use_cpu_execution_time', defined( 'PANTHEON_ENVIRONMENT' ) ) ) {
|
||||||
|
$resource_usages = getrusage();
|
||||||
|
|
||||||
|
if ( isset( $resource_usages['ru_stime.tv_usec'], $resource_usages['ru_stime.tv_usec'] ) ) {
|
||||||
|
$execution_time = $resource_usages['ru_stime.tv_sec'] + ( $resource_usages['ru_stime.tv_usec'] / 1000000 );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $execution_time;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_Schedule
|
||||||
|
*/
|
||||||
|
interface ActionScheduler_Schedule {
|
||||||
|
/**
|
||||||
|
* @param DateTime $after
|
||||||
|
* @return DateTime|null
|
||||||
|
*/
|
||||||
|
public function next( DateTime $after = NULL );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function is_recurring();
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,44 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_SimpleSchedule
|
||||||
|
*/
|
||||||
|
class ActionScheduler_SimpleSchedule implements ActionScheduler_Schedule {
|
||||||
|
private $date = NULL;
|
||||||
|
private $timestamp = 0;
|
||||||
|
public function __construct( DateTime $date ) {
|
||||||
|
$this->date = clone $date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param DateTime $after
|
||||||
|
*
|
||||||
|
* @return DateTime|null
|
||||||
|
*/
|
||||||
|
public function next( DateTime $after = NULL ) {
|
||||||
|
$after = empty($after) ? as_get_datetime_object('@0') : $after;
|
||||||
|
return ( $after > $this->date ) ? NULL : clone $this->date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function is_recurring() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* For PHP 5.2 compat, since DateTime objects can't be serialized
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function __sleep() {
|
||||||
|
$this->timestamp = $this->date->getTimestamp();
|
||||||
|
return array(
|
||||||
|
'timestamp',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function __wakeup() {
|
||||||
|
$this->date = as_get_datetime_object($this->timestamp);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,210 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_Store
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
abstract class ActionScheduler_Store {
|
||||||
|
const STATUS_COMPLETE = 'complete';
|
||||||
|
const STATUS_PENDING = 'pending';
|
||||||
|
const STATUS_RUNNING = 'in-progress';
|
||||||
|
const STATUS_FAILED = 'failed';
|
||||||
|
const STATUS_CANCELED = 'canceled';
|
||||||
|
|
||||||
|
/** @var ActionScheduler_Store */
|
||||||
|
private static $store = NULL;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param ActionScheduler_Action $action
|
||||||
|
* @param DateTime $scheduled_date Optional Date of the first instance
|
||||||
|
* to store. Otherwise uses the first date of the action's
|
||||||
|
* schedule.
|
||||||
|
*
|
||||||
|
* @return string The action ID
|
||||||
|
*/
|
||||||
|
abstract public function save_action( ActionScheduler_Action $action, DateTime $scheduled_date = NULL );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*
|
||||||
|
* @return ActionScheduler_Action
|
||||||
|
*/
|
||||||
|
abstract public function fetch_action( $action_id );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $hook
|
||||||
|
* @param array $params
|
||||||
|
* @return string ID of the next action matching the criteria
|
||||||
|
*/
|
||||||
|
abstract public function find_action( $hook, $params = array() );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $query
|
||||||
|
* @return array The IDs of actions matching the query
|
||||||
|
*/
|
||||||
|
abstract public function query_actions( $query = array() );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a count of all actions in the store, grouped by status
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
abstract public function action_counts();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*/
|
||||||
|
abstract public function cancel_action( $action_id );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*/
|
||||||
|
abstract public function delete_action( $action_id );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*
|
||||||
|
* @return DateTime The date the action is schedule to run, or the date that it ran.
|
||||||
|
*/
|
||||||
|
abstract public function get_date( $action_id );
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int $max_actions
|
||||||
|
* @param DateTime $before_date Claim only actions schedule before the given date. Defaults to now.
|
||||||
|
* @param array $hooks Claim only actions with a hook or hooks.
|
||||||
|
* @param string $group Claim only actions in the given group.
|
||||||
|
*
|
||||||
|
* @return ActionScheduler_ActionClaim
|
||||||
|
*/
|
||||||
|
abstract public function stake_claim( $max_actions = 10, DateTime $before_date = null, $hooks = array(), $group = '' );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
abstract public function get_claim_count();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param ActionScheduler_ActionClaim $claim
|
||||||
|
*/
|
||||||
|
abstract public function release_claim( ActionScheduler_ActionClaim $claim );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*/
|
||||||
|
abstract public function unclaim_action( $action_id );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*/
|
||||||
|
abstract public function mark_failure( $action_id );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*/
|
||||||
|
abstract public function log_execution( $action_id );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*/
|
||||||
|
abstract public function mark_complete( $action_id );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
abstract public function get_status( $action_id );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
abstract public function get_claim_id( $action_id );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $claim_id
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
abstract public function find_actions_by_claim_id( $claim_id );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $comparison_operator
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function validate_sql_comparator( $comparison_operator ) {
|
||||||
|
if ( in_array( $comparison_operator, array('!=', '>', '>=', '<', '<=', '=') ) ) {
|
||||||
|
return $comparison_operator;
|
||||||
|
}
|
||||||
|
return '=';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the time MySQL formated date/time string for an action's (next) scheduled date.
|
||||||
|
*
|
||||||
|
* @param ActionScheduler_Action $action
|
||||||
|
* @param DateTime $scheduled_date (optional)
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function get_scheduled_date_string( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
|
||||||
|
$next = null === $scheduled_date ? $action->get_schedule()->next() : $scheduled_date;
|
||||||
|
if ( ! $next ) {
|
||||||
|
throw new InvalidArgumentException( __( 'Invalid schedule. Cannot save action.', 'action-scheduler' ) );
|
||||||
|
}
|
||||||
|
$next->setTimezone( new DateTimeZone( 'UTC' ) );
|
||||||
|
|
||||||
|
return $next->format( 'Y-m-d H:i:s' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the time MySQL formated date/time string for an action's (next) scheduled date.
|
||||||
|
*
|
||||||
|
* @param ActionScheduler_Action $action
|
||||||
|
* @param DateTime $scheduled_date (optional)
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function get_scheduled_date_string_local( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
|
||||||
|
$next = null === $scheduled_date ? $action->get_schedule()->next() : $scheduled_date;
|
||||||
|
if ( ! $next ) {
|
||||||
|
throw new InvalidArgumentException( __( 'Invalid schedule. Cannot save action.', 'action-scheduler' ) );
|
||||||
|
}
|
||||||
|
$next->setTimezone( $this->get_local_timezone() );
|
||||||
|
|
||||||
|
return $next->format( 'Y-m-d H:i:s' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the site's local time. Wrapper for ActionScheduler_TimezoneHelper::get_local_timezone().
|
||||||
|
*
|
||||||
|
* @return DateTimeZone
|
||||||
|
*/
|
||||||
|
protected function get_local_timezone() {
|
||||||
|
return ActionScheduler_TimezoneHelper::get_local_timezone();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function get_status_labels() {
|
||||||
|
return array(
|
||||||
|
self::STATUS_COMPLETE => __( 'Complete', 'action-scheduler' ),
|
||||||
|
self::STATUS_PENDING => __( 'Pending', 'action-scheduler' ),
|
||||||
|
self::STATUS_RUNNING => __( 'In-progress', 'action-scheduler' ),
|
||||||
|
self::STATUS_FAILED => __( 'Failed', 'action-scheduler' ),
|
||||||
|
self::STATUS_CANCELED => __( 'Canceled', 'action-scheduler' ),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function init() {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return ActionScheduler_Store
|
||||||
|
*/
|
||||||
|
public static function instance() {
|
||||||
|
if ( empty(self::$store) ) {
|
||||||
|
$class = apply_filters('action_scheduler_store_class', 'ActionScheduler_wpPostStore');
|
||||||
|
self::$store = new $class();
|
||||||
|
}
|
||||||
|
return self::$store;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,44 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_TimezoneHelper
|
||||||
|
*/
|
||||||
|
abstract class ActionScheduler_TimezoneHelper {
|
||||||
|
private static $local_timezone = NULL;
|
||||||
|
public static function get_local_timezone( $reset = FALSE ) {
|
||||||
|
if ( $reset ) {
|
||||||
|
self::$local_timezone = NULL;
|
||||||
|
}
|
||||||
|
if ( !isset(self::$local_timezone) ) {
|
||||||
|
$tzstring = get_option('timezone_string');
|
||||||
|
|
||||||
|
if ( empty($tzstring) ) {
|
||||||
|
$gmt_offset = get_option('gmt_offset');
|
||||||
|
if ( $gmt_offset == 0 ) {
|
||||||
|
$tzstring = 'UTC';
|
||||||
|
} else {
|
||||||
|
$gmt_offset *= HOUR_IN_SECONDS;
|
||||||
|
$tzstring = timezone_name_from_abbr('', $gmt_offset);
|
||||||
|
if ( false === $tzstring ) {
|
||||||
|
$is_dst = date( 'I' );
|
||||||
|
foreach ( timezone_abbreviations_list() as $abbr ) {
|
||||||
|
foreach ( $abbr as $city ) {
|
||||||
|
if ( $city['dst'] == $is_dst && $city['offset'] == $gmt_offset ) {
|
||||||
|
$tzstring = $city['timezone_id'];
|
||||||
|
break 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ( false === $tzstring ) {
|
||||||
|
$tzstring = 'UTC';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self::$local_timezone = new DateTimeZone($tzstring);
|
||||||
|
}
|
||||||
|
return self::$local_timezone;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,62 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_Versions
|
||||||
|
*/
|
||||||
|
class ActionScheduler_Versions {
|
||||||
|
/**
|
||||||
|
* @var ActionScheduler_Versions
|
||||||
|
*/
|
||||||
|
private static $instance = NULL;
|
||||||
|
|
||||||
|
private $versions = array();
|
||||||
|
|
||||||
|
public function register( $version_string, $initialization_callback ) {
|
||||||
|
if ( isset($this->versions[$version_string]) ) {
|
||||||
|
return FALSE;
|
||||||
|
}
|
||||||
|
$this->versions[$version_string] = $initialization_callback;
|
||||||
|
return TRUE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function get_versions() {
|
||||||
|
return $this->versions;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function latest_version() {
|
||||||
|
$keys = array_keys($this->versions);
|
||||||
|
if ( empty($keys) ) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
uasort( $keys, 'version_compare' );
|
||||||
|
return end($keys);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function latest_version_callback() {
|
||||||
|
$latest = $this->latest_version();
|
||||||
|
if ( empty($latest) || !isset($this->versions[$latest]) ) {
|
||||||
|
return '__return_null';
|
||||||
|
}
|
||||||
|
return $this->versions[$latest];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return ActionScheduler_Versions
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
public static function instance() {
|
||||||
|
if ( empty(self::$instance) ) {
|
||||||
|
self::$instance = new self();
|
||||||
|
}
|
||||||
|
return self::$instance;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
public static function initialize_latest_version() {
|
||||||
|
$self = self::instance();
|
||||||
|
call_user_func($self->latest_version_callback());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,204 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WP CLI Queue runner.
|
||||||
|
*
|
||||||
|
* This class can only be called from within a WP CLI instance.
|
||||||
|
*/
|
||||||
|
class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
|
||||||
|
|
||||||
|
/** @var array */
|
||||||
|
protected $actions;
|
||||||
|
|
||||||
|
/** @var ActionScheduler_ActionClaim */
|
||||||
|
protected $claim;
|
||||||
|
|
||||||
|
/** @var \cli\progress\Bar */
|
||||||
|
protected $progress_bar;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ActionScheduler_WPCLI_QueueRunner constructor.
|
||||||
|
*
|
||||||
|
* @param ActionScheduler_Store $store
|
||||||
|
* @param ActionScheduler_FatalErrorMonitor $monitor
|
||||||
|
* @param ActionScheduler_QueueCleaner $cleaner
|
||||||
|
*
|
||||||
|
* @throws Exception When this is not run within WP CLI
|
||||||
|
*/
|
||||||
|
public function __construct( ActionScheduler_Store $store = null, ActionScheduler_FatalErrorMonitor $monitor = null, ActionScheduler_QueueCleaner $cleaner = null ) {
|
||||||
|
if ( ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
|
||||||
|
throw new Exception( __( 'The ' . __CLASS__ . ' class can only be run within WP CLI.', 'action-scheduler' ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
parent::__construct( $store, $monitor, $cleaner );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set up the Queue before processing.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
*
|
||||||
|
* @param int $batch_size The batch size to process.
|
||||||
|
* @param array $hooks The hooks being used to filter the actions claimed in this batch.
|
||||||
|
* @param string $group The group of actions to claim with this batch.
|
||||||
|
* @param bool $force Whether to force running even with too many concurrent processes.
|
||||||
|
*
|
||||||
|
* @return int The number of actions that will be run.
|
||||||
|
* @throws \WP_CLI\ExitException When there are too many concurrent batches.
|
||||||
|
*/
|
||||||
|
public function setup( $batch_size, $hooks = array(), $group = '', $force = false ) {
|
||||||
|
$this->run_cleanup();
|
||||||
|
$this->add_hooks();
|
||||||
|
|
||||||
|
// Check to make sure there aren't too many concurrent processes running.
|
||||||
|
$claim_count = $this->store->get_claim_count();
|
||||||
|
$too_many = $claim_count >= $this->get_allowed_concurrent_batches();
|
||||||
|
if ( $too_many ) {
|
||||||
|
if ( $force ) {
|
||||||
|
WP_CLI::warning( __( 'There are too many concurrent batches, but the run is forced to continue.', 'action-scheduler' ) );
|
||||||
|
} else {
|
||||||
|
WP_CLI::error( __( 'There are too many concurrent batches.', 'action-scheduler' ) );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stake a claim and store it.
|
||||||
|
$this->claim = $this->store->stake_claim( $batch_size, null, $hooks, $group );
|
||||||
|
$this->monitor->attach( $this->claim );
|
||||||
|
$this->actions = $this->claim->get_actions();
|
||||||
|
|
||||||
|
return count( $this->actions );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add our hooks to the appropriate actions.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
*/
|
||||||
|
protected function add_hooks() {
|
||||||
|
add_action( 'action_scheduler_before_execute', array( $this, 'before_execute' ) );
|
||||||
|
add_action( 'action_scheduler_after_execute', array( $this, 'after_execute' ) );
|
||||||
|
add_action( 'action_scheduler_failed_execution', array( $this, 'action_failed' ), 10, 2 );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set up the WP CLI progress bar.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
*/
|
||||||
|
protected function setup_progress_bar() {
|
||||||
|
$count = count( $this->actions );
|
||||||
|
$this->progress_bar = \WP_CLI\Utils\make_progress_bar(
|
||||||
|
sprintf( _n( 'Running %d action', 'Running %d actions', $count, 'action-scheduler' ), number_format_i18n( $count ) ),
|
||||||
|
$count
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process actions in the queue.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
* @return int The number of actions processed.
|
||||||
|
*/
|
||||||
|
public function run() {
|
||||||
|
do_action( 'action_scheduler_before_process_queue' );
|
||||||
|
$this->setup_progress_bar();
|
||||||
|
foreach ( $this->actions as $action_id ) {
|
||||||
|
// Error if we lost the claim.
|
||||||
|
if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $this->claim->get_id() ) ) ) {
|
||||||
|
WP_CLI::warning( __( 'The claim has been lost. Aborting current batch.', 'action-scheduler' ) );
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->process_action( $action_id );
|
||||||
|
$this->progress_bar->tick();
|
||||||
|
|
||||||
|
// Free up memory after every 50 items
|
||||||
|
if ( 0 === $this->progress_bar->current() % 50 ) {
|
||||||
|
$this->stop_the_insanity();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$completed = $this->progress_bar->current();
|
||||||
|
$this->progress_bar->finish();
|
||||||
|
$this->store->release_claim( $this->claim );
|
||||||
|
do_action( 'action_scheduler_after_process_queue' );
|
||||||
|
|
||||||
|
return $completed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle WP CLI message when the action is starting.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
*
|
||||||
|
* @param $action_id
|
||||||
|
*/
|
||||||
|
public function before_execute( $action_id ) {
|
||||||
|
/* translators: %s refers to the action ID */
|
||||||
|
WP_CLI::log( sprintf( __( 'Started processing action %s', 'action-scheduler' ), $action_id ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle WP CLI message when the action has completed.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
*
|
||||||
|
* @param $action_id
|
||||||
|
*/
|
||||||
|
public function after_execute( $action_id ) {
|
||||||
|
/* translators: %s refers to the action ID */
|
||||||
|
WP_CLI::log( sprintf( __( 'Completed processing action %s', 'action-scheduler' ), $action_id ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle WP CLI message when the action has failed.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
*
|
||||||
|
* @param int $action_id
|
||||||
|
* @param Exception $exception
|
||||||
|
* @throws \WP_CLI\ExitException With failure message.
|
||||||
|
*/
|
||||||
|
public function action_failed( $action_id, $exception ) {
|
||||||
|
WP_CLI::error(
|
||||||
|
/* translators: %1$s refers to the action ID, %2$s refers to the Exception message */
|
||||||
|
sprintf( __( 'Error processing action %1$s: %2$s', 'action-scheduler' ), $action_id, $exception->getMessage() ),
|
||||||
|
false
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sleep and help avoid hitting memory limit
|
||||||
|
*
|
||||||
|
* @param int $sleep_time Amount of seconds to sleep
|
||||||
|
*/
|
||||||
|
protected function stop_the_insanity( $sleep_time = 0 ) {
|
||||||
|
if ( 0 < $sleep_time ) {
|
||||||
|
WP_CLI::warning( sprintf( 'Stopped the insanity for %d %s', $sleep_time, _n( 'second', 'seconds', $sleep_time ) ) );
|
||||||
|
sleep( $sleep_time );
|
||||||
|
}
|
||||||
|
|
||||||
|
WP_CLI::warning( __( 'Attempting to reduce used memory...', 'action-scheduler' ) );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var $wpdb \wpdb
|
||||||
|
* @var $wp_object_cache \WP_Object_Cache
|
||||||
|
*/
|
||||||
|
global $wpdb, $wp_object_cache;
|
||||||
|
|
||||||
|
$wpdb->queries = array();
|
||||||
|
|
||||||
|
if ( ! is_object( $wp_object_cache ) ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
$wp_object_cache->group_ops = array();
|
||||||
|
$wp_object_cache->stats = array();
|
||||||
|
$wp_object_cache->memcache_debug = array();
|
||||||
|
$wp_object_cache->cache = array();
|
||||||
|
|
||||||
|
if ( is_callable( array( $wp_object_cache, '__remoteset' ) ) ) {
|
||||||
|
call_user_func( array( $wp_object_cache, '__remoteset' ) ); // important
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,145 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Commands for the Action Scheduler by Prospress.
|
||||||
|
*/
|
||||||
|
class ActionScheduler_WPCLI_Scheduler_command extends WP_CLI_Command {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run the Action Scheduler
|
||||||
|
*
|
||||||
|
* ## OPTIONS
|
||||||
|
*
|
||||||
|
* [--batch-size=<size>]
|
||||||
|
* : The maximum number of actions to run. Defaults to 100.
|
||||||
|
*
|
||||||
|
* [--batches=<size>]
|
||||||
|
* : Limit execution to a number of batches. Defaults to 0, meaning batches will continue being executed until all actions are complete.
|
||||||
|
*
|
||||||
|
* [--cleanup-batch-size=<size>]
|
||||||
|
* : The maximum number of actions to clean up. Defaults to the value of --batch-size.
|
||||||
|
*
|
||||||
|
* [--hooks=<hooks>]
|
||||||
|
* : Only run actions with the specified hook. Omitting this option runs actions with any hook. Define multiple hooks as a comma separated string (without spaces), e.g. `--hooks=hook_one,hook_two,hook_three`
|
||||||
|
*
|
||||||
|
* [--group=<group>]
|
||||||
|
* : Only run actions from the specified group. Omitting this option runs actions from all groups.
|
||||||
|
*
|
||||||
|
* [--force]
|
||||||
|
* : Whether to force execution despite the maximum number of concurrent processes being exceeded.
|
||||||
|
*
|
||||||
|
* @param array $args Positional arguments.
|
||||||
|
* @param array $assoc_args Keyed arguments.
|
||||||
|
* @throws \WP_CLI\ExitException When an error occurs.
|
||||||
|
*/
|
||||||
|
public function run( $args, $assoc_args ) {
|
||||||
|
// Handle passed arguments.
|
||||||
|
$batch = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batch-size', 100 ) );
|
||||||
|
$batches = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batches', 0 ) );
|
||||||
|
$clean = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'cleanup-batch-size', $batch ) );
|
||||||
|
$hooks = explode( ',', WP_CLI\Utils\get_flag_value( $assoc_args, 'hooks', '' ) );
|
||||||
|
$hooks = array_filter( array_map( 'trim', $hooks ) );
|
||||||
|
$group = \WP_CLI\Utils\get_flag_value( $assoc_args, 'group', '' );
|
||||||
|
$force = \WP_CLI\Utils\get_flag_value( $assoc_args, 'force', false );
|
||||||
|
|
||||||
|
$batches_completed = 0;
|
||||||
|
$actions_completed = 0;
|
||||||
|
$unlimited = $batches === 0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Custom queue cleaner instance.
|
||||||
|
$cleaner = new ActionScheduler_QueueCleaner( null, $clean );
|
||||||
|
|
||||||
|
// Get the queue runner instance
|
||||||
|
$runner = new ActionScheduler_WPCLI_QueueRunner( null, null, $cleaner );
|
||||||
|
|
||||||
|
// Determine how many tasks will be run in the first batch.
|
||||||
|
$total = $runner->setup( $batch, $hooks, $group, $force );
|
||||||
|
|
||||||
|
// Run actions for as long as possible.
|
||||||
|
while ( $total > 0 ) {
|
||||||
|
$this->print_total_actions( $total );
|
||||||
|
$actions_completed += $runner->run();
|
||||||
|
$batches_completed++;
|
||||||
|
|
||||||
|
// Maybe set up tasks for the next batch.
|
||||||
|
$total = ( $unlimited || $batches_completed < $batches ) ? $runner->setup( $batch, $hooks, $group, $force ) : 0;
|
||||||
|
}
|
||||||
|
} catch ( Exception $e ) {
|
||||||
|
$this->print_error( $e );
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->print_total_batches( $batches_completed );
|
||||||
|
$this->print_success( $actions_completed );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Print WP CLI message about how many actions are about to be processed.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
*
|
||||||
|
* @param int $total
|
||||||
|
*/
|
||||||
|
protected function print_total_actions( $total ) {
|
||||||
|
WP_CLI::log(
|
||||||
|
sprintf(
|
||||||
|
/* translators: %d refers to how many scheduled taks were found to run */
|
||||||
|
_n( 'Found %d scheduled task', 'Found %d scheduled tasks', $total, 'action-scheduler' ),
|
||||||
|
number_format_i18n( $total )
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Print WP CLI message about how many batches of actions were processed.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
*
|
||||||
|
* @param int $batches_completed
|
||||||
|
*/
|
||||||
|
protected function print_total_batches( $batches_completed ) {
|
||||||
|
WP_CLI::log(
|
||||||
|
sprintf(
|
||||||
|
/* translators: %d refers to the total number of batches executed */
|
||||||
|
_n( '%d batch executed.', '%d batches executed.', $batches_completed, 'action-scheduler' ),
|
||||||
|
number_format_i18n( $batches_completed )
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert an exception into a WP CLI error.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
*
|
||||||
|
* @param Exception $e The error object.
|
||||||
|
*
|
||||||
|
* @throws \WP_CLI\ExitException
|
||||||
|
*/
|
||||||
|
protected function print_error( Exception $e ) {
|
||||||
|
WP_CLI::error(
|
||||||
|
sprintf(
|
||||||
|
/* translators: %s refers to the exception error message. */
|
||||||
|
__( 'There was an error running the action scheduler: %s', 'action-scheduler' ),
|
||||||
|
$e->getMessage()
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Print a success message with the number of completed actions.
|
||||||
|
*
|
||||||
|
* @author Jeremy Pry
|
||||||
|
*
|
||||||
|
* @param int $actions_completed
|
||||||
|
*/
|
||||||
|
protected function print_success( $actions_completed ) {
|
||||||
|
WP_CLI::success(
|
||||||
|
sprintf(
|
||||||
|
/* translators: %d refers to the total number of taskes completed */
|
||||||
|
_n( '%d scheduled task completed.', '%d scheduled tasks completed.', $actions_completed, 'action-scheduler' ),
|
||||||
|
number_format_i18n( $actions_completed )
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,278 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_wpCommentLogger
|
||||||
|
*/
|
||||||
|
class ActionScheduler_wpCommentLogger extends ActionScheduler_Logger {
|
||||||
|
const AGENT = 'ActionScheduler';
|
||||||
|
const TYPE = 'action_log';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
* @param string $message
|
||||||
|
* @param DateTime $date
|
||||||
|
*
|
||||||
|
* @return string The log entry ID
|
||||||
|
*/
|
||||||
|
public function log( $action_id, $message, DateTime $date = NULL ) {
|
||||||
|
if ( empty($date) ) {
|
||||||
|
$date = as_get_datetime_object();
|
||||||
|
} else {
|
||||||
|
$date = clone $date;
|
||||||
|
}
|
||||||
|
$comment_id = $this->create_wp_comment( $action_id, $message, $date );
|
||||||
|
return $comment_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function create_wp_comment( $action_id, $message, DateTime $date ) {
|
||||||
|
$comment_date_gmt = $date->format('Y-m-d H:i:s');
|
||||||
|
$date->setTimezone( ActionScheduler_TimezoneHelper::get_local_timezone() );
|
||||||
|
$comment_data = array(
|
||||||
|
'comment_post_ID' => $action_id,
|
||||||
|
'comment_date' => $date->format('Y-m-d H:i:s'),
|
||||||
|
'comment_date_gmt' => $comment_date_gmt,
|
||||||
|
'comment_author' => self::AGENT,
|
||||||
|
'comment_content' => $message,
|
||||||
|
'comment_agent' => self::AGENT,
|
||||||
|
'comment_type' => self::TYPE,
|
||||||
|
);
|
||||||
|
return wp_insert_comment($comment_data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $entry_id
|
||||||
|
*
|
||||||
|
* @return ActionScheduler_LogEntry
|
||||||
|
*/
|
||||||
|
public function get_entry( $entry_id ) {
|
||||||
|
$comment = $this->get_comment( $entry_id );
|
||||||
|
if ( empty($comment) || $comment->comment_type != self::TYPE ) {
|
||||||
|
return new ActionScheduler_NullLogEntry();
|
||||||
|
}
|
||||||
|
|
||||||
|
$date = as_get_datetime_object( $comment->comment_date_gmt );
|
||||||
|
$date->setTimezone( ActionScheduler_TimezoneHelper::get_local_timezone() );
|
||||||
|
return new ActionScheduler_LogEntry( $comment->comment_post_ID, $comment->comment_content, $date );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*
|
||||||
|
* @return ActionScheduler_LogEntry[]
|
||||||
|
*/
|
||||||
|
public function get_logs( $action_id ) {
|
||||||
|
$status = 'all';
|
||||||
|
if ( get_post_status($action_id) == 'trash' ) {
|
||||||
|
$status = 'post-trashed';
|
||||||
|
}
|
||||||
|
$comments = get_comments(array(
|
||||||
|
'post_id' => $action_id,
|
||||||
|
'orderby' => 'comment_date_gmt',
|
||||||
|
'order' => 'ASC',
|
||||||
|
'type' => self::TYPE,
|
||||||
|
'status' => $status,
|
||||||
|
));
|
||||||
|
$logs = array();
|
||||||
|
foreach ( $comments as $c ) {
|
||||||
|
$entry = $this->get_entry( $c );
|
||||||
|
if ( !empty($entry) ) {
|
||||||
|
$logs[] = $entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $logs;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function get_comment( $comment_id ) {
|
||||||
|
return get_comment( $comment_id );
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param WP_Comment_Query $query
|
||||||
|
*/
|
||||||
|
public function filter_comment_queries( $query ) {
|
||||||
|
foreach ( array('ID', 'parent', 'post_author', 'post_name', 'post_parent', 'type', 'post_type', 'post_id', 'post_ID') as $key ) {
|
||||||
|
if ( !empty($query->query_vars[$key]) ) {
|
||||||
|
return; // don't slow down queries that wouldn't include action_log comments anyway
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$query->query_vars['action_log_filter'] = TRUE;
|
||||||
|
add_filter( 'comments_clauses', array( $this, 'filter_comment_query_clauses' ), 10, 2 );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $clauses
|
||||||
|
* @param WP_Comment_Query $query
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function filter_comment_query_clauses( $clauses, $query ) {
|
||||||
|
if ( !empty($query->query_vars['action_log_filter']) ) {
|
||||||
|
$clauses['where'] .= $this->get_where_clause();
|
||||||
|
}
|
||||||
|
return $clauses;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Make sure Action Scheduler logs are excluded from comment feeds, which use WP_Query, not
|
||||||
|
* the WP_Comment_Query class handled by @see self::filter_comment_queries().
|
||||||
|
*
|
||||||
|
* @param string $where
|
||||||
|
* @param WP_Query $query
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
public function filter_comment_feed( $where, $query ) {
|
||||||
|
if ( is_comment_feed() ) {
|
||||||
|
$where .= $this->get_where_clause();
|
||||||
|
}
|
||||||
|
return $where;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a SQL clause to exclude Action Scheduler comments.
|
||||||
|
*
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function get_where_clause() {
|
||||||
|
global $wpdb;
|
||||||
|
return sprintf( " AND {$wpdb->comments}.comment_type != '%s'", self::TYPE );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove action log entries from wp_count_comments()
|
||||||
|
*
|
||||||
|
* @param array $stats
|
||||||
|
* @param int $post_id
|
||||||
|
*
|
||||||
|
* @return object
|
||||||
|
*/
|
||||||
|
public function filter_comment_count( $stats, $post_id ) {
|
||||||
|
global $wpdb;
|
||||||
|
|
||||||
|
if ( 0 === $post_id ) {
|
||||||
|
$stats = $this->get_comment_count();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve the comment counts from our cache, or the database if the cached version isn't set.
|
||||||
|
*
|
||||||
|
* @return object
|
||||||
|
*/
|
||||||
|
protected function get_comment_count() {
|
||||||
|
global $wpdb;
|
||||||
|
|
||||||
|
$stats = get_transient( 'as_comment_count' );
|
||||||
|
|
||||||
|
if ( ! $stats ) {
|
||||||
|
$stats = array();
|
||||||
|
|
||||||
|
$count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} WHERE comment_type NOT IN('order_note','action_log') GROUP BY comment_approved", ARRAY_A );
|
||||||
|
|
||||||
|
$total = 0;
|
||||||
|
$stats = array();
|
||||||
|
$approved = array( '0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed' );
|
||||||
|
|
||||||
|
foreach ( (array) $count as $row ) {
|
||||||
|
// Don't count post-trashed toward totals
|
||||||
|
if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) {
|
||||||
|
$total += $row['num_comments'];
|
||||||
|
}
|
||||||
|
if ( isset( $approved[ $row['comment_approved'] ] ) ) {
|
||||||
|
$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$stats['total_comments'] = $total;
|
||||||
|
$stats['all'] = $total;
|
||||||
|
|
||||||
|
foreach ( $approved as $key ) {
|
||||||
|
if ( empty( $stats[ $key ] ) ) {
|
||||||
|
$stats[ $key ] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$stats = (object) $stats;
|
||||||
|
set_transient( 'as_comment_count', $stats );
|
||||||
|
}
|
||||||
|
|
||||||
|
return $stats;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete comment count cache whenever there is new comment or the status of a comment changes. Cache
|
||||||
|
* will be regenerated next time ActionScheduler_wpCommentLogger::filter_comment_count() is called.
|
||||||
|
*/
|
||||||
|
public function delete_comment_count_cache() {
|
||||||
|
delete_transient( 'as_comment_count' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
public function init() {
|
||||||
|
add_action( 'action_scheduler_before_process_queue', array( $this, 'disable_comment_counting' ), 10, 0 );
|
||||||
|
add_action( 'action_scheduler_after_process_queue', array( $this, 'enable_comment_counting' ), 10, 0 );
|
||||||
|
add_action( 'action_scheduler_stored_action', array( $this, 'log_stored_action' ), 10, 1 );
|
||||||
|
add_action( 'action_scheduler_canceled_action', array( $this, 'log_canceled_action' ), 10, 1 );
|
||||||
|
add_action( 'action_scheduler_before_execute', array( $this, 'log_started_action' ), 10, 1 );
|
||||||
|
add_action( 'action_scheduler_after_execute', array( $this, 'log_completed_action' ), 10, 1 );
|
||||||
|
add_action( 'action_scheduler_failed_execution', array( $this, 'log_failed_action' ), 10, 2 );
|
||||||
|
add_action( 'action_scheduler_failed_action', array( $this, 'log_timed_out_action' ), 10, 2 );
|
||||||
|
add_action( 'action_scheduler_unexpected_shutdown', array( $this, 'log_unexpected_shutdown' ), 10, 2 );
|
||||||
|
add_action( 'action_scheduler_reset_action', array( $this, 'log_reset_action' ), 10, 1 );
|
||||||
|
add_action( 'pre_get_comments', array( $this, 'filter_comment_queries' ), 10, 1 );
|
||||||
|
add_action( 'wp_count_comments', array( $this, 'filter_comment_count' ), 20, 2 ); // run after WC_Comments::wp_count_comments() to make sure we exclude order notes and action logs
|
||||||
|
add_action( 'comment_feed_where', array( $this, 'filter_comment_feed' ), 10, 2 );
|
||||||
|
|
||||||
|
// Delete comments count cache whenever there is a new comment or a comment status changes
|
||||||
|
add_action( 'wp_insert_comment', array( $this, 'delete_comment_count_cache' ) );
|
||||||
|
add_action( 'wp_set_comment_status', array( $this, 'delete_comment_count_cache' ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function disable_comment_counting() {
|
||||||
|
wp_defer_comment_counting(true);
|
||||||
|
}
|
||||||
|
public function enable_comment_counting() {
|
||||||
|
wp_defer_comment_counting(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function log_stored_action( $action_id ) {
|
||||||
|
$this->log( $action_id, __('action created', 'action-scheduler') );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function log_canceled_action( $action_id ) {
|
||||||
|
$this->log( $action_id, __('action canceled', 'action-scheduler') );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function log_started_action( $action_id ) {
|
||||||
|
$this->log( $action_id, __('action started', 'action-scheduler') );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function log_completed_action( $action_id ) {
|
||||||
|
$this->log( $action_id, __('action complete', 'action-scheduler') );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function log_failed_action( $action_id, Exception $exception ) {
|
||||||
|
$this->log( $action_id, sprintf(__('action failed: %s', 'action-scheduler'), $exception->getMessage() ));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function log_timed_out_action( $action_id, $timeout) {
|
||||||
|
$this->log( $action_id, sprintf( __('action timed out after %s seconds', 'action-scheduler'), $timeout ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function log_unexpected_shutdown( $action_id, $error ) {
|
||||||
|
if ( !empty($error) ) {
|
||||||
|
$this->log( $action_id, sprintf(__('unexpected shutdown: PHP Fatal error %s in %s on line %s', 'action-scheduler'), $error['message'], $error['file'], $error['line'] ) );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function log_reset_action( $action_id ) {
|
||||||
|
$this->log( $action_id, __('action reset', 'action_scheduler') );
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -0,0 +1,732 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_wpPostStore
|
||||||
|
*/
|
||||||
|
class ActionScheduler_wpPostStore extends ActionScheduler_Store {
|
||||||
|
const POST_TYPE = 'scheduled-action';
|
||||||
|
const GROUP_TAXONOMY = 'action-group';
|
||||||
|
const SCHEDULE_META_KEY = '_action_manager_schedule';
|
||||||
|
|
||||||
|
/** @var DateTimeZone */
|
||||||
|
protected $local_timezone = NULL;
|
||||||
|
|
||||||
|
public function save_action( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ){
|
||||||
|
try {
|
||||||
|
$post_array = $this->create_post_array( $action, $scheduled_date );
|
||||||
|
$post_id = $this->save_post_array( $post_array );
|
||||||
|
$this->save_post_schedule( $post_id, $action->get_schedule() );
|
||||||
|
$this->save_action_group( $post_id, $action->get_group() );
|
||||||
|
do_action( 'action_scheduler_stored_action', $post_id );
|
||||||
|
return $post_id;
|
||||||
|
} catch ( Exception $e ) {
|
||||||
|
throw new RuntimeException( sprintf( __('Error saving action: %s', 'action-scheduler'), $e->getMessage() ), 0 );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function create_post_array( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
|
||||||
|
$post = array(
|
||||||
|
'post_type' => self::POST_TYPE,
|
||||||
|
'post_title' => $action->get_hook(),
|
||||||
|
'post_content' => json_encode($action->get_args()),
|
||||||
|
'post_status' => ( $action->is_finished() ? 'publish' : 'pending' ),
|
||||||
|
'post_date_gmt' => $this->get_scheduled_date_string( $action, $scheduled_date ),
|
||||||
|
'post_date' => $this->get_scheduled_date_string_local( $action, $scheduled_date ),
|
||||||
|
);
|
||||||
|
return $post;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function save_post_array( $post_array ) {
|
||||||
|
add_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 );
|
||||||
|
$post_id = wp_insert_post($post_array);
|
||||||
|
remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10 );
|
||||||
|
|
||||||
|
if ( is_wp_error($post_id) || empty($post_id) ) {
|
||||||
|
throw new RuntimeException(__('Unable to save action.', 'action-scheduler'));
|
||||||
|
}
|
||||||
|
return $post_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function filter_insert_post_data( $postdata ) {
|
||||||
|
if ( $postdata['post_type'] == self::POST_TYPE ) {
|
||||||
|
$postdata['post_author'] = 0;
|
||||||
|
if ( $postdata['post_status'] == 'future' ) {
|
||||||
|
$postdata['post_status'] = 'publish';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $postdata;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function save_post_schedule( $post_id, $schedule ) {
|
||||||
|
update_post_meta( $post_id, self::SCHEDULE_META_KEY, $schedule );
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function save_action_group( $post_id, $group ) {
|
||||||
|
if ( empty($group) ) {
|
||||||
|
wp_set_object_terms( $post_id, array(), self::GROUP_TAXONOMY, FALSE );
|
||||||
|
} else {
|
||||||
|
wp_set_object_terms( $post_id, array($group), self::GROUP_TAXONOMY, FALSE );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function fetch_action( $action_id ) {
|
||||||
|
$post = $this->get_post( $action_id );
|
||||||
|
if ( empty($post) || $post->post_type != self::POST_TYPE ) {
|
||||||
|
return $this->get_null_action();
|
||||||
|
}
|
||||||
|
return $this->make_action_from_post($post);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function get_post( $action_id ) {
|
||||||
|
if ( empty($action_id) ) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
return get_post($action_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function get_null_action() {
|
||||||
|
return new ActionScheduler_NullAction();
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function make_action_from_post( $post ) {
|
||||||
|
$hook = $post->post_title;
|
||||||
|
$args = json_decode( $post->post_content, true );
|
||||||
|
$schedule = get_post_meta( $post->ID, self::SCHEDULE_META_KEY, true );
|
||||||
|
if ( empty($schedule) ) {
|
||||||
|
$schedule = new ActionScheduler_NullSchedule();
|
||||||
|
}
|
||||||
|
$group = wp_get_object_terms( $post->ID, self::GROUP_TAXONOMY, array('fields' => 'names') );
|
||||||
|
$group = empty( $group ) ? '' : reset($group);
|
||||||
|
|
||||||
|
return ActionScheduler::factory()->get_stored_action( $this->get_action_status_by_post_status( $post->post_status ), $hook, $args, $schedule, $group );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $post_status
|
||||||
|
*
|
||||||
|
* @throws InvalidArgumentException if $post_status not in known status fields returned by $this->get_status_labels()
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function get_action_status_by_post_status( $post_status ) {
|
||||||
|
|
||||||
|
switch ( $post_status ) {
|
||||||
|
case 'publish' :
|
||||||
|
$action_status = self::STATUS_COMPLETE;
|
||||||
|
break;
|
||||||
|
case 'trash' :
|
||||||
|
$action_status = self::STATUS_CANCELED;
|
||||||
|
break;
|
||||||
|
default :
|
||||||
|
if ( ! array_key_exists( $post_status, $this->get_status_labels() ) ) {
|
||||||
|
throw new InvalidArgumentException( sprintf( 'Invalid post status: "%s". No matching action status available.', $post_status ) );
|
||||||
|
}
|
||||||
|
$action_status = $post_status;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $action_status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_status
|
||||||
|
* @throws InvalidArgumentException if $post_status not in known status fields returned by $this->get_status_labels()
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
protected function get_post_status_by_action_status( $action_status ) {
|
||||||
|
|
||||||
|
switch ( $action_status ) {
|
||||||
|
case self::STATUS_COMPLETE :
|
||||||
|
$post_status = 'publish';
|
||||||
|
break;
|
||||||
|
case self::STATUS_CANCELED :
|
||||||
|
$post_status = 'trash';
|
||||||
|
break;
|
||||||
|
default :
|
||||||
|
if ( ! array_key_exists( $action_status, $this->get_status_labels() ) ) {
|
||||||
|
throw new InvalidArgumentException( sprintf( 'Invalid action status: "%s".', $action_status ) );
|
||||||
|
}
|
||||||
|
$post_status = $action_status;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $post_status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $hook
|
||||||
|
* @param array $params
|
||||||
|
*
|
||||||
|
* @return string ID of the next action matching the criteria or NULL if not found
|
||||||
|
*/
|
||||||
|
public function find_action( $hook, $params = array() ) {
|
||||||
|
$params = wp_parse_args( $params, array(
|
||||||
|
'args' => NULL,
|
||||||
|
'status' => ActionScheduler_Store::STATUS_PENDING,
|
||||||
|
'group' => '',
|
||||||
|
));
|
||||||
|
/** @var wpdb $wpdb */
|
||||||
|
global $wpdb;
|
||||||
|
$query = "SELECT p.ID FROM {$wpdb->posts} p";
|
||||||
|
$args = array();
|
||||||
|
if ( !empty($params['group']) ) {
|
||||||
|
$query .= " INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID";
|
||||||
|
$query .= " INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id";
|
||||||
|
$query .= " INNER JOIN {$wpdb->terms} t ON tt.term_id=t.term_id AND t.slug=%s";
|
||||||
|
$args[] = $params['group'];
|
||||||
|
}
|
||||||
|
$query .= " WHERE p.post_title=%s";
|
||||||
|
$args[] = $hook;
|
||||||
|
$query .= " AND p.post_type=%s";
|
||||||
|
$args[] = self::POST_TYPE;
|
||||||
|
if ( !is_null($params['args']) ) {
|
||||||
|
$query .= " AND p.post_content=%s";
|
||||||
|
$args[] = json_encode($params['args']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( ! empty( $params['status'] ) ) {
|
||||||
|
$query .= " AND p.post_status=%s";
|
||||||
|
$args[] = $this->get_post_status_by_action_status( $params['status'] );
|
||||||
|
}
|
||||||
|
|
||||||
|
switch ( $params['status'] ) {
|
||||||
|
case self::STATUS_COMPLETE:
|
||||||
|
case self::STATUS_RUNNING:
|
||||||
|
case self::STATUS_FAILED:
|
||||||
|
$order = 'DESC'; // Find the most recent action that matches
|
||||||
|
break;
|
||||||
|
case self::STATUS_PENDING:
|
||||||
|
default:
|
||||||
|
$order = 'ASC'; // Find the next action that matches
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
$query .= " ORDER BY post_date_gmt $order LIMIT 1";
|
||||||
|
|
||||||
|
$query = $wpdb->prepare( $query, $args );
|
||||||
|
|
||||||
|
$id = $wpdb->get_var($query);
|
||||||
|
return $id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the SQL statement to query (or count) actions.
|
||||||
|
*
|
||||||
|
* @param array $query Filtering options
|
||||||
|
* @param string $select_or_count Whether the SQL should select and return the IDs or just the row count
|
||||||
|
* @throws InvalidArgumentException if $select_or_count not count or select
|
||||||
|
* @return string SQL statement. The returned SQL is already properly escaped.
|
||||||
|
*/
|
||||||
|
protected function get_query_actions_sql( array $query, $select_or_count = 'select' ) {
|
||||||
|
|
||||||
|
if ( ! in_array( $select_or_count, array( 'select', 'count' ) ) ) {
|
||||||
|
throw new InvalidArgumentException(__('Invalid schedule. Cannot save action.', 'action-scheduler'));
|
||||||
|
}
|
||||||
|
|
||||||
|
$query = wp_parse_args( $query, array(
|
||||||
|
'hook' => '',
|
||||||
|
'args' => NULL,
|
||||||
|
'date' => NULL,
|
||||||
|
'date_compare' => '<=',
|
||||||
|
'modified' => NULL,
|
||||||
|
'modified_compare' => '<=',
|
||||||
|
'group' => '',
|
||||||
|
'status' => '',
|
||||||
|
'claimed' => NULL,
|
||||||
|
'per_page' => 5,
|
||||||
|
'offset' => 0,
|
||||||
|
'orderby' => 'date',
|
||||||
|
'order' => 'ASC',
|
||||||
|
'search' => '',
|
||||||
|
) );
|
||||||
|
|
||||||
|
/** @var wpdb $wpdb */
|
||||||
|
global $wpdb;
|
||||||
|
$sql = ( 'count' === $select_or_count ) ? 'SELECT count(p.ID)' : 'SELECT p.ID ';
|
||||||
|
$sql .= "FROM {$wpdb->posts} p";
|
||||||
|
$sql_params = array();
|
||||||
|
if ( ! empty( $query['group'] ) || 'group' === $query['orderby'] ) {
|
||||||
|
$sql .= " INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID";
|
||||||
|
$sql .= " INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id";
|
||||||
|
$sql .= " INNER JOIN {$wpdb->terms} t ON tt.term_id=t.term_id";
|
||||||
|
|
||||||
|
if ( ! empty( $query['group'] ) ) {
|
||||||
|
$sql .= " AND t.slug=%s";
|
||||||
|
$sql_params[] = $query['group'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$sql .= " WHERE post_type=%s";
|
||||||
|
$sql_params[] = self::POST_TYPE;
|
||||||
|
if ( $query['hook'] ) {
|
||||||
|
$sql .= " AND p.post_title=%s";
|
||||||
|
$sql_params[] = $query['hook'];
|
||||||
|
}
|
||||||
|
if ( !is_null($query['args']) ) {
|
||||||
|
$sql .= " AND p.post_content=%s";
|
||||||
|
$sql_params[] = json_encode($query['args']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( ! empty( $query['status'] ) ) {
|
||||||
|
$sql .= " AND p.post_status=%s";
|
||||||
|
$sql_params[] = $this->get_post_status_by_action_status( $query['status'] );
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( $query['date'] instanceof DateTime ) {
|
||||||
|
$date = clone $query['date'];
|
||||||
|
$date->setTimezone( new DateTimeZone('UTC') );
|
||||||
|
$date_string = $date->format('Y-m-d H:i:s');
|
||||||
|
$comparator = $this->validate_sql_comparator($query['date_compare']);
|
||||||
|
$sql .= " AND p.post_date_gmt $comparator %s";
|
||||||
|
$sql_params[] = $date_string;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( $query['modified'] instanceof DateTime ) {
|
||||||
|
$modified = clone $query['modified'];
|
||||||
|
$modified->setTimezone( new DateTimeZone('UTC') );
|
||||||
|
$date_string = $modified->format('Y-m-d H:i:s');
|
||||||
|
$comparator = $this->validate_sql_comparator($query['modified_compare']);
|
||||||
|
$sql .= " AND p.post_modified_gmt $comparator %s";
|
||||||
|
$sql_params[] = $date_string;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( $query['claimed'] === TRUE ) {
|
||||||
|
$sql .= " AND p.post_password != ''";
|
||||||
|
} elseif ( $query['claimed'] === FALSE ) {
|
||||||
|
$sql .= " AND p.post_password = ''";
|
||||||
|
} elseif ( !is_null($query['claimed']) ) {
|
||||||
|
$sql .= " AND p.post_password = %s";
|
||||||
|
$sql_params[] = $query['claimed'];
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( ! empty( $query['search'] ) ) {
|
||||||
|
$sql .= " AND (p.post_title LIKE %s OR p.post_content LIKE %s OR p.post_password LIKE %s)";
|
||||||
|
for( $i = 0; $i < 3; $i++ ) {
|
||||||
|
$sql_params[] = sprintf( '%%%s%%', $query['search'] );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( 'select' === $select_or_count ) {
|
||||||
|
switch ( $query['orderby'] ) {
|
||||||
|
case 'hook':
|
||||||
|
$orderby = 'p.post_title';
|
||||||
|
break;
|
||||||
|
case 'group':
|
||||||
|
$orderby = 't.name';
|
||||||
|
break;
|
||||||
|
case 'status':
|
||||||
|
$orderby = 'p.post_status';
|
||||||
|
break;
|
||||||
|
case 'modified':
|
||||||
|
$orderby = 'p.post_modified';
|
||||||
|
break;
|
||||||
|
case 'claim_id':
|
||||||
|
$orderby = 'p.post_password';
|
||||||
|
break;
|
||||||
|
case 'schedule':
|
||||||
|
case 'date':
|
||||||
|
default:
|
||||||
|
$orderby = 'p.post_date_gmt';
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if ( 'ASC' === strtoupper( $query['order'] ) ) {
|
||||||
|
$order = 'ASC';
|
||||||
|
} else {
|
||||||
|
$order = 'DESC';
|
||||||
|
}
|
||||||
|
$sql .= " ORDER BY $orderby $order";
|
||||||
|
if ( $query['per_page'] > 0 ) {
|
||||||
|
$sql .= " LIMIT %d, %d";
|
||||||
|
$sql_params[] = $query['offset'];
|
||||||
|
$sql_params[] = $query['per_page'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $wpdb->prepare( $sql, $sql_params );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param array $query
|
||||||
|
* @param string $query_type Whether to select or count the results. Default, select.
|
||||||
|
* @return string|array The IDs of actions matching the query
|
||||||
|
*/
|
||||||
|
public function query_actions( $query = array(), $query_type = 'select' ) {
|
||||||
|
/** @var wpdb $wpdb */
|
||||||
|
global $wpdb;
|
||||||
|
|
||||||
|
$sql = $this->get_query_actions_sql( $query, $query_type );
|
||||||
|
|
||||||
|
return ( 'count' === $query_type ) ? $wpdb->get_var( $sql ) : $wpdb->get_col( $sql );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a count of all actions in the store, grouped by status
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function action_counts() {
|
||||||
|
|
||||||
|
$action_counts_by_status = array();
|
||||||
|
$action_stati_and_labels = $this->get_status_labels();
|
||||||
|
$posts_count_by_status = (array) wp_count_posts( self::POST_TYPE, 'readable' );
|
||||||
|
|
||||||
|
foreach ( $posts_count_by_status as $post_status_name => $count ) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
$action_status_name = $this->get_action_status_by_post_status( $post_status_name );
|
||||||
|
} catch ( Exception $e ) {
|
||||||
|
// Ignore any post statuses that aren't for actions
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ( array_key_exists( $action_status_name, $action_stati_and_labels ) ) {
|
||||||
|
$action_counts_by_status[ $action_status_name ] = $count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $action_counts_by_status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*
|
||||||
|
* @throws InvalidArgumentException
|
||||||
|
*/
|
||||||
|
public function cancel_action( $action_id ) {
|
||||||
|
$post = get_post($action_id);
|
||||||
|
if ( empty($post) || ($post->post_type != self::POST_TYPE) ) {
|
||||||
|
throw new InvalidArgumentException(sprintf(__('Unidentified action %s', 'action-scheduler'), $action_id));
|
||||||
|
}
|
||||||
|
do_action( 'action_scheduler_canceled_action', $action_id );
|
||||||
|
wp_trash_post($action_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function delete_action( $action_id ) {
|
||||||
|
$post = get_post($action_id);
|
||||||
|
if ( empty($post) || ($post->post_type != self::POST_TYPE) ) {
|
||||||
|
throw new InvalidArgumentException(sprintf(__('Unidentified action %s', 'action-scheduler'), $action_id));
|
||||||
|
}
|
||||||
|
do_action( 'action_scheduler_deleted_action', $action_id );
|
||||||
|
wp_delete_post($action_id, TRUE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*
|
||||||
|
* @throws InvalidArgumentException
|
||||||
|
* @return DateTime The date the action is schedule to run, or the date that it ran.
|
||||||
|
*/
|
||||||
|
public function get_date( $action_id ) {
|
||||||
|
$date = $this->get_date_gmt( $action_id );
|
||||||
|
return $date->setTimezone( $this->get_local_timezone() );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*
|
||||||
|
* @throws InvalidArgumentException
|
||||||
|
* @return DateTime The date the action is schedule to run, or the date that it ran.
|
||||||
|
*/
|
||||||
|
public function get_date_gmt( $action_id ) {
|
||||||
|
$post = get_post($action_id);
|
||||||
|
if ( empty($post) || ($post->post_type != self::POST_TYPE) ) {
|
||||||
|
throw new InvalidArgumentException(sprintf(__('Unidentified action %s', 'action-scheduler'), $action_id));
|
||||||
|
}
|
||||||
|
if ( $post->post_status == 'publish' ) {
|
||||||
|
return as_get_datetime_object($post->post_modified_gmt);
|
||||||
|
} else {
|
||||||
|
return as_get_datetime_object($post->post_date_gmt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param int $max_actions
|
||||||
|
* @param DateTime $before_date Jobs must be schedule before this date. Defaults to now.
|
||||||
|
* @param array $hooks Claim only actions with a hook or hooks.
|
||||||
|
* @param string $group Claim only actions in the given group.
|
||||||
|
*
|
||||||
|
* @return ActionScheduler_ActionClaim
|
||||||
|
* @throws RuntimeException When there is an error staking a claim.
|
||||||
|
* @throws InvalidArgumentException When the given group is not valid.
|
||||||
|
*/
|
||||||
|
public function stake_claim( $max_actions = 10, DateTime $before_date = null, $hooks = array(), $group = '' ) {
|
||||||
|
$claim_id = $this->generate_claim_id();
|
||||||
|
$this->claim_actions( $claim_id, $max_actions, $before_date, $hooks, $group );
|
||||||
|
$action_ids = $this->find_actions_by_claim_id( $claim_id );
|
||||||
|
|
||||||
|
return new ActionScheduler_ActionClaim( $claim_id, $action_ids );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
public function get_claim_count(){
|
||||||
|
global $wpdb;
|
||||||
|
|
||||||
|
$sql = "SELECT COUNT(DISTINCT post_password) FROM {$wpdb->posts} WHERE post_password != '' AND post_type = %s AND post_status IN ('in-progress','pending')";
|
||||||
|
$sql = $wpdb->prepare( $sql, array( self::POST_TYPE ) );
|
||||||
|
|
||||||
|
return $wpdb->get_var( $sql );
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function generate_claim_id() {
|
||||||
|
$claim_id = md5(microtime(true) . rand(0,1000));
|
||||||
|
return substr($claim_id, 0, 20); // to fit in db field with 20 char limit
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $claim_id
|
||||||
|
* @param int $limit
|
||||||
|
* @param DateTime $before_date Should use UTC timezone.
|
||||||
|
* @param array $hooks Claim only actions with a hook or hooks.
|
||||||
|
* @param string $group Claim only actions in the given group.
|
||||||
|
*
|
||||||
|
* @return int The number of actions that were claimed
|
||||||
|
* @throws RuntimeException When there is a database error.
|
||||||
|
* @throws InvalidArgumentException When the group is invalid.
|
||||||
|
*/
|
||||||
|
protected function claim_actions( $claim_id, $limit, DateTime $before_date = null, $hooks = array(), $group = '' ) {
|
||||||
|
// Set up initial variables.
|
||||||
|
$date = null === $before_date ? as_get_datetime_object() : clone $before_date;
|
||||||
|
$limit_ids = ! empty( $group );
|
||||||
|
$ids = $limit_ids ? $this->get_actions_by_group( $group, $limit, $date ) : array();
|
||||||
|
|
||||||
|
// If limiting by IDs and no posts found, then return early since we have nothing to update.
|
||||||
|
if ( $limit_ids && 0 === count( $ids ) ) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @var wpdb $wpdb */
|
||||||
|
global $wpdb;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Build up custom query to update the affected posts. Parameters are built as a separate array
|
||||||
|
* to make it easier to identify where they are in the query.
|
||||||
|
*
|
||||||
|
* We can't use $wpdb->update() here because of the "ID IN ..." clause.
|
||||||
|
*/
|
||||||
|
$update = "UPDATE {$wpdb->posts} SET post_password = %s, post_modified_gmt = %s, post_modified = %s";
|
||||||
|
$params = array(
|
||||||
|
$claim_id,
|
||||||
|
current_time( 'mysql', true ),
|
||||||
|
current_time( 'mysql' ),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Build initial WHERE clause.
|
||||||
|
$where = "WHERE post_type = %s AND post_status = %s AND post_password = ''";
|
||||||
|
$params[] = self::POST_TYPE;
|
||||||
|
$params[] = ActionScheduler_Store::STATUS_PENDING;
|
||||||
|
|
||||||
|
if ( ! empty( $hooks ) ) {
|
||||||
|
$placeholders = array_fill( 0, count( $hooks ), '%s' );
|
||||||
|
$where .= ' AND post_title IN (' . join( ', ', $placeholders ) . ')';
|
||||||
|
$params = array_merge( $params, array_values( $hooks ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Add the IDs to the WHERE clause. IDs not escaped because they came directly from a prior DB query.
|
||||||
|
*
|
||||||
|
* If we're not limiting by IDs, then include the post_date_gmt clause.
|
||||||
|
*/
|
||||||
|
if ( $limit_ids ) {
|
||||||
|
$where .= ' AND ID IN (' . join( ',', $ids ) . ')';
|
||||||
|
} else {
|
||||||
|
$where .= ' AND post_date_gmt <= %s';
|
||||||
|
$params[] = $date->format( 'Y-m-d H:i:s' );
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add the ORDER BY clause and,ms limit.
|
||||||
|
$order = 'ORDER BY menu_order ASC, post_date_gmt ASC, ID ASC LIMIT %d';
|
||||||
|
$params[] = $limit;
|
||||||
|
|
||||||
|
// Run the query and gather results.
|
||||||
|
$rows_affected = $wpdb->query( $wpdb->prepare( "{$update} {$where} {$order}", $params ) );
|
||||||
|
if ( $rows_affected === false ) {
|
||||||
|
throw new RuntimeException( __( 'Unable to claim actions. Database error.', 'action-scheduler' ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
return (int) $rows_affected;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get IDs of actions within a certain group and up to a certain date/time.
|
||||||
|
*
|
||||||
|
* @param string $group The group to use in finding actions.
|
||||||
|
* @param int $limit The number of actions to retrieve.
|
||||||
|
* @param DateTime $date DateTime object representing cutoff time for actions. Actions retrieved will be
|
||||||
|
* up to and including this DateTime.
|
||||||
|
*
|
||||||
|
* @return array IDs of actions in the appropriate group and before the appropriate time.
|
||||||
|
* @throws InvalidArgumentException When the group does not exist.
|
||||||
|
*/
|
||||||
|
protected function get_actions_by_group( $group, $limit, DateTime $date ) {
|
||||||
|
// Ensure the group exists before continuing.
|
||||||
|
if ( ! term_exists( $group, self::GROUP_TAXONOMY )) {
|
||||||
|
throw new InvalidArgumentException( sprintf( __( 'The group "%s" does not exist.', 'action-scheduler' ), $group ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set up a query for post IDs to use later.
|
||||||
|
$query = new WP_Query();
|
||||||
|
$query_args = array(
|
||||||
|
'fields' => 'ids',
|
||||||
|
'post_type' => self::POST_TYPE,
|
||||||
|
'post_status' => ActionScheduler_Store::STATUS_PENDING,
|
||||||
|
'has_password' => false,
|
||||||
|
'posts_per_page' => $limit * 3,
|
||||||
|
'suppress_filters' => true,
|
||||||
|
'no_found_rows' => true,
|
||||||
|
'orderby' => array(
|
||||||
|
'menu_order' => 'ASC',
|
||||||
|
'date' => 'ASC',
|
||||||
|
'ID' => 'ASC',
|
||||||
|
),
|
||||||
|
'date_query' => array(
|
||||||
|
'column' => 'post_date',
|
||||||
|
array(
|
||||||
|
'compare' => '<=',
|
||||||
|
'year' => $date->format( 'Y' ),
|
||||||
|
'month' => $date->format( 'n' ),
|
||||||
|
'day' => $date->format( 'j' ),
|
||||||
|
'hour' => $date->format( 'G' ),
|
||||||
|
'minute' => $date->format( 'i' ),
|
||||||
|
'second' => $date->format( 's' ),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
'tax_query' => array(
|
||||||
|
array(
|
||||||
|
'taxonomy' => self::GROUP_TAXONOMY,
|
||||||
|
'field' => 'slug',
|
||||||
|
'terms' => $group,
|
||||||
|
'include_children' => false,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
return $query->query( $query_args );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $claim_id
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
public function find_actions_by_claim_id( $claim_id ) {
|
||||||
|
/** @var wpdb $wpdb */
|
||||||
|
global $wpdb;
|
||||||
|
$sql = "SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND post_password = %s";
|
||||||
|
$sql = $wpdb->prepare( $sql, array( self::POST_TYPE, $claim_id ) );
|
||||||
|
$action_ids = $wpdb->get_col( $sql );
|
||||||
|
return $action_ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function release_claim( ActionScheduler_ActionClaim $claim ) {
|
||||||
|
$action_ids = $this->find_actions_by_claim_id( $claim->get_id() );
|
||||||
|
if ( empty($action_ids) ) {
|
||||||
|
return; // nothing to do
|
||||||
|
}
|
||||||
|
$action_id_string = implode(',', array_map('intval', $action_ids));
|
||||||
|
/** @var wpdb $wpdb */
|
||||||
|
global $wpdb;
|
||||||
|
$sql = "UPDATE {$wpdb->posts} SET post_password = '' WHERE ID IN ($action_id_string) AND post_password = %s";
|
||||||
|
$sql = $wpdb->prepare( $sql, array( $claim->get_id() ) );
|
||||||
|
$result = $wpdb->query($sql);
|
||||||
|
if ( $result === false ) {
|
||||||
|
throw new RuntimeException( sprintf( __('Unable to unlock claim %s. Database error.', 'action-scheduler'), $claim->get_id() ) );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*/
|
||||||
|
public function unclaim_action( $action_id ) {
|
||||||
|
/** @var wpdb $wpdb */
|
||||||
|
global $wpdb;
|
||||||
|
$sql = "UPDATE {$wpdb->posts} SET post_password = '' WHERE ID = %d AND post_type = %s";
|
||||||
|
$sql = $wpdb->prepare( $sql, $action_id, self::POST_TYPE );
|
||||||
|
$result = $wpdb->query($sql);
|
||||||
|
if ( $result === false ) {
|
||||||
|
throw new RuntimeException( sprintf( __('Unable to unlock claim on action %s. Database error.', 'action-scheduler'), $action_id ) );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function mark_failure( $action_id ) {
|
||||||
|
/** @var wpdb $wpdb */
|
||||||
|
global $wpdb;
|
||||||
|
$sql = "UPDATE {$wpdb->posts} SET post_status = %s WHERE ID = %d AND post_type = %s";
|
||||||
|
$sql = $wpdb->prepare( $sql, self::STATUS_FAILED, $action_id, self::POST_TYPE );
|
||||||
|
$result = $wpdb->query($sql);
|
||||||
|
if ( $result === false ) {
|
||||||
|
throw new RuntimeException( sprintf( __('Unable to mark failure on action %s. Database error.', 'action-scheduler'), $action_id ) );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return an action's claim ID, as stored in the post password column
|
||||||
|
*
|
||||||
|
* @param string $action_id
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
public function get_claim_id( $action_id ) {
|
||||||
|
return $this->get_post_column( $action_id, 'post_password' );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return an action's status, as stored in the post status column
|
||||||
|
*
|
||||||
|
* @param string $action_id
|
||||||
|
* @return mixed
|
||||||
|
*/
|
||||||
|
public function get_status( $action_id ) {
|
||||||
|
$status = $this->get_post_column( $action_id, 'post_status' );
|
||||||
|
|
||||||
|
if ( $status === null ) {
|
||||||
|
throw new \InvalidArgumentException( __( 'Invalid action ID. No status found.', 'action-scheduler' ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->get_action_status_by_post_status( $status );
|
||||||
|
}
|
||||||
|
|
||||||
|
private function get_post_column( $action_id, $column_name ) {
|
||||||
|
/** @var \wpdb $wpdb */
|
||||||
|
global $wpdb;
|
||||||
|
return $wpdb->get_var( $wpdb->prepare( "SELECT {$column_name} FROM {$wpdb->posts} WHERE ID=%d AND post_type=%s", $action_id, self::POST_TYPE ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $action_id
|
||||||
|
*/
|
||||||
|
public function log_execution( $action_id ) {
|
||||||
|
/** @var wpdb $wpdb */
|
||||||
|
global $wpdb;
|
||||||
|
|
||||||
|
$sql = "UPDATE {$wpdb->posts} SET menu_order = menu_order+1, post_status=%s, post_modified_gmt = %s, post_modified = %s WHERE ID = %d AND post_type = %s";
|
||||||
|
$sql = $wpdb->prepare( $sql, self::STATUS_RUNNING, current_time('mysql', true), current_time('mysql'), $action_id, self::POST_TYPE );
|
||||||
|
$wpdb->query($sql);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public function mark_complete( $action_id ) {
|
||||||
|
$post = get_post($action_id);
|
||||||
|
if ( empty($post) || ($post->post_type != self::POST_TYPE) ) {
|
||||||
|
throw new InvalidArgumentException(sprintf(__('Unidentified action %s', 'action-scheduler'), $action_id));
|
||||||
|
}
|
||||||
|
add_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 );
|
||||||
|
$result = wp_update_post(array(
|
||||||
|
'ID' => $action_id,
|
||||||
|
'post_status' => 'publish',
|
||||||
|
), TRUE);
|
||||||
|
remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10 );
|
||||||
|
if ( is_wp_error($result) ) {
|
||||||
|
throw new RuntimeException($result->get_error_message());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
public function init() {
|
||||||
|
$post_type_registrar = new ActionScheduler_wpPostStore_PostTypeRegistrar();
|
||||||
|
$post_type_registrar->register();
|
||||||
|
|
||||||
|
$post_status_registrar = new ActionScheduler_wpPostStore_PostStatusRegistrar();
|
||||||
|
$post_status_registrar->register();
|
||||||
|
|
||||||
|
$taxonomy_registrar = new ActionScheduler_wpPostStore_TaxonomyRegistrar();
|
||||||
|
$taxonomy_registrar->register();
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,57 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_wpPostStore_PostStatusRegistrar
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
class ActionScheduler_wpPostStore_PostStatusRegistrar {
|
||||||
|
public function register() {
|
||||||
|
register_post_status( ActionScheduler_Store::STATUS_RUNNING, array_merge( $this->post_status_args(), $this->post_status_running_labels() ) );
|
||||||
|
register_post_status( ActionScheduler_Store::STATUS_FAILED, array_merge( $this->post_status_args(), $this->post_status_failed_labels() ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the args array for the post type definition
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
protected function post_status_args() {
|
||||||
|
$args = array(
|
||||||
|
'public' => false,
|
||||||
|
'exclude_from_search' => false,
|
||||||
|
'show_in_admin_all_list' => true,
|
||||||
|
'show_in_admin_status_list' => true,
|
||||||
|
);
|
||||||
|
|
||||||
|
return apply_filters( 'action_scheduler_post_status_args', $args );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the args array for the post type definition
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
protected function post_status_failed_labels() {
|
||||||
|
$labels = array(
|
||||||
|
'label' => _x( 'Failed', 'post' ),
|
||||||
|
'label_count' => _n_noop( 'Failed <span class="count">(%s)</span>', 'Failed <span class="count">(%s)</span>' ),
|
||||||
|
);
|
||||||
|
|
||||||
|
return apply_filters( 'action_scheduler_post_status_failed_labels', $labels );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the args array for the post type definition
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
protected function post_status_running_labels() {
|
||||||
|
$labels = array(
|
||||||
|
'label' => _x( 'In-Progress', 'post' ),
|
||||||
|
'label_count' => _n_noop( 'In-Progress <span class="count">(%s)</span>', 'In-Progress <span class="count">(%s)</span>' ),
|
||||||
|
);
|
||||||
|
|
||||||
|
return apply_filters( 'action_scheduler_post_status_running_labels', $labels );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,50 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_wpPostStore_PostTypeRegistrar
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
class ActionScheduler_wpPostStore_PostTypeRegistrar {
|
||||||
|
public function register() {
|
||||||
|
register_post_type( ActionScheduler_wpPostStore::POST_TYPE, $this->post_type_args() );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the args array for the post type definition
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
protected function post_type_args() {
|
||||||
|
$args = array(
|
||||||
|
'label' => __( 'Scheduled Actions', 'action-scheduler' ),
|
||||||
|
'description' => __( 'Scheduled actions are hooks triggered on a cetain date and time.', 'action-scheduler' ),
|
||||||
|
'public' => false,
|
||||||
|
'map_meta_cap' => true,
|
||||||
|
'hierarchical' => false,
|
||||||
|
'supports' => array('title', 'editor','comments'),
|
||||||
|
'rewrite' => false,
|
||||||
|
'query_var' => false,
|
||||||
|
'can_export' => true,
|
||||||
|
'ep_mask' => EP_NONE,
|
||||||
|
'labels' => array(
|
||||||
|
'name' => __( 'Scheduled Actions', 'action-scheduler' ),
|
||||||
|
'singular_name' => __( 'Scheduled Action', 'action-scheduler' ),
|
||||||
|
'menu_name' => _x( 'Scheduled Actions', 'Admin menu name', 'action-scheduler' ),
|
||||||
|
'add_new' => __( 'Add', 'action-scheduler' ),
|
||||||
|
'add_new_item' => __( 'Add New Scheduled Action', 'action-scheduler' ),
|
||||||
|
'edit' => __( 'Edit', 'action-scheduler' ),
|
||||||
|
'edit_item' => __( 'Edit Scheduled Action', 'action-scheduler' ),
|
||||||
|
'new_item' => __( 'New Scheduled Action', 'action-scheduler' ),
|
||||||
|
'view' => __( 'View Action', 'action-scheduler' ),
|
||||||
|
'view_item' => __( 'View Action', 'action-scheduler' ),
|
||||||
|
'search_items' => __( 'Search Scheduled Actions', 'action-scheduler' ),
|
||||||
|
'not_found' => __( 'No actions found', 'action-scheduler' ),
|
||||||
|
'not_found_in_trash' => __( 'No actions found in trash', 'action-scheduler' ),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
$args = apply_filters('action_scheduler_post_type_args', $args);
|
||||||
|
return $args;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,26 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_wpPostStore_TaxonomyRegistrar
|
||||||
|
* @codeCoverageIgnore
|
||||||
|
*/
|
||||||
|
class ActionScheduler_wpPostStore_TaxonomyRegistrar {
|
||||||
|
public function register() {
|
||||||
|
register_taxonomy( ActionScheduler_wpPostStore::GROUP_TAXONOMY, ActionScheduler_wpPostStore::POST_TYPE, $this->taxonomy_args() );
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function taxonomy_args() {
|
||||||
|
$args = array(
|
||||||
|
'label' => __('Action Group', 'action-scheduler'),
|
||||||
|
'public' => false,
|
||||||
|
'hierarchical' => false,
|
||||||
|
'show_admin_column' => true,
|
||||||
|
'query_var' => false,
|
||||||
|
'rewrite' => false,
|
||||||
|
);
|
||||||
|
|
||||||
|
$args = apply_filters('action_scheduler_taxonomy_args', $args);
|
||||||
|
return $args;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,13 @@
|
||||||
|
codecov:
|
||||||
|
branch: master
|
||||||
|
|
||||||
|
coverage:
|
||||||
|
ignore:
|
||||||
|
- tests/.*
|
||||||
|
- lib/.*
|
||||||
|
status:
|
||||||
|
project: false
|
||||||
|
patch: false
|
||||||
|
changes: false
|
||||||
|
|
||||||
|
comment: false
|
|
@ -0,0 +1,12 @@
|
||||||
|
{
|
||||||
|
"name": "prospress/action-scheduler",
|
||||||
|
"version": "2.0.0",
|
||||||
|
"description": "Action Scheduler for WordPress and WooCommerce",
|
||||||
|
"type": "wordpress-plugin",
|
||||||
|
"license": "GPL-3.0",
|
||||||
|
"minimum-stability": "dev",
|
||||||
|
"require": {},
|
||||||
|
"require-dev": {
|
||||||
|
"wp-cli/wp-cli": "^1.3"
|
||||||
|
}
|
||||||
|
}
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,186 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* General API functions for scheduling actions
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedule an action to run one time
|
||||||
|
*
|
||||||
|
* @param int $timestamp When the job will run
|
||||||
|
* @param string $hook The hook to trigger
|
||||||
|
* @param array $args Arguments to pass when the hook triggers
|
||||||
|
* @param string $group The group to assign this job to
|
||||||
|
*
|
||||||
|
* @return string The job ID
|
||||||
|
*/
|
||||||
|
function wc_schedule_single_action( $timestamp, $hook, $args = array(), $group = '' ) {
|
||||||
|
return ActionScheduler::factory()->single( $hook, $args, $timestamp, $group );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedule a recurring action
|
||||||
|
*
|
||||||
|
* @param int $timestamp When the first instance of the job will run
|
||||||
|
* @param int $interval_in_seconds How long to wait between runs
|
||||||
|
* @param string $hook The hook to trigger
|
||||||
|
* @param array $args Arguments to pass when the hook triggers
|
||||||
|
* @param string $group The group to assign this job to
|
||||||
|
*
|
||||||
|
* @return string The job ID
|
||||||
|
*/
|
||||||
|
function wc_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args = array(), $group = '' ) {
|
||||||
|
return ActionScheduler::factory()->recurring( $hook, $args, $timestamp, $interval_in_seconds, $group );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schedule an action that recurs on a cron-like schedule.
|
||||||
|
*
|
||||||
|
* @param int $timestamp The schedule will start on or after this time
|
||||||
|
* @param string $schedule A cron-link schedule string
|
||||||
|
* @see http://en.wikipedia.org/wiki/Cron
|
||||||
|
* * * * * * *
|
||||||
|
* ┬ ┬ ┬ ┬ ┬ ┬
|
||||||
|
* | | | | | |
|
||||||
|
* | | | | | + year [optional]
|
||||||
|
* | | | | +----- day of week (0 - 7) (Sunday=0 or 7)
|
||||||
|
* | | | +---------- month (1 - 12)
|
||||||
|
* | | +--------------- day of month (1 - 31)
|
||||||
|
* | +-------------------- hour (0 - 23)
|
||||||
|
* +------------------------- min (0 - 59)
|
||||||
|
* @param string $hook The hook to trigger
|
||||||
|
* @param array $args Arguments to pass when the hook triggers
|
||||||
|
* @param string $group The group to assign this job to
|
||||||
|
*
|
||||||
|
* @return string The job ID
|
||||||
|
*/
|
||||||
|
function wc_schedule_cron_action( $timestamp, $schedule, $hook, $args = array(), $group = '' ) {
|
||||||
|
return ActionScheduler::factory()->cron( $hook, $args, $timestamp, $schedule, $group );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cancel the next occurrence of a job.
|
||||||
|
*
|
||||||
|
* @param string $hook The hook that the job will trigger
|
||||||
|
* @param array $args Args that would have been passed to the job
|
||||||
|
* @param string $group
|
||||||
|
*/
|
||||||
|
function wc_unschedule_action( $hook, $args = array(), $group = '' ) {
|
||||||
|
$params = array();
|
||||||
|
if ( is_array($args) ) {
|
||||||
|
$params['args'] = $args;
|
||||||
|
}
|
||||||
|
if ( !empty($group) ) {
|
||||||
|
$params['group'] = $group;
|
||||||
|
}
|
||||||
|
$job_id = ActionScheduler::store()->find_action( $hook, $params );
|
||||||
|
if ( empty($job_id) ) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ActionScheduler::store()->cancel_action( $job_id );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param string $hook
|
||||||
|
* @param array $args
|
||||||
|
* @param string $group
|
||||||
|
*
|
||||||
|
* @return int|bool The timestamp for the next occurrence, or false if nothing was found
|
||||||
|
*/
|
||||||
|
function wc_next_scheduled_action( $hook, $args = NULL, $group = '' ) {
|
||||||
|
$params = array();
|
||||||
|
if ( is_array($args) ) {
|
||||||
|
$params['args'] = $args;
|
||||||
|
}
|
||||||
|
if ( !empty($group) ) {
|
||||||
|
$params['group'] = $group;
|
||||||
|
}
|
||||||
|
$job_id = ActionScheduler::store()->find_action( $hook, $params );
|
||||||
|
if ( empty($job_id) ) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
$job = ActionScheduler::store()->fetch_action( $job_id );
|
||||||
|
$next = $job->get_schedule()->next();
|
||||||
|
if ( $next ) {
|
||||||
|
return (int)($next->format('U'));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find scheduled actions
|
||||||
|
*
|
||||||
|
* @param array $args Possible arguments, with their default values:
|
||||||
|
* 'hook' => '' - the name of the action that will be triggered
|
||||||
|
* 'args' => NULL - the args array that will be passed with the action
|
||||||
|
* 'date' => NULL - the scheduled date of the action. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
|
||||||
|
* 'date_compare' => '<=' - operator for testing "date". accepted values are '!=', '>', '>=', '<', '<=', '='
|
||||||
|
* 'modified' => NULL - the date the action was last updated. Expects a DateTime object, a unix timestamp, or a string that can parsed with strtotime(). Used in UTC timezone.
|
||||||
|
* 'modified_compare' => '<=' - operator for testing "modified". accepted values are '!=', '>', '>=', '<', '<=', '='
|
||||||
|
* 'group' => '' - the group the action belongs to
|
||||||
|
* 'status' => '' - ActionScheduler_Store::STATUS_COMPLETE or ActionScheduler_Store::STATUS_PENDING
|
||||||
|
* 'claimed' => NULL - TRUE to find claimed actions, FALSE to find unclaimed actions, a string to find a specific claim ID
|
||||||
|
* 'per_page' => 5 - Number of results to return
|
||||||
|
* 'offset' => 0
|
||||||
|
* 'orderby' => 'date' - accepted values are 'hook', 'group', 'modified', or 'date'
|
||||||
|
* 'order' => 'ASC'
|
||||||
|
*
|
||||||
|
* @param string $return_format OBJECT, ARRAY_A, or ids
|
||||||
|
*
|
||||||
|
* @return array
|
||||||
|
*/
|
||||||
|
function wc_get_scheduled_actions( $args = array(), $return_format = OBJECT ) {
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
foreach ( array('date', 'modified') as $key ) {
|
||||||
|
if ( isset($args[$key]) ) {
|
||||||
|
$args[$key] = as_get_datetime_object($args[$key]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$ids = $store->query_actions( $args );
|
||||||
|
|
||||||
|
if ( $return_format == 'ids' || $return_format == 'int' ) {
|
||||||
|
return $ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
$actions = array();
|
||||||
|
foreach ( $ids as $action_id ) {
|
||||||
|
$actions[$action_id] = $store->fetch_action( $action_id );
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( $return_format == ARRAY_A ) {
|
||||||
|
foreach ( $actions as $action_id => $action_object ) {
|
||||||
|
$actions[$action_id] = get_object_vars($action_object);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $actions;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper function to create an instance of DateTime based on a given
|
||||||
|
* string and timezone. By default, will return the current date/time
|
||||||
|
* in the UTC timezone.
|
||||||
|
*
|
||||||
|
* Needed because new DateTime() called without an explicit timezone
|
||||||
|
* will create a date/time in PHP's timezone, but we need to have
|
||||||
|
* assurance that a date/time uses the right timezone (which we almost
|
||||||
|
* always want to be UTC), which means we need to always include the
|
||||||
|
* timezone when instantiating datetimes rather than leaving it up to
|
||||||
|
* the PHP default.
|
||||||
|
*
|
||||||
|
* @param mixed $date_string A date/time string. Valid formats are explained in http://php.net/manual/en/datetime.formats.php
|
||||||
|
* @param string $timezone A timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available http://php.net/manual/en/timezones.php
|
||||||
|
*
|
||||||
|
* @return ActionScheduler_DateTime
|
||||||
|
*/
|
||||||
|
function as_get_datetime_object( $date_string = null, $timezone = 'UTC' ) {
|
||||||
|
if ( is_object( $date_string ) && $date_string instanceof DateTime ) {
|
||||||
|
$date = new ActionScheduler_DateTime( $date_string->format( 'Y-m-d H:i:s' ), new DateTimeZone( $timezone ) );
|
||||||
|
} elseif ( is_numeric( $date_string ) ) {
|
||||||
|
$date = new ActionScheduler_DateTime( '@' . $date_string, new DateTimeZone( $timezone ) );
|
||||||
|
} else {
|
||||||
|
$date = new ActionScheduler_DateTime( $date_string, new DateTimeZone( $timezone ) );
|
||||||
|
}
|
||||||
|
return $date;
|
||||||
|
}
|
|
@ -0,0 +1,318 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CRON expression parser that can determine whether or not a CRON expression is
|
||||||
|
* due to run, the next run date and previous run date of a CRON expression.
|
||||||
|
* The determinations made by this class are accurate if checked run once per
|
||||||
|
* minute (seconds are dropped from date time comparisons).
|
||||||
|
*
|
||||||
|
* Schedule parts must map to:
|
||||||
|
* minute [0-59], hour [0-23], day of month, month [1-12|JAN-DEC], day of week
|
||||||
|
* [1-7|MON-SUN], and an optional year.
|
||||||
|
*
|
||||||
|
* @author Michael Dowling <mtdowling@gmail.com>
|
||||||
|
* @link http://en.wikipedia.org/wiki/Cron
|
||||||
|
*/
|
||||||
|
class CronExpression
|
||||||
|
{
|
||||||
|
const MINUTE = 0;
|
||||||
|
const HOUR = 1;
|
||||||
|
const DAY = 2;
|
||||||
|
const MONTH = 3;
|
||||||
|
const WEEKDAY = 4;
|
||||||
|
const YEAR = 5;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array CRON expression parts
|
||||||
|
*/
|
||||||
|
private $cronParts;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var CronExpression_FieldFactory CRON field factory
|
||||||
|
*/
|
||||||
|
private $fieldFactory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @var array Order in which to test of cron parts
|
||||||
|
*/
|
||||||
|
private static $order = array(self::YEAR, self::MONTH, self::DAY, self::WEEKDAY, self::HOUR, self::MINUTE);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Factory method to create a new CronExpression.
|
||||||
|
*
|
||||||
|
* @param string $expression The CRON expression to create. There are
|
||||||
|
* several special predefined values which can be used to substitute the
|
||||||
|
* CRON expression:
|
||||||
|
*
|
||||||
|
* @yearly, @annually) - Run once a year, midnight, Jan. 1 - 0 0 1 1 *
|
||||||
|
* @monthly - Run once a month, midnight, first of month - 0 0 1 * *
|
||||||
|
* @weekly - Run once a week, midnight on Sun - 0 0 * * 0
|
||||||
|
* @daily - Run once a day, midnight - 0 0 * * *
|
||||||
|
* @hourly - Run once an hour, first minute - 0 * * * *
|
||||||
|
*
|
||||||
|
*@param CronExpression_FieldFactory $fieldFactory (optional) Field factory to use
|
||||||
|
*
|
||||||
|
* @return CronExpression
|
||||||
|
*/
|
||||||
|
public static function factory($expression, CronExpression_FieldFactory $fieldFactory = null)
|
||||||
|
{
|
||||||
|
$mappings = array(
|
||||||
|
'@yearly' => '0 0 1 1 *',
|
||||||
|
'@annually' => '0 0 1 1 *',
|
||||||
|
'@monthly' => '0 0 1 * *',
|
||||||
|
'@weekly' => '0 0 * * 0',
|
||||||
|
'@daily' => '0 0 * * *',
|
||||||
|
'@hourly' => '0 * * * *'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isset($mappings[$expression])) {
|
||||||
|
$expression = $mappings[$expression];
|
||||||
|
}
|
||||||
|
|
||||||
|
return new self($expression, $fieldFactory ? $fieldFactory : new CronExpression_FieldFactory());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a CRON expression
|
||||||
|
*
|
||||||
|
* @param string $expression CRON expression (e.g. '8 * * * *')
|
||||||
|
* @param CronExpression_FieldFactory $fieldFactory Factory to create cron fields
|
||||||
|
*/
|
||||||
|
public function __construct($expression, CronExpression_FieldFactory $fieldFactory)
|
||||||
|
{
|
||||||
|
$this->fieldFactory = $fieldFactory;
|
||||||
|
$this->setExpression($expression);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set or change the CRON expression
|
||||||
|
*
|
||||||
|
* @param string $value CRON expression (e.g. 8 * * * *)
|
||||||
|
*
|
||||||
|
* @return CronExpression
|
||||||
|
* @throws InvalidArgumentException if not a valid CRON expression
|
||||||
|
*/
|
||||||
|
public function setExpression($value)
|
||||||
|
{
|
||||||
|
$this->cronParts = preg_split('/\s/', $value, -1, PREG_SPLIT_NO_EMPTY);
|
||||||
|
if (count($this->cronParts) < 5) {
|
||||||
|
throw new InvalidArgumentException(
|
||||||
|
$value . ' is not a valid CRON expression'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($this->cronParts as $position => $part) {
|
||||||
|
$this->setPart($position, $part);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set part of the CRON expression
|
||||||
|
*
|
||||||
|
* @param int $position The position of the CRON expression to set
|
||||||
|
* @param string $value The value to set
|
||||||
|
*
|
||||||
|
* @return CronExpression
|
||||||
|
* @throws InvalidArgumentException if the value is not valid for the part
|
||||||
|
*/
|
||||||
|
public function setPart($position, $value)
|
||||||
|
{
|
||||||
|
if (!$this->fieldFactory->getField($position)->validate($value)) {
|
||||||
|
throw new InvalidArgumentException(
|
||||||
|
'Invalid CRON field value ' . $value . ' as position ' . $position
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->cronParts[$position] = $value;
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a next run date relative to the current date or a specific date
|
||||||
|
*
|
||||||
|
* @param string|DateTime $currentTime (optional) Relative calculation date
|
||||||
|
* @param int $nth (optional) Number of matches to skip before returning a
|
||||||
|
* matching next run date. 0, the default, will return the current
|
||||||
|
* date and time if the next run date falls on the current date and
|
||||||
|
* time. Setting this value to 1 will skip the first match and go to
|
||||||
|
* the second match. Setting this value to 2 will skip the first 2
|
||||||
|
* matches and so on.
|
||||||
|
* @param bool $allowCurrentDate (optional) Set to TRUE to return the
|
||||||
|
* current date if it matches the cron expression
|
||||||
|
*
|
||||||
|
* @return DateTime
|
||||||
|
* @throws RuntimeException on too many iterations
|
||||||
|
*/
|
||||||
|
public function getNextRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false)
|
||||||
|
{
|
||||||
|
return $this->getRunDate($currentTime, $nth, false, $allowCurrentDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a previous run date relative to the current date or a specific date
|
||||||
|
*
|
||||||
|
* @param string|DateTime $currentTime (optional) Relative calculation date
|
||||||
|
* @param int $nth (optional) Number of matches to skip before returning
|
||||||
|
* @param bool $allowCurrentDate (optional) Set to TRUE to return the
|
||||||
|
* current date if it matches the cron expression
|
||||||
|
*
|
||||||
|
* @return DateTime
|
||||||
|
* @throws RuntimeException on too many iterations
|
||||||
|
* @see CronExpression::getNextRunDate
|
||||||
|
*/
|
||||||
|
public function getPreviousRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false)
|
||||||
|
{
|
||||||
|
return $this->getRunDate($currentTime, $nth, true, $allowCurrentDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get multiple run dates starting at the current date or a specific date
|
||||||
|
*
|
||||||
|
* @param int $total Set the total number of dates to calculate
|
||||||
|
* @param string|DateTime $currentTime (optional) Relative calculation date
|
||||||
|
* @param bool $invert (optional) Set to TRUE to retrieve previous dates
|
||||||
|
* @param bool $allowCurrentDate (optional) Set to TRUE to return the
|
||||||
|
* current date if it matches the cron expression
|
||||||
|
*
|
||||||
|
* @return array Returns an array of run dates
|
||||||
|
*/
|
||||||
|
public function getMultipleRunDates($total, $currentTime = 'now', $invert = false, $allowCurrentDate = false)
|
||||||
|
{
|
||||||
|
$matches = array();
|
||||||
|
for ($i = 0; $i < max(0, $total); $i++) {
|
||||||
|
$matches[] = $this->getRunDate($currentTime, $i, $invert, $allowCurrentDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $matches;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all or part of the CRON expression
|
||||||
|
*
|
||||||
|
* @param string $part (optional) Specify the part to retrieve or NULL to
|
||||||
|
* get the full cron schedule string.
|
||||||
|
*
|
||||||
|
* @return string|null Returns the CRON expression, a part of the
|
||||||
|
* CRON expression, or NULL if the part was specified but not found
|
||||||
|
*/
|
||||||
|
public function getExpression($part = null)
|
||||||
|
{
|
||||||
|
if (null === $part) {
|
||||||
|
return implode(' ', $this->cronParts);
|
||||||
|
} elseif (array_key_exists($part, $this->cronParts)) {
|
||||||
|
return $this->cronParts[$part];
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to output the full expression.
|
||||||
|
*
|
||||||
|
* @return string Full CRON expression
|
||||||
|
*/
|
||||||
|
public function __toString()
|
||||||
|
{
|
||||||
|
return $this->getExpression();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if the cron is due to run based on the current date or a
|
||||||
|
* specific date. This method assumes that the current number of
|
||||||
|
* seconds are irrelevant, and should be called once per minute.
|
||||||
|
*
|
||||||
|
* @param string|DateTime $currentTime (optional) Relative calculation date
|
||||||
|
*
|
||||||
|
* @return bool Returns TRUE if the cron is due to run or FALSE if not
|
||||||
|
*/
|
||||||
|
public function isDue($currentTime = 'now')
|
||||||
|
{
|
||||||
|
if ('now' === $currentTime) {
|
||||||
|
$currentDate = date('Y-m-d H:i');
|
||||||
|
$currentTime = strtotime($currentDate);
|
||||||
|
} elseif ($currentTime instanceof DateTime) {
|
||||||
|
$currentDate = $currentTime->format('Y-m-d H:i');
|
||||||
|
$currentTime = strtotime($currentDate);
|
||||||
|
} else {
|
||||||
|
$currentTime = new DateTime($currentTime);
|
||||||
|
$currentTime->setTime($currentTime->format('H'), $currentTime->format('i'), 0);
|
||||||
|
$currentDate = $currentTime->format('Y-m-d H:i');
|
||||||
|
$currentTime = (int)($currentTime->getTimestamp());
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->getNextRunDate($currentDate, 0, true)->getTimestamp() == $currentTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the next or previous run date of the expression relative to a date
|
||||||
|
*
|
||||||
|
* @param string|DateTime $currentTime (optional) Relative calculation date
|
||||||
|
* @param int $nth (optional) Number of matches to skip before returning
|
||||||
|
* @param bool $invert (optional) Set to TRUE to go backwards in time
|
||||||
|
* @param bool $allowCurrentDate (optional) Set to TRUE to return the
|
||||||
|
* current date if it matches the cron expression
|
||||||
|
*
|
||||||
|
* @return DateTime
|
||||||
|
* @throws RuntimeException on too many iterations
|
||||||
|
*/
|
||||||
|
protected function getRunDate($currentTime = null, $nth = 0, $invert = false, $allowCurrentDate = false)
|
||||||
|
{
|
||||||
|
if ($currentTime instanceof DateTime) {
|
||||||
|
$currentDate = $currentTime;
|
||||||
|
} else {
|
||||||
|
$currentDate = new DateTime($currentTime ? $currentTime : 'now');
|
||||||
|
$currentDate->setTimezone(new DateTimeZone(date_default_timezone_get()));
|
||||||
|
}
|
||||||
|
|
||||||
|
$currentDate->setTime($currentDate->format('H'), $currentDate->format('i'), 0);
|
||||||
|
$nextRun = clone $currentDate;
|
||||||
|
$nth = (int) $nth;
|
||||||
|
|
||||||
|
// Set a hard limit to bail on an impossible date
|
||||||
|
for ($i = 0; $i < 1000; $i++) {
|
||||||
|
|
||||||
|
foreach (self::$order as $position) {
|
||||||
|
$part = $this->getExpression($position);
|
||||||
|
if (null === $part) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
$satisfied = false;
|
||||||
|
// Get the field object used to validate this part
|
||||||
|
$field = $this->fieldFactory->getField($position);
|
||||||
|
// Check if this is singular or a list
|
||||||
|
if (strpos($part, ',') === false) {
|
||||||
|
$satisfied = $field->isSatisfiedBy($nextRun, $part);
|
||||||
|
} else {
|
||||||
|
foreach (array_map('trim', explode(',', $part)) as $listPart) {
|
||||||
|
if ($field->isSatisfiedBy($nextRun, $listPart)) {
|
||||||
|
$satisfied = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the field is not satisfied, then start over
|
||||||
|
if (!$satisfied) {
|
||||||
|
$field->increment($nextRun, $invert);
|
||||||
|
continue 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip this match if needed
|
||||||
|
if ((!$allowCurrentDate && $nextRun == $currentDate) || --$nth > -1) {
|
||||||
|
$this->fieldFactory->getField(0)->increment($nextRun, $invert);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $nextRun;
|
||||||
|
}
|
||||||
|
|
||||||
|
// @codeCoverageIgnoreStart
|
||||||
|
throw new RuntimeException('Impossible CRON expression');
|
||||||
|
// @codeCoverageIgnoreEnd
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,100 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Abstract CRON expression field
|
||||||
|
*
|
||||||
|
* @author Michael Dowling <mtdowling@gmail.com>
|
||||||
|
*/
|
||||||
|
abstract class CronExpression_AbstractField implements CronExpression_FieldInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Check to see if a field is satisfied by a value
|
||||||
|
*
|
||||||
|
* @param string $dateValue Date value to check
|
||||||
|
* @param string $value Value to test
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function isSatisfied($dateValue, $value)
|
||||||
|
{
|
||||||
|
if ($this->isIncrementsOfRanges($value)) {
|
||||||
|
return $this->isInIncrementsOfRanges($dateValue, $value);
|
||||||
|
} elseif ($this->isRange($value)) {
|
||||||
|
return $this->isInRange($dateValue, $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $value == '*' || $dateValue == $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a value is a range
|
||||||
|
*
|
||||||
|
* @param string $value Value to test
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function isRange($value)
|
||||||
|
{
|
||||||
|
return strpos($value, '-') !== false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a value is an increments of ranges
|
||||||
|
*
|
||||||
|
* @param string $value Value to test
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function isIncrementsOfRanges($value)
|
||||||
|
{
|
||||||
|
return strpos($value, '/') !== false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test if a value is within a range
|
||||||
|
*
|
||||||
|
* @param string $dateValue Set date value
|
||||||
|
* @param string $value Value to test
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function isInRange($dateValue, $value)
|
||||||
|
{
|
||||||
|
$parts = array_map('trim', explode('-', $value, 2));
|
||||||
|
|
||||||
|
return $dateValue >= $parts[0] && $dateValue <= $parts[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Test if a value is within an increments of ranges (offset[-to]/step size)
|
||||||
|
*
|
||||||
|
* @param string $dateValue Set date value
|
||||||
|
* @param string $value Value to test
|
||||||
|
*
|
||||||
|
* @return bool
|
||||||
|
*/
|
||||||
|
public function isInIncrementsOfRanges($dateValue, $value)
|
||||||
|
{
|
||||||
|
$parts = array_map('trim', explode('/', $value, 2));
|
||||||
|
$stepSize = isset($parts[1]) ? $parts[1] : 0;
|
||||||
|
if ($parts[0] == '*' || $parts[0] === '0') {
|
||||||
|
return (int) $dateValue % $stepSize == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
$range = explode('-', $parts[0], 2);
|
||||||
|
$offset = $range[0];
|
||||||
|
$to = isset($range[1]) ? $range[1] : $dateValue;
|
||||||
|
// Ensure that the date value is within the range
|
||||||
|
if ($dateValue < $offset || $dateValue > $to) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for ($i = $offset; $i <= $to; $i+= $stepSize) {
|
||||||
|
if ($i == $dateValue) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,110 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Day of month field. Allows: * , / - ? L W
|
||||||
|
*
|
||||||
|
* 'L' stands for "last" and specifies the last day of the month.
|
||||||
|
*
|
||||||
|
* The 'W' character is used to specify the weekday (Monday-Friday) nearest the
|
||||||
|
* given day. As an example, if you were to specify "15W" as the value for the
|
||||||
|
* day-of-month field, the meaning is: "the nearest weekday to the 15th of the
|
||||||
|
* month". So if the 15th is a Saturday, the trigger will fire on Friday the
|
||||||
|
* 14th. If the 15th is a Sunday, the trigger will fire on Monday the 16th. If
|
||||||
|
* the 15th is a Tuesday, then it will fire on Tuesday the 15th. However if you
|
||||||
|
* specify "1W" as the value for day-of-month, and the 1st is a Saturday, the
|
||||||
|
* trigger will fire on Monday the 3rd, as it will not 'jump' over the boundary
|
||||||
|
* of a month's days. The 'W' character can only be specified when the
|
||||||
|
* day-of-month is a single day, not a range or list of days.
|
||||||
|
*
|
||||||
|
* @author Michael Dowling <mtdowling@gmail.com>
|
||||||
|
*/
|
||||||
|
class CronExpression_DayOfMonthField extends CronExpression_AbstractField
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Get the nearest day of the week for a given day in a month
|
||||||
|
*
|
||||||
|
* @param int $currentYear Current year
|
||||||
|
* @param int $currentMonth Current month
|
||||||
|
* @param int $targetDay Target day of the month
|
||||||
|
*
|
||||||
|
* @return DateTime Returns the nearest date
|
||||||
|
*/
|
||||||
|
private static function getNearestWeekday($currentYear, $currentMonth, $targetDay)
|
||||||
|
{
|
||||||
|
$tday = str_pad($targetDay, 2, '0', STR_PAD_LEFT);
|
||||||
|
$target = new DateTime("$currentYear-$currentMonth-$tday");
|
||||||
|
$currentWeekday = (int) $target->format('N');
|
||||||
|
|
||||||
|
if ($currentWeekday < 6) {
|
||||||
|
return $target;
|
||||||
|
}
|
||||||
|
|
||||||
|
$lastDayOfMonth = $target->format('t');
|
||||||
|
|
||||||
|
foreach (array(-1, 1, -2, 2) as $i) {
|
||||||
|
$adjusted = $targetDay + $i;
|
||||||
|
if ($adjusted > 0 && $adjusted <= $lastDayOfMonth) {
|
||||||
|
$target->setDate($currentYear, $currentMonth, $adjusted);
|
||||||
|
if ($target->format('N') < 6 && $target->format('m') == $currentMonth) {
|
||||||
|
return $target;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function isSatisfiedBy(DateTime $date, $value)
|
||||||
|
{
|
||||||
|
// ? states that the field value is to be skipped
|
||||||
|
if ($value == '?') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
$fieldValue = $date->format('d');
|
||||||
|
|
||||||
|
// Check to see if this is the last day of the month
|
||||||
|
if ($value == 'L') {
|
||||||
|
return $fieldValue == $date->format('t');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check to see if this is the nearest weekday to a particular value
|
||||||
|
if (strpos($value, 'W')) {
|
||||||
|
// Parse the target day
|
||||||
|
$targetDay = substr($value, 0, strpos($value, 'W'));
|
||||||
|
// Find out if the current day is the nearest day of the week
|
||||||
|
return $date->format('j') == self::getNearestWeekday(
|
||||||
|
$date->format('Y'),
|
||||||
|
$date->format('m'),
|
||||||
|
$targetDay
|
||||||
|
)->format('j');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->isSatisfied($date->format('d'), $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function increment(DateTime $date, $invert = false)
|
||||||
|
{
|
||||||
|
if ($invert) {
|
||||||
|
$date->modify('previous day');
|
||||||
|
$date->setTime(23, 59);
|
||||||
|
} else {
|
||||||
|
$date->modify('next day');
|
||||||
|
$date->setTime(0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function validate($value)
|
||||||
|
{
|
||||||
|
return (bool) preg_match('/[\*,\/\-\?LW0-9A-Za-z]+/', $value);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,124 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Day of week field. Allows: * / , - ? L #
|
||||||
|
*
|
||||||
|
* Days of the week can be represented as a number 0-7 (0|7 = Sunday)
|
||||||
|
* or as a three letter string: SUN, MON, TUE, WED, THU, FRI, SAT.
|
||||||
|
*
|
||||||
|
* 'L' stands for "last". It allows you to specify constructs such as
|
||||||
|
* "the last Friday" of a given month.
|
||||||
|
*
|
||||||
|
* '#' is allowed for the day-of-week field, and must be followed by a
|
||||||
|
* number between one and five. It allows you to specify constructs such as
|
||||||
|
* "the second Friday" of a given month.
|
||||||
|
*
|
||||||
|
* @author Michael Dowling <mtdowling@gmail.com>
|
||||||
|
*/
|
||||||
|
class CronExpression_DayOfWeekField extends CronExpression_AbstractField
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function isSatisfiedBy(DateTime $date, $value)
|
||||||
|
{
|
||||||
|
if ($value == '?') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert text day of the week values to integers
|
||||||
|
$value = str_ireplace(
|
||||||
|
array('SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'),
|
||||||
|
range(0, 6),
|
||||||
|
$value
|
||||||
|
);
|
||||||
|
|
||||||
|
$currentYear = $date->format('Y');
|
||||||
|
$currentMonth = $date->format('m');
|
||||||
|
$lastDayOfMonth = $date->format('t');
|
||||||
|
|
||||||
|
// Find out if this is the last specific weekday of the month
|
||||||
|
if (strpos($value, 'L')) {
|
||||||
|
$weekday = str_replace('7', '0', substr($value, 0, strpos($value, 'L')));
|
||||||
|
$tdate = clone $date;
|
||||||
|
$tdate->setDate($currentYear, $currentMonth, $lastDayOfMonth);
|
||||||
|
while ($tdate->format('w') != $weekday) {
|
||||||
|
$tdate->setDate($currentYear, $currentMonth, --$lastDayOfMonth);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $date->format('j') == $lastDayOfMonth;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle # hash tokens
|
||||||
|
if (strpos($value, '#')) {
|
||||||
|
list($weekday, $nth) = explode('#', $value);
|
||||||
|
// Validate the hash fields
|
||||||
|
if ($weekday < 1 || $weekday > 5) {
|
||||||
|
throw new InvalidArgumentException("Weekday must be a value between 1 and 5. {$weekday} given");
|
||||||
|
}
|
||||||
|
if ($nth > 5) {
|
||||||
|
throw new InvalidArgumentException('There are never more than 5 of a given weekday in a month');
|
||||||
|
}
|
||||||
|
// The current weekday must match the targeted weekday to proceed
|
||||||
|
if ($date->format('N') != $weekday) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$tdate = clone $date;
|
||||||
|
$tdate->setDate($currentYear, $currentMonth, 1);
|
||||||
|
$dayCount = 0;
|
||||||
|
$currentDay = 1;
|
||||||
|
while ($currentDay < $lastDayOfMonth + 1) {
|
||||||
|
if ($tdate->format('N') == $weekday) {
|
||||||
|
if (++$dayCount >= $nth) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$tdate->setDate($currentYear, $currentMonth, ++$currentDay);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $date->format('j') == $currentDay;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle day of the week values
|
||||||
|
if (strpos($value, '-')) {
|
||||||
|
$parts = explode('-', $value);
|
||||||
|
if ($parts[0] == '7') {
|
||||||
|
$parts[0] = '0';
|
||||||
|
} elseif ($parts[1] == '0') {
|
||||||
|
$parts[1] = '7';
|
||||||
|
}
|
||||||
|
$value = implode('-', $parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test to see which Sunday to use -- 0 == 7 == Sunday
|
||||||
|
$format = in_array(7, str_split($value)) ? 'N' : 'w';
|
||||||
|
$fieldValue = $date->format($format);
|
||||||
|
|
||||||
|
return $this->isSatisfied($fieldValue, $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function increment(DateTime $date, $invert = false)
|
||||||
|
{
|
||||||
|
if ($invert) {
|
||||||
|
$date->modify('-1 day');
|
||||||
|
$date->setTime(23, 59, 0);
|
||||||
|
} else {
|
||||||
|
$date->modify('+1 day');
|
||||||
|
$date->setTime(0, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function validate($value)
|
||||||
|
{
|
||||||
|
return (bool) preg_match('/[\*,\/\-0-9A-Z]+/', $value);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,55 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CRON field factory implementing a flyweight factory
|
||||||
|
*
|
||||||
|
* @author Michael Dowling <mtdowling@gmail.com>
|
||||||
|
* @link http://en.wikipedia.org/wiki/Cron
|
||||||
|
*/
|
||||||
|
class CronExpression_FieldFactory
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @var array Cache of instantiated fields
|
||||||
|
*/
|
||||||
|
private $fields = array();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get an instance of a field object for a cron expression position
|
||||||
|
*
|
||||||
|
* @param int $position CRON expression position value to retrieve
|
||||||
|
*
|
||||||
|
* @return CronExpression_FieldInterface
|
||||||
|
* @throws InvalidArgumentException if a position is not valid
|
||||||
|
*/
|
||||||
|
public function getField($position)
|
||||||
|
{
|
||||||
|
if (!isset($this->fields[$position])) {
|
||||||
|
switch ($position) {
|
||||||
|
case 0:
|
||||||
|
$this->fields[$position] = new CronExpression_MinutesField();
|
||||||
|
break;
|
||||||
|
case 1:
|
||||||
|
$this->fields[$position] = new CronExpression_HoursField();
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
$this->fields[$position] = new CronExpression_DayOfMonthField();
|
||||||
|
break;
|
||||||
|
case 3:
|
||||||
|
$this->fields[$position] = new CronExpression_MonthField();
|
||||||
|
break;
|
||||||
|
case 4:
|
||||||
|
$this->fields[$position] = new CronExpression_DayOfWeekField();
|
||||||
|
break;
|
||||||
|
case 5:
|
||||||
|
$this->fields[$position] = new CronExpression_YearField();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new InvalidArgumentException(
|
||||||
|
$position . ' is not a valid position'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->fields[$position];
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CRON field interface
|
||||||
|
*
|
||||||
|
* @author Michael Dowling <mtdowling@gmail.com>
|
||||||
|
*/
|
||||||
|
interface CronExpression_FieldInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Check if the respective value of a DateTime field satisfies a CRON exp
|
||||||
|
*
|
||||||
|
* @param DateTime $date DateTime object to check
|
||||||
|
* @param string $value CRON expression to test against
|
||||||
|
*
|
||||||
|
* @return bool Returns TRUE if satisfied, FALSE otherwise
|
||||||
|
*/
|
||||||
|
public function isSatisfiedBy(DateTime $date, $value);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When a CRON expression is not satisfied, this method is used to increment
|
||||||
|
* or decrement a DateTime object by the unit of the cron field
|
||||||
|
*
|
||||||
|
* @param DateTime $date DateTime object to change
|
||||||
|
* @param bool $invert (optional) Set to TRUE to decrement
|
||||||
|
*
|
||||||
|
* @return CronExpression_FieldInterface
|
||||||
|
*/
|
||||||
|
public function increment(DateTime $date, $invert = false);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates a CRON expression for a given field
|
||||||
|
*
|
||||||
|
* @param string $value CRON expression value to validate
|
||||||
|
*
|
||||||
|
* @return bool Returns TRUE if valid, FALSE otherwise
|
||||||
|
*/
|
||||||
|
public function validate($value);
|
||||||
|
}
|
|
@ -0,0 +1,47 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hours field. Allows: * , / -
|
||||||
|
*
|
||||||
|
* @author Michael Dowling <mtdowling@gmail.com>
|
||||||
|
*/
|
||||||
|
class CronExpression_HoursField extends CronExpression_AbstractField
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function isSatisfiedBy(DateTime $date, $value)
|
||||||
|
{
|
||||||
|
return $this->isSatisfied($date->format('H'), $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function increment(DateTime $date, $invert = false)
|
||||||
|
{
|
||||||
|
// Change timezone to UTC temporarily. This will
|
||||||
|
// allow us to go back or forwards and hour even
|
||||||
|
// if DST will be changed between the hours.
|
||||||
|
$timezone = $date->getTimezone();
|
||||||
|
$date->setTimezone(new DateTimeZone('UTC'));
|
||||||
|
if ($invert) {
|
||||||
|
$date->modify('-1 hour');
|
||||||
|
$date->setTime($date->format('H'), 59);
|
||||||
|
} else {
|
||||||
|
$date->modify('+1 hour');
|
||||||
|
$date->setTime($date->format('H'), 0);
|
||||||
|
}
|
||||||
|
$date->setTimezone($timezone);
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function validate($value)
|
||||||
|
{
|
||||||
|
return (bool) preg_match('/[\*,\/\-0-9]+/', $value);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,39 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minutes field. Allows: * , / -
|
||||||
|
*
|
||||||
|
* @author Michael Dowling <mtdowling@gmail.com>
|
||||||
|
*/
|
||||||
|
class CronExpression_MinutesField extends CronExpression_AbstractField
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function isSatisfiedBy(DateTime $date, $value)
|
||||||
|
{
|
||||||
|
return $this->isSatisfied($date->format('i'), $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function increment(DateTime $date, $invert = false)
|
||||||
|
{
|
||||||
|
if ($invert) {
|
||||||
|
$date->modify('-1 minute');
|
||||||
|
} else {
|
||||||
|
$date->modify('+1 minute');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function validate($value)
|
||||||
|
{
|
||||||
|
return (bool) preg_match('/[\*,\/\-0-9]+/', $value);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,55 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Month field. Allows: * , / -
|
||||||
|
*
|
||||||
|
* @author Michael Dowling <mtdowling@gmail.com>
|
||||||
|
*/
|
||||||
|
class CronExpression_MonthField extends CronExpression_AbstractField
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function isSatisfiedBy(DateTime $date, $value)
|
||||||
|
{
|
||||||
|
// Convert text month values to integers
|
||||||
|
$value = str_ireplace(
|
||||||
|
array(
|
||||||
|
'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN',
|
||||||
|
'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'
|
||||||
|
),
|
||||||
|
range(1, 12),
|
||||||
|
$value
|
||||||
|
);
|
||||||
|
|
||||||
|
return $this->isSatisfied($date->format('m'), $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function increment(DateTime $date, $invert = false)
|
||||||
|
{
|
||||||
|
if ($invert) {
|
||||||
|
// $date->modify('last day of previous month'); // remove for php 5.2 compat
|
||||||
|
$date->modify('previous month');
|
||||||
|
$date->modify($date->format('Y-m-t'));
|
||||||
|
$date->setTime(23, 59);
|
||||||
|
} else {
|
||||||
|
//$date->modify('first day of next month'); // remove for php 5.2 compat
|
||||||
|
$date->modify('next month');
|
||||||
|
$date->modify($date->format('Y-m-01'));
|
||||||
|
$date->setTime(0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function validate($value)
|
||||||
|
{
|
||||||
|
return (bool) preg_match('/[\*,\/\-0-9A-Z]+/', $value);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,43 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Year field. Allows: * , / -
|
||||||
|
*
|
||||||
|
* @author Michael Dowling <mtdowling@gmail.com>
|
||||||
|
*/
|
||||||
|
class CronExpression_YearField extends CronExpression_AbstractField
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function isSatisfiedBy(DateTime $date, $value)
|
||||||
|
{
|
||||||
|
return $this->isSatisfied($date->format('Y'), $value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function increment(DateTime $date, $invert = false)
|
||||||
|
{
|
||||||
|
if ($invert) {
|
||||||
|
$date->modify('-1 year');
|
||||||
|
$date->setDate($date->format('Y'), 12, 31);
|
||||||
|
$date->setTime(23, 59, 0);
|
||||||
|
} else {
|
||||||
|
$date->modify('+1 year');
|
||||||
|
$date->setDate($date->format('Y'), 1, 1);
|
||||||
|
$date->setTime(0, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*/
|
||||||
|
public function validate($value)
|
||||||
|
{
|
||||||
|
return (bool) preg_match('/[\*,\/\-0-9]+/', $value);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,19 @@
|
||||||
|
Copyright (c) 2011 Michael Dowling <mtdowling@gmail.com> and contributors
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
|
@ -0,0 +1,92 @@
|
||||||
|
PHP Cron Expression Parser
|
||||||
|
==========================
|
||||||
|
|
||||||
|
[![Latest Stable Version](https://poser.pugx.org/mtdowling/cron-expression/v/stable.png)](https://packagist.org/packages/mtdowling/cron-expression) [![Total Downloads](https://poser.pugx.org/mtdowling/cron-expression/downloads.png)](https://packagist.org/packages/mtdowling/cron-expression) [![Build Status](https://secure.travis-ci.org/mtdowling/cron-expression.png)](http://travis-ci.org/mtdowling/cron-expression)
|
||||||
|
|
||||||
|
The PHP cron expression parser can parse a CRON expression, determine if it is
|
||||||
|
due to run, calculate the next run date of the expression, and calculate the previous
|
||||||
|
run date of the expression. You can calculate dates far into the future or past by
|
||||||
|
skipping n number of matching dates.
|
||||||
|
|
||||||
|
The parser can handle increments of ranges (e.g. */12, 2-59/3), intervals (e.g. 0-9),
|
||||||
|
lists (e.g. 1,2,3), W to find the nearest weekday for a given day of the month, L to
|
||||||
|
find the last day of the month, L to find the last given weekday of a month, and hash
|
||||||
|
(#) to find the nth weekday of a given month.
|
||||||
|
|
||||||
|
Credits
|
||||||
|
==========
|
||||||
|
|
||||||
|
Created by Micheal Dowling. Ported to PHP 5.2 by Flightless, Inc.
|
||||||
|
Based on version 1.0.3: https://github.com/mtdowling/cron-expression/tree/v1.0.3
|
||||||
|
|
||||||
|
Installing
|
||||||
|
==========
|
||||||
|
|
||||||
|
Add the following to your project's composer.json:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
{
|
||||||
|
"require": {
|
||||||
|
"mtdowling/cron-expression": "1.0.*"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Usage
|
||||||
|
=====
|
||||||
|
```php
|
||||||
|
<?php
|
||||||
|
|
||||||
|
require_once '/vendor/autoload.php';
|
||||||
|
|
||||||
|
// Works with predefined scheduling definitions
|
||||||
|
$cron = Cron\CronExpression::factory('@daily');
|
||||||
|
$cron->isDue();
|
||||||
|
echo $cron->getNextRunDate()->format('Y-m-d H:i:s');
|
||||||
|
echo $cron->getPreviousRunDate()->format('Y-m-d H:i:s');
|
||||||
|
|
||||||
|
// Works with complex expressions
|
||||||
|
$cron = Cron\CronExpression::factory('3-59/15 2,6-12 */15 1 2-5');
|
||||||
|
echo $cron->getNextRunDate()->format('Y-m-d H:i:s');
|
||||||
|
|
||||||
|
// Calculate a run date two iterations into the future
|
||||||
|
$cron = Cron\CronExpression::factory('@daily');
|
||||||
|
echo $cron->getNextRunDate(null, 2)->format('Y-m-d H:i:s');
|
||||||
|
|
||||||
|
// Calculate a run date relative to a specific time
|
||||||
|
$cron = Cron\CronExpression::factory('@monthly');
|
||||||
|
echo $cron->getNextRunDate('2010-01-12 00:00:00')->format('Y-m-d H:i:s');
|
||||||
|
```
|
||||||
|
|
||||||
|
CRON Expressions
|
||||||
|
================
|
||||||
|
|
||||||
|
A CRON expression is a string representing the schedule for a particular command to execute. The parts of a CRON schedule are as follows:
|
||||||
|
|
||||||
|
* * * * * *
|
||||||
|
- - - - - -
|
||||||
|
| | | | | |
|
||||||
|
| | | | | + year [optional]
|
||||||
|
| | | | +----- day of week (0 - 7) (Sunday=0 or 7)
|
||||||
|
| | | +---------- month (1 - 12)
|
||||||
|
| | +--------------- day of month (1 - 31)
|
||||||
|
| +-------------------- hour (0 - 23)
|
||||||
|
+------------------------- min (0 - 59)
|
||||||
|
|
||||||
|
Requirements
|
||||||
|
============
|
||||||
|
|
||||||
|
- PHP 5.3+
|
||||||
|
- PHPUnit is required to run the unit tests
|
||||||
|
- Composer is required to run the unit tests
|
||||||
|
|
||||||
|
CHANGELOG
|
||||||
|
=========
|
||||||
|
|
||||||
|
1.0.3 (2013-11-23)
|
||||||
|
------------------
|
||||||
|
|
||||||
|
* Only set default timezone if the given $currentTime is not a DateTime instance (#34)
|
||||||
|
* Fixes issue #28 where PHP increments of ranges were failing due to PHP casting hyphens to 0
|
||||||
|
* Now supports expressions with any number of extra spaces, tabs, or newlines
|
||||||
|
* Using static instead of self in `CronExpression::factory`
|
|
@ -0,0 +1,674 @@
|
||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
|
@ -0,0 +1,44 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_UnitTestCase
|
||||||
|
*/
|
||||||
|
class ActionScheduler_UnitTestCase extends WP_UnitTestCase {
|
||||||
|
|
||||||
|
protected $existing_timezone;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Counts the number of test cases executed by run(TestResult result).
|
||||||
|
*
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
public function count() {
|
||||||
|
return 'UTC' == date_default_timezone_get() ? 2 : 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* We want to run every test multiple times using a different timezone to make sure
|
||||||
|
* that they are unaffected by changes to PHP's timezone.
|
||||||
|
*/
|
||||||
|
public function run( PHPUnit\Framework\TestResult $result = NULL ){
|
||||||
|
|
||||||
|
if ($result === NULL) {
|
||||||
|
$result = $this->createResult();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( 'UTC' != ( $this->existing_timezone = date_default_timezone_get() ) ) {
|
||||||
|
date_default_timezone_set( 'UTC' );
|
||||||
|
$result->run( $this );
|
||||||
|
}
|
||||||
|
|
||||||
|
date_default_timezone_set( 'Pacific/Fiji' ); // UTC+12
|
||||||
|
$result->run( $this );
|
||||||
|
|
||||||
|
date_default_timezone_set( 'Pacific/Tahiti' ); // UTC-10: it's a magical place
|
||||||
|
$result->run( $this );
|
||||||
|
|
||||||
|
date_default_timezone_set( $this->existing_timezone );
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,31 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
$GLOBALS['wp_tests_options'][ 'template' ] = 'twentyseventeen';
|
||||||
|
$GLOBALS['wp_tests_options'][ 'stylesheet' ] = 'twentyseventeen';
|
||||||
|
$GLOBALS['wp_tests_options'][ 'active_plugins' ][] = basename( dirname( __DIR__ ) ) .'/action-scheduler.php';
|
||||||
|
|
||||||
|
// Check for select constants defined as environment variables
|
||||||
|
foreach ( array('WP_CONTENT_DIR', 'WP_CONTENT_URL', 'WP_PLUGIN_DIR', 'WP_PLUGIN_URL', 'WPMU_PLUGIN_DIR') as $env_constant ) {
|
||||||
|
if ( false !== getenv( $env_constant ) && !defined( $env_constant ) ) {
|
||||||
|
define( $env_constant, getenv( $env_constant ));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the wordpress-tests repo location has been customized (and specified
|
||||||
|
// with WP_TESTS_DIR), use that location. This will most commonly be the case
|
||||||
|
// when configured for use with Travis CI.
|
||||||
|
|
||||||
|
// Otherwise, we'll just assume that this plugin is installed in the WordPress
|
||||||
|
// SVN external checkout configured in the wordpress-tests repo.
|
||||||
|
|
||||||
|
if( false !== getenv( 'WP_TESTS_DIR' ) ) {
|
||||||
|
require getenv( 'WP_TESTS_DIR' ) . '/includes/bootstrap.php';
|
||||||
|
} else {
|
||||||
|
require dirname( dirname( dirname( dirname( dirname( dirname( __FILE__ ) ) ) ) ) ) . '/tests/phpunit/includes/bootstrap.php';
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( class_exists( 'PHPUnit\Framework\TestResult' ) ) { // PHPUnit 6.0 or newer
|
||||||
|
include_once('ActionScheduler_UnitTestCase.php');
|
||||||
|
} else {
|
||||||
|
include_once('phpunit/deprecated/ActionScheduler_UnitTestCase.php');
|
||||||
|
}
|
|
@ -0,0 +1,32 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
|
||||||
|
<phpunit backupGlobals="false"
|
||||||
|
backupStaticAttributes="false"
|
||||||
|
colors="true"
|
||||||
|
convertErrorsToExceptions="true"
|
||||||
|
convertNoticesToExceptions="true"
|
||||||
|
convertWarningsToExceptions="true"
|
||||||
|
processIsolation="false"
|
||||||
|
stopOnFailure="false"
|
||||||
|
syntaxCheck="false"
|
||||||
|
bootstrap="bootstrap.php"
|
||||||
|
>
|
||||||
|
<testsuites>
|
||||||
|
<testsuite name="Action Scheduler">
|
||||||
|
<directory>./phpunit</directory>
|
||||||
|
</testsuite>
|
||||||
|
</testsuites>
|
||||||
|
<groups>
|
||||||
|
<exclude>
|
||||||
|
<group>ignore</group>
|
||||||
|
</exclude>
|
||||||
|
</groups>
|
||||||
|
<filter>
|
||||||
|
<whitelist processsUncoveredFilesFromWhitelist="true">
|
||||||
|
<directory suffix=".php">..</directory>
|
||||||
|
<exclude>
|
||||||
|
<directory>.</directory>
|
||||||
|
</exclude>
|
||||||
|
</whitelist>
|
||||||
|
</filter>
|
||||||
|
</phpunit>
|
|
@ -0,0 +1,44 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_UnitTestCase
|
||||||
|
*/
|
||||||
|
class ActionScheduler_UnitTestCase extends WP_UnitTestCase {
|
||||||
|
|
||||||
|
protected $existing_timezone;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Counts the number of test cases executed by run(TestResult result).
|
||||||
|
*
|
||||||
|
* @return int
|
||||||
|
*/
|
||||||
|
public function count() {
|
||||||
|
return 'UTC' == date_default_timezone_get() ? 2 : 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* We want to run every test multiple times using a different timezone to make sure
|
||||||
|
* that they are unaffected by changes to PHP's timezone.
|
||||||
|
*/
|
||||||
|
public function run( PHPUnit_Framework_TestResult $result = NULL ){
|
||||||
|
|
||||||
|
if ($result === NULL) {
|
||||||
|
$result = $this->createResult();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( 'UTC' != ( $this->existing_timezone = date_default_timezone_get() ) ) {
|
||||||
|
date_default_timezone_set( 'UTC' );
|
||||||
|
$result->run( $this );
|
||||||
|
}
|
||||||
|
|
||||||
|
date_default_timezone_set( 'Pacific/Fiji' ); // UTC+12
|
||||||
|
$result->run( $this );
|
||||||
|
|
||||||
|
date_default_timezone_set( 'Pacific/Tahiti' ); // UTC-10: it's a magical place
|
||||||
|
$result->run( $this );
|
||||||
|
|
||||||
|
date_default_timezone_set( $this->existing_timezone );
|
||||||
|
|
||||||
|
return $result;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,55 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_Action_Test
|
||||||
|
* @group actions
|
||||||
|
*/
|
||||||
|
class ActionScheduler_Action_Test extends ActionScheduler_UnitTestCase {
|
||||||
|
public function test_set_schedule() {
|
||||||
|
$time = as_get_datetime_object();
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
|
||||||
|
$this->assertEquals( $schedule, $action->get_schedule() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_null_schedule() {
|
||||||
|
$action = new ActionScheduler_Action('my_hook');
|
||||||
|
$this->assertInstanceOf( 'ActionScheduler_NullSchedule', $action->get_schedule() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_set_hook() {
|
||||||
|
$action = new ActionScheduler_Action('my_hook');
|
||||||
|
$this->assertEquals( 'my_hook', $action->get_hook() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_args() {
|
||||||
|
$action = new ActionScheduler_Action('my_hook');
|
||||||
|
$this->assertEmpty($action->get_args());
|
||||||
|
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array(5,10,15));
|
||||||
|
$this->assertEqualSets(array(5,10,15), $action->get_args());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_set_group() {
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array(), NULL, 'my_group');
|
||||||
|
$this->assertEquals('my_group', $action->get_group());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_execute() {
|
||||||
|
$mock = new MockAction();
|
||||||
|
|
||||||
|
$random = md5(rand());
|
||||||
|
add_action( $random, array( $mock, 'action' ) );
|
||||||
|
|
||||||
|
$action = new ActionScheduler_Action( $random, array($random) );
|
||||||
|
$action->execute();
|
||||||
|
|
||||||
|
remove_action( $random, array( $mock, 'action' ) );
|
||||||
|
|
||||||
|
$this->assertEquals( 1, $mock->get_call_count() );
|
||||||
|
$events = $mock->get_events();
|
||||||
|
$event = reset($events);
|
||||||
|
$this->assertEquals( $random, reset($event['args']) );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,16 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_NullAction_Test
|
||||||
|
* @group actions
|
||||||
|
*/
|
||||||
|
class ActionScheduler_NullAction_Test extends ActionScheduler_UnitTestCase {
|
||||||
|
public function test_null_action() {
|
||||||
|
$action = new ActionScheduler_NullAction();
|
||||||
|
|
||||||
|
$this->assertEmpty($action->get_hook());
|
||||||
|
$this->assertEmpty($action->get_args());
|
||||||
|
$this->assertNull($action->get_schedule()->next());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,352 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_wpPostStore_Test
|
||||||
|
* @group stores
|
||||||
|
*/
|
||||||
|
class ActionScheduler_wpPostStore_Test extends ActionScheduler_UnitTestCase {
|
||||||
|
|
||||||
|
public function test_create_action() {
|
||||||
|
$time = as_get_datetime_object();
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
$action_id = $store->save_action($action);
|
||||||
|
|
||||||
|
$this->assertNotEmpty($action_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_create_action_with_scheduled_date() {
|
||||||
|
$time = as_get_datetime_object( strtotime( '-1 week' ) );
|
||||||
|
$action = new ActionScheduler_Action( 'my_hook', array(), new ActionScheduler_SimpleSchedule( $time ) );
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
|
||||||
|
$action_id = $store->save_action( $action, $time );
|
||||||
|
$action_date = $store->get_date( $action_id );
|
||||||
|
|
||||||
|
$this->assertEquals( $time->getTimestamp(), $action_date->getTimestamp() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_retrieve_action() {
|
||||||
|
$time = as_get_datetime_object();
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array(), $schedule, 'my_group');
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
$action_id = $store->save_action($action);
|
||||||
|
|
||||||
|
$retrieved = $store->fetch_action($action_id);
|
||||||
|
$this->assertEquals($action->get_hook(), $retrieved->get_hook());
|
||||||
|
$this->assertEqualSets($action->get_args(), $retrieved->get_args());
|
||||||
|
$this->assertEquals($action->get_schedule()->next()->getTimestamp(), $retrieved->get_schedule()->next()->getTimestamp());
|
||||||
|
$this->assertEquals($action->get_group(), $retrieved->get_group());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_cancel_action() {
|
||||||
|
$time = as_get_datetime_object();
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array(), $schedule, 'my_group');
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
$action_id = $store->save_action($action);
|
||||||
|
$store->cancel_action( $action_id );
|
||||||
|
|
||||||
|
$fetched = $store->fetch_action( $action_id );
|
||||||
|
$this->assertInstanceOf( 'ActionScheduler_CanceledAction', $fetched );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_claim_actions() {
|
||||||
|
$created_actions = array();
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
for ( $i = 3 ; $i > -3 ; $i-- ) {
|
||||||
|
$time = as_get_datetime_object($i.' hours');
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array($i), $schedule, 'my_group');
|
||||||
|
$created_actions[] = $store->save_action($action);
|
||||||
|
}
|
||||||
|
|
||||||
|
$claim = $store->stake_claim();
|
||||||
|
$this->assertInstanceof( 'ActionScheduler_ActionClaim', $claim );
|
||||||
|
|
||||||
|
$this->assertCount( 3, $claim->get_actions() );
|
||||||
|
$this->assertEqualSets( array_slice( $created_actions, 3, 3 ), $claim->get_actions() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_claim_actions_order() {
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule( as_get_datetime_object( '-1 hour' ) );
|
||||||
|
$created_actions = array(
|
||||||
|
$store->save_action( new ActionScheduler_Action( 'my_hook', array( 1 ), $schedule, 'my_group' ) ),
|
||||||
|
$store->save_action( new ActionScheduler_Action( 'my_hook', array( 1 ), $schedule, 'my_group' ) ),
|
||||||
|
);
|
||||||
|
|
||||||
|
$claim = $store->stake_claim();
|
||||||
|
$this->assertInstanceof( 'ActionScheduler_ActionClaim', $claim );
|
||||||
|
|
||||||
|
// Verify uniqueness of action IDs.
|
||||||
|
$this->assertEquals( 2, count( array_unique( $created_actions ) ) );
|
||||||
|
|
||||||
|
// Verify the count and order of the actions.
|
||||||
|
$claimed_actions = $claim->get_actions();
|
||||||
|
$this->assertCount( 2, $claimed_actions );
|
||||||
|
$this->assertEquals( $created_actions, $claimed_actions );
|
||||||
|
|
||||||
|
// Verify the reversed order doesn't pass.
|
||||||
|
$reversed_actions = array_reverse( $created_actions );
|
||||||
|
$this->assertNotEquals( $reversed_actions, $claimed_actions );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_duplicate_claim() {
|
||||||
|
$created_actions = array();
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
for ( $i = 0 ; $i > -3 ; $i-- ) {
|
||||||
|
$time = as_get_datetime_object($i.' hours');
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array($i), $schedule, 'my_group');
|
||||||
|
$created_actions[] = $store->save_action($action);
|
||||||
|
}
|
||||||
|
|
||||||
|
$claim1 = $store->stake_claim();
|
||||||
|
$claim2 = $store->stake_claim();
|
||||||
|
$this->assertCount( 3, $claim1->get_actions() );
|
||||||
|
$this->assertCount( 0, $claim2->get_actions() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_release_claim() {
|
||||||
|
$created_actions = array();
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
for ( $i = 0 ; $i > -3 ; $i-- ) {
|
||||||
|
$time = as_get_datetime_object($i.' hours');
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array($i), $schedule, 'my_group');
|
||||||
|
$created_actions[] = $store->save_action($action);
|
||||||
|
}
|
||||||
|
|
||||||
|
$claim1 = $store->stake_claim();
|
||||||
|
|
||||||
|
$store->release_claim( $claim1 );
|
||||||
|
|
||||||
|
$claim2 = $store->stake_claim();
|
||||||
|
$this->assertCount( 3, $claim2->get_actions() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_search() {
|
||||||
|
$created_actions = array();
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
for ( $i = -3 ; $i <= 3 ; $i++ ) {
|
||||||
|
$time = as_get_datetime_object($i.' hours');
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array($i), $schedule, 'my_group');
|
||||||
|
$created_actions[] = $store->save_action($action);
|
||||||
|
}
|
||||||
|
|
||||||
|
$next_no_args = $store->find_action( 'my_hook' );
|
||||||
|
$this->assertEquals( $created_actions[0], $next_no_args );
|
||||||
|
|
||||||
|
$next_with_args = $store->find_action( 'my_hook', array( 'args' => array( 1 ) ) );
|
||||||
|
$this->assertEquals( $created_actions[4], $next_with_args );
|
||||||
|
|
||||||
|
$non_existent = $store->find_action( 'my_hook', array( 'args' => array( 17 ) ) );
|
||||||
|
$this->assertNull( $non_existent );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_search_by_group() {
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('tomorrow'));
|
||||||
|
$abc = $store->save_action(new ActionScheduler_Action('my_hook', array(1), $schedule, 'abc'));
|
||||||
|
$def = $store->save_action(new ActionScheduler_Action('my_hook', array(1), $schedule, 'def'));
|
||||||
|
$ghi = $store->save_action(new ActionScheduler_Action('my_hook', array(1), $schedule, 'ghi'));
|
||||||
|
|
||||||
|
$this->assertEquals( $abc, $store->find_action('my_hook', array('group' => 'abc')));
|
||||||
|
$this->assertEquals( $def, $store->find_action('my_hook', array('group' => 'def')));
|
||||||
|
$this->assertEquals( $ghi, $store->find_action('my_hook', array('group' => 'ghi')));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_post_author() {
|
||||||
|
$current_user = get_current_user_id();
|
||||||
|
|
||||||
|
$time = as_get_datetime_object();
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
$action_id = $store->save_action($action);
|
||||||
|
|
||||||
|
$post = get_post($action_id);
|
||||||
|
$this->assertEquals(0, $post->post_author);
|
||||||
|
|
||||||
|
$new_user = $this->factory->user->create_object(array(
|
||||||
|
'user_login' => __FUNCTION__,
|
||||||
|
'user_pass' => md5(rand()),
|
||||||
|
));
|
||||||
|
wp_set_current_user( $new_user );
|
||||||
|
|
||||||
|
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
|
||||||
|
$action_id = $store->save_action($action);
|
||||||
|
$post = get_post($action_id);
|
||||||
|
$this->assertEquals(0, $post->post_author);
|
||||||
|
|
||||||
|
wp_set_current_user($current_user);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @issue 13
|
||||||
|
*/
|
||||||
|
public function test_post_status_for_recurring_action() {
|
||||||
|
$time = as_get_datetime_object('10 minutes');
|
||||||
|
$schedule = new ActionScheduler_IntervalSchedule($time, HOUR_IN_SECONDS);
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
$action_id = $store->save_action($action);
|
||||||
|
|
||||||
|
$action = $store->fetch_action($action_id);
|
||||||
|
$action->execute();
|
||||||
|
$store->mark_complete( $action_id );
|
||||||
|
|
||||||
|
$next = $action->get_schedule()->next( as_get_datetime_object() );
|
||||||
|
$new_action_id = $store->save_action( $action, $next );
|
||||||
|
|
||||||
|
$this->assertEquals('publish', get_post_status($action_id));
|
||||||
|
$this->assertEquals('pending', get_post_status($new_action_id));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_get_run_date() {
|
||||||
|
$time = as_get_datetime_object('-10 minutes');
|
||||||
|
$schedule = new ActionScheduler_IntervalSchedule($time, HOUR_IN_SECONDS);
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
$action_id = $store->save_action($action);
|
||||||
|
|
||||||
|
$this->assertEquals( $store->get_date($action_id)->getTimestamp(), $time->getTimestamp() );
|
||||||
|
|
||||||
|
$action = $store->fetch_action($action_id);
|
||||||
|
$action->execute();
|
||||||
|
$now = as_get_datetime_object();
|
||||||
|
$store->mark_complete( $action_id );
|
||||||
|
|
||||||
|
$this->assertEquals( $store->get_date($action_id)->getTimestamp(), $now->getTimestamp() );
|
||||||
|
|
||||||
|
$next = $action->get_schedule()->next( $now );
|
||||||
|
$new_action_id = $store->save_action( $action, $next );
|
||||||
|
|
||||||
|
$this->assertEquals( (int)($now->getTimestamp()) + HOUR_IN_SECONDS, $store->get_date($new_action_id)->getTimestamp() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_get_status() {
|
||||||
|
$time = as_get_datetime_object('-10 minutes');
|
||||||
|
$schedule = new ActionScheduler_IntervalSchedule($time, HOUR_IN_SECONDS);
|
||||||
|
$action = new ActionScheduler_Action('my_hook', array(), $schedule);
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
$action_id = $store->save_action($action);
|
||||||
|
|
||||||
|
$this->assertEquals( ActionScheduler_Store::STATUS_PENDING, $store->get_status( $action_id ) );
|
||||||
|
|
||||||
|
$store->mark_complete( $action_id );
|
||||||
|
$this->assertEquals( ActionScheduler_Store::STATUS_COMPLETE, $store->get_status( $action_id ) );
|
||||||
|
|
||||||
|
$store->mark_failure( $action_id );
|
||||||
|
$this->assertEquals( ActionScheduler_Store::STATUS_FAILED, $store->get_status( $action_id ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_claim_actions_by_hooks() {
|
||||||
|
$hook1 = __FUNCTION__ . '_hook_1';
|
||||||
|
$hook2 = __FUNCTION__ . '_hook_2';
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule( as_get_datetime_object( '-1 hour' ) );
|
||||||
|
|
||||||
|
$action1 = $store->save_action( new ActionScheduler_Action( $hook1, array(), $schedule ) );
|
||||||
|
$action2 = $store->save_action( new ActionScheduler_Action( $hook2, array(), $schedule ) );
|
||||||
|
|
||||||
|
// Claiming no hooks should include all actions.
|
||||||
|
$claim = $store->stake_claim( 10 );
|
||||||
|
$this->assertEquals( 2, count( $claim->get_actions() ) );
|
||||||
|
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
|
||||||
|
$this->assertTrue( in_array( $action2, $claim->get_actions() ) );
|
||||||
|
$store->release_claim( $claim );
|
||||||
|
|
||||||
|
// Claiming a hook should claim only actions with that hook
|
||||||
|
$claim = $store->stake_claim( 10, null, array( $hook1 ) );
|
||||||
|
$this->assertEquals( 1, count( $claim->get_actions() ) );
|
||||||
|
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
|
||||||
|
$store->release_claim( $claim );
|
||||||
|
|
||||||
|
// Claiming two hooks should claim actions with either of those hooks
|
||||||
|
$claim = $store->stake_claim( 10, null, array( $hook1, $hook2 ) );
|
||||||
|
$this->assertEquals( 2, count( $claim->get_actions() ) );
|
||||||
|
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
|
||||||
|
$this->assertTrue( in_array( $action2, $claim->get_actions() ) );
|
||||||
|
$store->release_claim( $claim );
|
||||||
|
|
||||||
|
// Claiming two hooks should claim actions with either of those hooks
|
||||||
|
$claim = $store->stake_claim( 10, null, array( __METHOD__ . '_hook_3' ) );
|
||||||
|
$this->assertEquals( 0, count( $claim->get_actions() ) );
|
||||||
|
$this->assertFalse( in_array( $action1, $claim->get_actions() ) );
|
||||||
|
$this->assertFalse( in_array( $action2, $claim->get_actions() ) );
|
||||||
|
$store->release_claim( $claim );
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @issue 121
|
||||||
|
*/
|
||||||
|
public function test_claim_actions_by_group() {
|
||||||
|
$group1 = md5( rand() );
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule( as_get_datetime_object( '-1 hour' ) );
|
||||||
|
|
||||||
|
$action1 = $store->save_action( new ActionScheduler_Action( __METHOD__, array(), $schedule, $group1 ) );
|
||||||
|
$action2 = $store->save_action( new ActionScheduler_Action( __METHOD__, array(), $schedule ) );
|
||||||
|
|
||||||
|
// Claiming no group should include all actions.
|
||||||
|
$claim = $store->stake_claim( 10 );
|
||||||
|
$this->assertEquals( 2, count( $claim->get_actions() ) );
|
||||||
|
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
|
||||||
|
$this->assertTrue( in_array( $action2, $claim->get_actions() ) );
|
||||||
|
$store->release_claim( $claim );
|
||||||
|
|
||||||
|
// Claiming a group should claim only actions in that group.
|
||||||
|
$claim = $store->stake_claim( 10, null, array(), $group1 );
|
||||||
|
$this->assertEquals( 1, count( $claim->get_actions() ) );
|
||||||
|
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
|
||||||
|
$store->release_claim( $claim );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_claim_actions_by_hook_and_group() {
|
||||||
|
$hook1 = __FUNCTION__ . '_hook_1';
|
||||||
|
$hook2 = __FUNCTION__ . '_hook_2';
|
||||||
|
$hook3 = __FUNCTION__ . '_hook_3';
|
||||||
|
$group1 = 'group_' . md5( rand() );
|
||||||
|
$group2 = 'group_' . md5( rand() );
|
||||||
|
$store = new ActionScheduler_wpPostStore();
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule( as_get_datetime_object( '-1 hour' ) );
|
||||||
|
|
||||||
|
$action1 = $store->save_action( new ActionScheduler_Action( $hook1, array(), $schedule, $group1 ) );
|
||||||
|
$action2 = $store->save_action( new ActionScheduler_Action( $hook2, array(), $schedule ) );
|
||||||
|
$action3 = $store->save_action( new ActionScheduler_Action( $hook3, array(), $schedule, $group2 ) );
|
||||||
|
|
||||||
|
// Claiming no hooks or group should include all actions.
|
||||||
|
$claim = $store->stake_claim( 10 );
|
||||||
|
$this->assertEquals( 3, count( $claim->get_actions() ) );
|
||||||
|
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
|
||||||
|
$this->assertTrue( in_array( $action2, $claim->get_actions() ) );
|
||||||
|
$store->release_claim( $claim );
|
||||||
|
|
||||||
|
// Claiming a group and hook should claim only actions in that group.
|
||||||
|
$claim = $store->stake_claim( 10, null, array( $hook1 ), $group1 );
|
||||||
|
$this->assertEquals( 1, count( $claim->get_actions() ) );
|
||||||
|
$this->assertTrue( in_array( $action1, $claim->get_actions() ) );
|
||||||
|
$store->release_claim( $claim );
|
||||||
|
|
||||||
|
// Claiming a group and hook should claim only actions with that hook in that group.
|
||||||
|
$claim = $store->stake_claim( 10, null, array( $hook2 ), $group1 );
|
||||||
|
$this->assertEquals( 0, count( $claim->get_actions() ) );
|
||||||
|
$this->assertFalse( in_array( $action1, $claim->get_actions() ) );
|
||||||
|
$this->assertFalse( in_array( $action2, $claim->get_actions() ) );
|
||||||
|
$store->release_claim( $claim );
|
||||||
|
|
||||||
|
// Claiming a group and hook should claim only actions with that hook in that group.
|
||||||
|
$claim = $store->stake_claim( 10, null, array( $hook1, $hook2 ), $group2 );
|
||||||
|
$this->assertEquals( 0, count( $claim->get_actions() ) );
|
||||||
|
$this->assertFalse( in_array( $action1, $claim->get_actions() ) );
|
||||||
|
$this->assertFalse( in_array( $action2, $claim->get_actions() ) );
|
||||||
|
$store->release_claim( $claim );
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,166 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_wpCommentLogger_Test
|
||||||
|
* @package test_cases\logging
|
||||||
|
*/
|
||||||
|
class ActionScheduler_wpCommentLogger_Test extends ActionScheduler_UnitTestCase {
|
||||||
|
public function test_default_logger() {
|
||||||
|
$logger = ActionScheduler::logger();
|
||||||
|
$this->assertInstanceOf( 'ActionScheduler_Logger', $logger );
|
||||||
|
$this->assertInstanceOf( 'ActionScheduler_wpCommentLogger', $logger );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_add_log_entry() {
|
||||||
|
$action_id = wc_schedule_single_action( time(), 'a hook' );
|
||||||
|
$logger = ActionScheduler::logger();
|
||||||
|
$message = 'Logging that something happened';
|
||||||
|
$log_id = $logger->log( $action_id, $message );
|
||||||
|
$entry = $logger->get_entry( $log_id );
|
||||||
|
|
||||||
|
$this->assertEquals( $action_id, $entry->get_action_id() );
|
||||||
|
$this->assertEquals( $message, $entry->get_message() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_null_log_entry() {
|
||||||
|
$logger = ActionScheduler::logger();
|
||||||
|
$entry = $logger->get_entry( 1 );
|
||||||
|
$this->assertEquals( '', $entry->get_action_id() );
|
||||||
|
$this->assertEquals( '', $entry->get_message() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_erroneous_entry_id() {
|
||||||
|
$comment = wp_insert_comment(array(
|
||||||
|
'comment_post_ID' => 1,
|
||||||
|
'comment_author' => 'test',
|
||||||
|
'comment_content' => 'this is not a log entry',
|
||||||
|
));
|
||||||
|
$logger = ActionScheduler::logger();
|
||||||
|
$entry = $logger->get_entry( $comment );
|
||||||
|
$this->assertEquals( '', $entry->get_action_id() );
|
||||||
|
$this->assertEquals( '', $entry->get_message() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_storage_comments() {
|
||||||
|
$action_id = wc_schedule_single_action( time(), 'a hook' );
|
||||||
|
$logger = ActionScheduler::logger();
|
||||||
|
$logs = $logger->get_logs( $action_id );
|
||||||
|
$expected = new ActionScheduler_LogEntry( $action_id, 'action created' );
|
||||||
|
$this->assertTrue( in_array( $this->log_entry_to_array( $expected ) , $this->log_entry_to_array( $logs ) ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function log_entry_to_array( $logs ) {
|
||||||
|
if ( $logs instanceof ActionScheduler_LogEntry ) {
|
||||||
|
return array( 'action_id' => $logs->get_action_id(), 'message' => $logs->get_message() );
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ( $logs as $id => $log) {
|
||||||
|
$logs[ $id ] = array( 'action_id' => $log->get_action_id(), 'message' => $log->get_message() );
|
||||||
|
}
|
||||||
|
|
||||||
|
return $logs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_execution_comments() {
|
||||||
|
$action_id = wc_schedule_single_action( time(), 'a hook' );
|
||||||
|
$logger = ActionScheduler::logger();
|
||||||
|
$started = new ActionScheduler_LogEntry( $action_id, 'action started' );
|
||||||
|
$finished = new ActionScheduler_LogEntry( $action_id, 'action complete' );
|
||||||
|
|
||||||
|
$runner = new ActionScheduler_QueueRunner();
|
||||||
|
$runner->run();
|
||||||
|
|
||||||
|
$logs = $logger->get_logs( $action_id );
|
||||||
|
$this->assertTrue( in_array( $this->log_entry_to_array( $started ), $this->log_entry_to_array( $logs ) ) );
|
||||||
|
$this->assertTrue( in_array( $this->log_entry_to_array( $finished ), $this->log_entry_to_array( $logs ) ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_failed_execution_comments() {
|
||||||
|
$hook = md5(rand());
|
||||||
|
add_action( $hook, array( $this, '_a_hook_callback_that_throws_an_exception' ) );
|
||||||
|
$action_id = wc_schedule_single_action( time(), $hook );
|
||||||
|
$logger = ActionScheduler::logger();
|
||||||
|
$started = new ActionScheduler_LogEntry( $action_id, 'action started' );
|
||||||
|
$finished = new ActionScheduler_LogEntry( $action_id, 'action complete' );
|
||||||
|
$failed = new ActionScheduler_LogEntry( $action_id, 'action failed: Execution failed' );
|
||||||
|
|
||||||
|
$runner = new ActionScheduler_QueueRunner();
|
||||||
|
$runner->run();
|
||||||
|
|
||||||
|
$logs = $logger->get_logs( $action_id );
|
||||||
|
$this->assertTrue( in_array( $this->log_entry_to_array( $started ), $this->log_entry_to_array( $logs ) ) );
|
||||||
|
$this->assertFalse( in_array( $this->log_entry_to_array( $finished ), $this->log_entry_to_array( $logs ) ) );
|
||||||
|
$this->assertTrue( in_array( $this->log_entry_to_array( $failed ), $this->log_entry_to_array( $logs ) ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_fatal_error_comments() {
|
||||||
|
$hook = md5(rand());
|
||||||
|
$action_id = wc_schedule_single_action( time(), $hook );
|
||||||
|
$logger = ActionScheduler::logger();
|
||||||
|
do_action( 'action_scheduler_unexpected_shutdown', $action_id, array(
|
||||||
|
'type' => E_ERROR,
|
||||||
|
'message' => 'Test error',
|
||||||
|
'file' => __FILE__,
|
||||||
|
'line' => __LINE__,
|
||||||
|
));
|
||||||
|
|
||||||
|
$logs = $logger->get_logs( $action_id );
|
||||||
|
$found_log = FALSE;
|
||||||
|
foreach ( $logs as $l ) {
|
||||||
|
if ( strpos( $l->get_message(), 'unexpected shutdown' ) === 0 ) {
|
||||||
|
$found_log = TRUE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$this->assertTrue( $found_log, 'Unexpected shutdown log not found' );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_canceled_action_comments() {
|
||||||
|
$action_id = wc_schedule_single_action( time(), 'a hook' );
|
||||||
|
wc_unschedule_action( 'a hook' );
|
||||||
|
$logger = ActionScheduler::logger();
|
||||||
|
$logs = $logger->get_logs( $action_id );
|
||||||
|
$expected = new ActionScheduler_LogEntry( $action_id, 'action canceled' );
|
||||||
|
$this->assertTrue( in_array( $this->log_entry_to_array( $expected ), $this->log_entry_to_array( $logs ) ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function _a_hook_callback_that_throws_an_exception() {
|
||||||
|
throw new RuntimeException('Execution failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_filtering_of_get_comments() {
|
||||||
|
$post_id = $this->factory->post->create_object(array(
|
||||||
|
'post_title' => __FUNCTION__,
|
||||||
|
));
|
||||||
|
$comment_id = $this->factory->comment->create_object(array(
|
||||||
|
'comment_post_ID' => $post_id,
|
||||||
|
'comment_author' => __CLASS__,
|
||||||
|
'comment_content' => __FUNCTION__,
|
||||||
|
));
|
||||||
|
|
||||||
|
// Verify that we're getting the expected comment before we add logging comments
|
||||||
|
$comments = get_comments();
|
||||||
|
$this->assertCount( 1, $comments );
|
||||||
|
$this->assertEquals( $comment_id, $comments[0]->comment_ID );
|
||||||
|
|
||||||
|
|
||||||
|
$action_id = wc_schedule_single_action( time(), 'a hook' );
|
||||||
|
$logger = ActionScheduler::logger();
|
||||||
|
$message = 'Logging that something happened';
|
||||||
|
$log_id = $logger->log( $action_id, $message );
|
||||||
|
|
||||||
|
|
||||||
|
// Verify that logging comments are excluded from general comment queries
|
||||||
|
$comments = get_comments();
|
||||||
|
$this->assertCount( 1, $comments );
|
||||||
|
$this->assertEquals( $comment_id, $comments[0]->comment_ID );
|
||||||
|
|
||||||
|
// Verify that logging comments are returned when asking for them specifically
|
||||||
|
$comments = get_comments(array(
|
||||||
|
'type' => ActionScheduler_wpCommentLogger::TYPE,
|
||||||
|
));
|
||||||
|
// Expecting two: one when the action is created, another when we added our custom log
|
||||||
|
$this->assertCount( 2, $comments );
|
||||||
|
$this->assertContains( $log_id, wp_list_pluck($comments, 'comment_ID'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,142 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class procedural_api_Test
|
||||||
|
*/
|
||||||
|
class procedural_api_Test extends ActionScheduler_UnitTestCase {
|
||||||
|
|
||||||
|
public function test_schedule_action() {
|
||||||
|
$time = time();
|
||||||
|
$hook = md5(rand());
|
||||||
|
$action_id = wc_schedule_single_action( $time, $hook );
|
||||||
|
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
$action = $store->fetch_action($action_id);
|
||||||
|
$this->assertEquals( $time, $action->get_schedule()->next()->getTimestamp() );
|
||||||
|
$this->assertEquals( $hook, $action->get_hook() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_recurring_action() {
|
||||||
|
$time = time();
|
||||||
|
$hook = md5(rand());
|
||||||
|
$action_id = wc_schedule_recurring_action( $time, HOUR_IN_SECONDS, $hook );
|
||||||
|
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
$action = $store->fetch_action($action_id);
|
||||||
|
$this->assertEquals( $time, $action->get_schedule()->next()->getTimestamp() );
|
||||||
|
$this->assertEquals( $time + HOUR_IN_SECONDS + 2, $action->get_schedule()->next(as_get_datetime_object($time + 2))->getTimestamp());
|
||||||
|
$this->assertEquals( $hook, $action->get_hook() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_cron_schedule() {
|
||||||
|
$time = as_get_datetime_object('2014-01-01');
|
||||||
|
$hook = md5(rand());
|
||||||
|
$action_id = wc_schedule_cron_action( $time->getTimestamp(), '0 0 10 10 *', $hook );
|
||||||
|
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
$action = $store->fetch_action($action_id);
|
||||||
|
$expected_date = as_get_datetime_object('2014-10-10');
|
||||||
|
$this->assertEquals( $expected_date->getTimestamp(), $action->get_schedule()->next()->getTimestamp() );
|
||||||
|
$this->assertEquals( $hook, $action->get_hook() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_get_next() {
|
||||||
|
$time = as_get_datetime_object('tomorrow');
|
||||||
|
$hook = md5(rand());
|
||||||
|
wc_schedule_recurring_action( $time->getTimestamp(), HOUR_IN_SECONDS, $hook );
|
||||||
|
|
||||||
|
$next = wc_next_scheduled_action( $hook );
|
||||||
|
|
||||||
|
$this->assertEquals( $time->getTimestamp(), $next );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_unschedule() {
|
||||||
|
$time = time();
|
||||||
|
$hook = md5(rand());
|
||||||
|
$action_id = wc_schedule_single_action( $time, $hook );
|
||||||
|
|
||||||
|
wc_unschedule_action( $hook );
|
||||||
|
|
||||||
|
$next = wc_next_scheduled_action( $hook );
|
||||||
|
$this->assertFalse($next);
|
||||||
|
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
$action = $store->fetch_action($action_id);
|
||||||
|
|
||||||
|
$this->assertNull($action->get_schedule()->next());
|
||||||
|
$this->assertEquals($hook, $action->get_hook() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_as_get_datetime_object_default() {
|
||||||
|
|
||||||
|
$utc_now = new ActionScheduler_DateTime(null, new DateTimeZone('UTC'));
|
||||||
|
$as_now = as_get_datetime_object();
|
||||||
|
|
||||||
|
// Don't want to use 'U' as timestamps will always be in UTC
|
||||||
|
$this->assertEquals($utc_now->format('Y-m-d H:i:s'),$as_now->format('Y-m-d H:i:s'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_as_get_datetime_object_relative() {
|
||||||
|
|
||||||
|
$utc_tomorrow = new ActionScheduler_DateTime('tomorrow', new DateTimeZone('UTC'));
|
||||||
|
$as_tomorrow = as_get_datetime_object('tomorrow');
|
||||||
|
|
||||||
|
$this->assertEquals($utc_tomorrow->format('Y-m-d H:i:s'),$as_tomorrow->format('Y-m-d H:i:s'));
|
||||||
|
|
||||||
|
$utc_tomorrow = new ActionScheduler_DateTime('yesterday', new DateTimeZone('UTC'));
|
||||||
|
$as_tomorrow = as_get_datetime_object('yesterday');
|
||||||
|
|
||||||
|
$this->assertEquals($utc_tomorrow->format('Y-m-d H:i:s'),$as_tomorrow->format('Y-m-d H:i:s'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_as_get_datetime_object_fixed() {
|
||||||
|
|
||||||
|
$utc_tomorrow = new ActionScheduler_DateTime('29 February 2016', new DateTimeZone('UTC'));
|
||||||
|
$as_tomorrow = as_get_datetime_object('29 February 2016');
|
||||||
|
|
||||||
|
$this->assertEquals($utc_tomorrow->format('Y-m-d H:i:s'),$as_tomorrow->format('Y-m-d H:i:s'));
|
||||||
|
|
||||||
|
$utc_tomorrow = new ActionScheduler_DateTime('1st January 2024', new DateTimeZone('UTC'));
|
||||||
|
$as_tomorrow = as_get_datetime_object('1st January 2024');
|
||||||
|
|
||||||
|
$this->assertEquals($utc_tomorrow->format('Y-m-d H:i:s'),$as_tomorrow->format('Y-m-d H:i:s'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_as_get_datetime_object_timezone() {
|
||||||
|
|
||||||
|
$timezone_au = 'Australia/Brisbane';
|
||||||
|
$timezone_default = date_default_timezone_get();
|
||||||
|
|
||||||
|
date_default_timezone_set( $timezone_au );
|
||||||
|
|
||||||
|
$au_now = new ActionScheduler_DateTime(null);
|
||||||
|
$as_now = as_get_datetime_object();
|
||||||
|
|
||||||
|
// Make sure they're for the same time
|
||||||
|
$this->assertEquals($au_now->getTimestamp(),$as_now->getTimestamp());
|
||||||
|
|
||||||
|
// But not in the same timezone, as $as_now should be using UTC
|
||||||
|
$this->assertNotEquals($au_now->format('Y-m-d H:i:s'),$as_now->format('Y-m-d H:i:s'));
|
||||||
|
|
||||||
|
$au_now = new ActionScheduler_DateTime(null);
|
||||||
|
$as_au_now = as_get_datetime_object();
|
||||||
|
|
||||||
|
$this->assertEquals($au_now->getTimestamp(),$as_now->getTimestamp());
|
||||||
|
|
||||||
|
// But not in the same timezone, as $as_now should be using UTC
|
||||||
|
$this->assertNotEquals($au_now->format('Y-m-d H:i:s'),$as_now->format('Y-m-d H:i:s'));
|
||||||
|
|
||||||
|
// Just in cases
|
||||||
|
date_default_timezone_set( $timezone_default );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_as_get_datetime_object_type() {
|
||||||
|
$f = 'Y-m-d H:i:s';
|
||||||
|
$now = as_get_datetime_object();
|
||||||
|
$this->assertInstanceOf( 'ActionScheduler_DateTime', $now );
|
||||||
|
|
||||||
|
$dateTime = new DateTime( 'now', new DateTimeZone( 'UTC' ) );
|
||||||
|
$asDateTime = as_get_datetime_object( $dateTime );
|
||||||
|
$this->assertEquals( $dateTime->format( $f ), $asDateTime->format( $f ) );
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,100 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class wc_get_scheduled_actions_Test
|
||||||
|
*/
|
||||||
|
class wc_get_scheduled_actions_Test extends ActionScheduler_UnitTestCase {
|
||||||
|
private $hooks = array();
|
||||||
|
private $args = array();
|
||||||
|
private $groups = array();
|
||||||
|
|
||||||
|
public function setUp() {
|
||||||
|
parent::setUp();
|
||||||
|
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
|
||||||
|
for ( $i = 0 ; $i < 10 ; $i++ ) {
|
||||||
|
$this->hooks[$i] = md5(rand());
|
||||||
|
$this->args[$i] = md5(rand());
|
||||||
|
$this->groups[$i] = md5(rand());
|
||||||
|
}
|
||||||
|
|
||||||
|
for ( $i = 0 ; $i < 10 ; $i++ ) {
|
||||||
|
for ( $j = 0 ; $j < 10 ; $j++ ) {
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule( as_get_datetime_object( $j - 3 . 'days') );
|
||||||
|
$group = $this->groups[ ( $i + $j ) % 10 ];
|
||||||
|
$action = new ActionScheduler_Action( $this->hooks[$i], array($this->args[$j]), $schedule, $group );
|
||||||
|
$store->save_action( $action );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_date_queries() {
|
||||||
|
$actions = wc_get_scheduled_actions(array(
|
||||||
|
'date' => as_get_datetime_object(gmdate('Y-m-d 00:00:00')),
|
||||||
|
'per_page' => -1,
|
||||||
|
), 'ids');
|
||||||
|
$this->assertCount(30, $actions);
|
||||||
|
|
||||||
|
$actions = wc_get_scheduled_actions(array(
|
||||||
|
'date' => as_get_datetime_object(gmdate('Y-m-d 00:00:00')),
|
||||||
|
'date_compare' => '>=',
|
||||||
|
'per_page' => -1,
|
||||||
|
), 'ids');
|
||||||
|
$this->assertCount(70, $actions);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_hook_queries() {
|
||||||
|
$actions = wc_get_scheduled_actions(array(
|
||||||
|
'hook' => $this->hooks[2],
|
||||||
|
'per_page' => -1,
|
||||||
|
), 'ids');
|
||||||
|
$this->assertCount(10, $actions);
|
||||||
|
|
||||||
|
$actions = wc_get_scheduled_actions(array(
|
||||||
|
'hook' => $this->hooks[2],
|
||||||
|
'date' => as_get_datetime_object(gmdate('Y-m-d 00:00:00')),
|
||||||
|
'per_page' => -1,
|
||||||
|
), 'ids');
|
||||||
|
$this->assertCount(3, $actions);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_args_queries() {
|
||||||
|
$actions = wc_get_scheduled_actions(array(
|
||||||
|
'args' => array($this->args[5]),
|
||||||
|
'per_page' => -1,
|
||||||
|
), 'ids');
|
||||||
|
$this->assertCount(10, $actions);
|
||||||
|
|
||||||
|
$actions = wc_get_scheduled_actions(array(
|
||||||
|
'args' => array($this->args[5]),
|
||||||
|
'hook' => $this->hooks[3],
|
||||||
|
'per_page' => -1,
|
||||||
|
), 'ids');
|
||||||
|
$this->assertCount(1, $actions);
|
||||||
|
|
||||||
|
$actions = wc_get_scheduled_actions(array(
|
||||||
|
'args' => array($this->args[5]),
|
||||||
|
'hook' => $this->hooks[3],
|
||||||
|
'date' => as_get_datetime_object(gmdate('Y-m-d 00:00:00')),
|
||||||
|
'per_page' => -1,
|
||||||
|
), 'ids');
|
||||||
|
$this->assertCount(0, $actions);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_group_queries() {
|
||||||
|
$actions = wc_get_scheduled_actions(array(
|
||||||
|
'group' => $this->groups[1],
|
||||||
|
'per_page' => -1,
|
||||||
|
), 'ids');
|
||||||
|
$this->assertCount(10, $actions);
|
||||||
|
|
||||||
|
$actions = wc_get_scheduled_actions(array(
|
||||||
|
'group' => $this->groups[1],
|
||||||
|
'hook' => $this->hooks[9],
|
||||||
|
'per_page' => -1,
|
||||||
|
), 'ids');
|
||||||
|
$this->assertCount(1, $actions);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,151 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_QueueCleaner_Test
|
||||||
|
*/
|
||||||
|
class ActionScheduler_QueueCleaner_Test extends ActionScheduler_UnitTestCase {
|
||||||
|
|
||||||
|
public function test_delete_old_actions() {
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
$runner = new ActionScheduler_QueueRunner( $store );
|
||||||
|
|
||||||
|
$random = md5(rand());
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
|
||||||
|
|
||||||
|
$created_actions = array();
|
||||||
|
for ( $i = 0 ; $i < 5 ; $i++ ) {
|
||||||
|
$action = new ActionScheduler_Action( $random, array($random), $schedule );
|
||||||
|
$created_actions[] = $store->save_action( $action );
|
||||||
|
}
|
||||||
|
|
||||||
|
$runner->run();
|
||||||
|
|
||||||
|
add_filter( 'action_scheduler_retention_period', '__return_zero' ); // delete any finished job
|
||||||
|
$cleaner = new ActionScheduler_QueueCleaner( $store );
|
||||||
|
$cleaner->delete_old_actions();
|
||||||
|
remove_filter( 'action_scheduler_retention_period', '__return_zero' );
|
||||||
|
|
||||||
|
foreach ( $created_actions as $action_id ) {
|
||||||
|
$action = $store->fetch_action($action_id);
|
||||||
|
$this->assertFalse($action->is_finished()); // it's a NullAction
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_delete_canceled_actions() {
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
|
||||||
|
$random = md5(rand());
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
|
||||||
|
|
||||||
|
$created_actions = array();
|
||||||
|
for ( $i = 0 ; $i < 5 ; $i++ ) {
|
||||||
|
$action = new ActionScheduler_Action( $random, array($random), $schedule );
|
||||||
|
$action_id = $store->save_action( $action );
|
||||||
|
$store->cancel_action( $action_id );
|
||||||
|
$created_actions[] = $action_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
// track the actions that are deleted
|
||||||
|
$mock_action = new MockAction();
|
||||||
|
add_action( 'action_scheduler_deleted_action', array( $mock_action, 'action' ), 10, 1 );
|
||||||
|
add_filter( 'action_scheduler_retention_period', '__return_zero' ); // delete any finished job
|
||||||
|
|
||||||
|
$cleaner = new ActionScheduler_QueueCleaner( $store );
|
||||||
|
$cleaner->delete_old_actions();
|
||||||
|
|
||||||
|
remove_filter( 'action_scheduler_retention_period', '__return_zero' );
|
||||||
|
remove_action( 'action_scheduler_deleted_action', array( $mock_action, 'action' ), 10 );
|
||||||
|
|
||||||
|
$deleted_actions = array_map( 'reset', $mock_action->get_args() );
|
||||||
|
$this->assertEqualSets( $created_actions, $deleted_actions );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_do_not_delete_recent_actions() {
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
$runner = new ActionScheduler_QueueRunner( $store );
|
||||||
|
|
||||||
|
$random = md5(rand());
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
|
||||||
|
|
||||||
|
$created_actions = array();
|
||||||
|
for ( $i = 0 ; $i < 5 ; $i++ ) {
|
||||||
|
$action = new ActionScheduler_Action( $random, array($random), $schedule );
|
||||||
|
$created_actions[] = $store->save_action( $action );
|
||||||
|
}
|
||||||
|
|
||||||
|
$runner->run();
|
||||||
|
|
||||||
|
$cleaner = new ActionScheduler_QueueCleaner( $store );
|
||||||
|
$cleaner->delete_old_actions();
|
||||||
|
|
||||||
|
foreach ( $created_actions as $action_id ) {
|
||||||
|
$action = $store->fetch_action($action_id);
|
||||||
|
$this->assertTrue($action->is_finished()); // It's a FinishedAction
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_reset_unrun_actions() {
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
|
||||||
|
$random = md5(rand());
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
|
||||||
|
|
||||||
|
$created_actions = array();
|
||||||
|
for ( $i = 0 ; $i < 5 ; $i++ ) {
|
||||||
|
$action = new ActionScheduler_Action( $random, array($random), $schedule );
|
||||||
|
$created_actions[] = $store->save_action( $action );
|
||||||
|
}
|
||||||
|
|
||||||
|
$store->stake_claim(10);
|
||||||
|
|
||||||
|
// don't actually process the jobs, to simulate a request that timed out
|
||||||
|
|
||||||
|
add_filter( 'action_scheduler_timeout_period', '__return_zero' ); // delete any finished job
|
||||||
|
$cleaner = new ActionScheduler_QueueCleaner( $store );
|
||||||
|
$cleaner->reset_timeouts();
|
||||||
|
|
||||||
|
remove_filter( 'action_scheduler_timeout_period', '__return_zero' );
|
||||||
|
|
||||||
|
$claim = $store->stake_claim(10);
|
||||||
|
$this->assertEqualSets($created_actions, $claim->get_actions());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_do_not_reset_failed_action() {
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
|
||||||
|
$random = md5(rand());
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
|
||||||
|
|
||||||
|
$created_actions = array();
|
||||||
|
for ( $i = 0 ; $i < 5 ; $i++ ) {
|
||||||
|
$action = new ActionScheduler_Action( $random, array($random), $schedule );
|
||||||
|
$created_actions[] = $store->save_action( $action );
|
||||||
|
}
|
||||||
|
|
||||||
|
$claim = $store->stake_claim(10);
|
||||||
|
foreach ( $claim->get_actions() as $action_id ) {
|
||||||
|
// simulate the first action interrupted by an uncatchable fatal error
|
||||||
|
$store->log_execution( $action_id );
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
add_filter( 'action_scheduler_timeout_period', '__return_zero' ); // delete any finished job
|
||||||
|
$cleaner = new ActionScheduler_QueueCleaner( $store );
|
||||||
|
$cleaner->reset_timeouts();
|
||||||
|
remove_filter( 'action_scheduler_timeout_period', '__return_zero' );
|
||||||
|
|
||||||
|
$new_claim = $store->stake_claim(10);
|
||||||
|
$this->assertCount( 4, $new_claim->get_actions() );
|
||||||
|
|
||||||
|
add_filter( 'action_scheduler_failure_period', '__return_zero' );
|
||||||
|
$cleaner->mark_failures();
|
||||||
|
remove_filter( 'action_scheduler_failure_period', '__return_zero' );
|
||||||
|
|
||||||
|
$failed = $store->query_actions(array('status' => ActionScheduler_Store::STATUS_FAILED));
|
||||||
|
$this->assertEquals( $created_actions[0], $failed[0] );
|
||||||
|
$this->assertCount( 1, $failed );
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,209 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_QueueRunner_Test
|
||||||
|
* @group runners
|
||||||
|
*/
|
||||||
|
class ActionScheduler_QueueRunner_Test extends ActionScheduler_UnitTestCase {
|
||||||
|
public function test_create_runner() {
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
$runner = new ActionScheduler_QueueRunner( $store );
|
||||||
|
$actions_run = $runner->run();
|
||||||
|
|
||||||
|
$this->assertEquals( 0, $actions_run );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_run() {
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
$runner = new ActionScheduler_QueueRunner( $store );
|
||||||
|
|
||||||
|
$mock = new MockAction();
|
||||||
|
$random = md5(rand());
|
||||||
|
add_action( $random, array( $mock, 'action' ) );
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
|
||||||
|
|
||||||
|
for ( $i = 0 ; $i < 5 ; $i++ ) {
|
||||||
|
$action = new ActionScheduler_Action( $random, array($random), $schedule );
|
||||||
|
$store->save_action( $action );
|
||||||
|
}
|
||||||
|
|
||||||
|
$actions_run = $runner->run();
|
||||||
|
|
||||||
|
remove_action( $random, array( $mock, 'action' ) );
|
||||||
|
|
||||||
|
$this->assertEquals( 5, $mock->get_call_count() );
|
||||||
|
$this->assertEquals( 5, $actions_run );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_run_with_future_actions() {
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
$runner = new ActionScheduler_QueueRunner( $store );
|
||||||
|
|
||||||
|
$mock = new MockAction();
|
||||||
|
$random = md5(rand());
|
||||||
|
add_action( $random, array( $mock, 'action' ) );
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('1 day ago'));
|
||||||
|
|
||||||
|
for ( $i = 0 ; $i < 3 ; $i++ ) {
|
||||||
|
$action = new ActionScheduler_Action( $random, array($random), $schedule );
|
||||||
|
$store->save_action( $action );
|
||||||
|
}
|
||||||
|
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('tomorrow'));
|
||||||
|
for ( $i = 0 ; $i < 3 ; $i++ ) {
|
||||||
|
$action = new ActionScheduler_Action( $random, array($random), $schedule );
|
||||||
|
$store->save_action( $action );
|
||||||
|
}
|
||||||
|
|
||||||
|
$actions_run = $runner->run();
|
||||||
|
|
||||||
|
remove_action( $random, array( $mock, 'action' ) );
|
||||||
|
|
||||||
|
$this->assertEquals( 3, $mock->get_call_count() );
|
||||||
|
$this->assertEquals( 3, $actions_run );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_completed_action_status() {
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
$runner = new ActionScheduler_QueueRunner( $store );
|
||||||
|
|
||||||
|
$random = md5(rand());
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('12 hours ago'));
|
||||||
|
|
||||||
|
$action = new ActionScheduler_Action( $random, array(), $schedule );
|
||||||
|
$action_id = $store->save_action( $action );
|
||||||
|
|
||||||
|
$runner->run();
|
||||||
|
|
||||||
|
$finished_action = $store->fetch_action( $action_id );
|
||||||
|
|
||||||
|
$this->assertTrue( $finished_action->is_finished() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_next_instance_of_action() {
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
$runner = new ActionScheduler_QueueRunner( $store );
|
||||||
|
|
||||||
|
$random = md5(rand());
|
||||||
|
$schedule = new ActionScheduler_IntervalSchedule(as_get_datetime_object('12 hours ago'), DAY_IN_SECONDS);
|
||||||
|
|
||||||
|
$action = new ActionScheduler_Action( $random, array(), $schedule );
|
||||||
|
$store->save_action( $action );
|
||||||
|
|
||||||
|
$runner->run();
|
||||||
|
|
||||||
|
$claim = $store->stake_claim(10, as_get_datetime_object((DAY_IN_SECONDS - 60).' seconds'));
|
||||||
|
$this->assertCount(0, $claim->get_actions());
|
||||||
|
|
||||||
|
$claim = $store->stake_claim(10, as_get_datetime_object(DAY_IN_SECONDS.' seconds'));
|
||||||
|
$actions = $claim->get_actions();
|
||||||
|
$this->assertCount(1, $actions);
|
||||||
|
|
||||||
|
$action_id = reset($actions);
|
||||||
|
$new_action = $store->fetch_action($action_id);
|
||||||
|
|
||||||
|
|
||||||
|
$this->assertEquals( $random, $new_action->get_hook() );
|
||||||
|
$this->assertEquals( $schedule->next(as_get_datetime_object())->getTimestamp(), $new_action->get_schedule()->next(as_get_datetime_object())->getTimestamp() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_hooked_into_wp_cron() {
|
||||||
|
$next = wp_next_scheduled( ActionScheduler_QueueRunner::WP_CRON_HOOK );
|
||||||
|
$this->assertNotEmpty($next);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_batch_count_limit() {
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
$runner = new ActionScheduler_QueueRunner( $store );
|
||||||
|
|
||||||
|
$mock = new MockAction();
|
||||||
|
$random = md5(rand());
|
||||||
|
add_action( $random, array( $mock, 'action' ) );
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule(new ActionScheduler_DateTime('1 day ago'));
|
||||||
|
|
||||||
|
for ( $i = 0 ; $i < 30 ; $i++ ) {
|
||||||
|
$action = new ActionScheduler_Action( $random, array($random), $schedule );
|
||||||
|
$store->save_action( $action );
|
||||||
|
}
|
||||||
|
|
||||||
|
$claims = array();
|
||||||
|
|
||||||
|
for ( $i = 0 ; $i < 5 ; $i++ ) {
|
||||||
|
$claims[] = $store->stake_claim( 5 );
|
||||||
|
}
|
||||||
|
|
||||||
|
$actions_run = $runner->run();
|
||||||
|
|
||||||
|
|
||||||
|
$this->assertEquals( 0, $mock->get_call_count() );
|
||||||
|
$this->assertEquals( 0, $actions_run );
|
||||||
|
|
||||||
|
$first = reset($claims);
|
||||||
|
$store->release_claim( $first );
|
||||||
|
|
||||||
|
$actions_run = $runner->run();
|
||||||
|
$this->assertEquals( 10, $mock->get_call_count() );
|
||||||
|
$this->assertEquals( 10, $actions_run );
|
||||||
|
|
||||||
|
remove_action( $random, array( $mock, 'action' ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_changing_batch_count_limit() {
|
||||||
|
$store = ActionScheduler::store();
|
||||||
|
$runner = new ActionScheduler_QueueRunner( $store );
|
||||||
|
|
||||||
|
$random = md5(rand());
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule(new ActionScheduler_DateTime('1 day ago'));
|
||||||
|
|
||||||
|
for ( $i = 0 ; $i < 30 ; $i++ ) {
|
||||||
|
$action = new ActionScheduler_Action( $random, array($random), $schedule );
|
||||||
|
$store->save_action( $action );
|
||||||
|
}
|
||||||
|
|
||||||
|
$claims = array();
|
||||||
|
|
||||||
|
for ( $i = 0 ; $i < 5 ; $i++ ) {
|
||||||
|
$claims[] = $store->stake_claim( 5 );
|
||||||
|
}
|
||||||
|
|
||||||
|
$mock1 = new MockAction();
|
||||||
|
add_action( $random, array( $mock1, 'action' ) );
|
||||||
|
$actions_run = $runner->run();
|
||||||
|
remove_action( $random, array( $mock1, 'action' ) );
|
||||||
|
|
||||||
|
$this->assertEquals( 0, $mock1->get_call_count() );
|
||||||
|
$this->assertEquals( 0, $actions_run );
|
||||||
|
|
||||||
|
|
||||||
|
add_filter( 'action_scheduler_queue_runner_concurrent_batches', array( $this, 'return_6' ) );
|
||||||
|
|
||||||
|
$mock2 = new MockAction();
|
||||||
|
add_action( $random, array( $mock2, 'action' ) );
|
||||||
|
$actions_run = $runner->run();
|
||||||
|
remove_action( $random, array( $mock2, 'action' ) );
|
||||||
|
|
||||||
|
$this->assertEquals( 5, $mock2->get_call_count() );
|
||||||
|
$this->assertEquals( 5, $actions_run );
|
||||||
|
|
||||||
|
remove_filter( 'action_scheduler_queue_runner_concurrent_batches', array( $this, 'return_6' ) );
|
||||||
|
|
||||||
|
for ( $i = 0 ; $i < 5 ; $i++ ) { // to make up for the actions we just processed
|
||||||
|
$action = new ActionScheduler_Action( $random, array($random), $schedule );
|
||||||
|
$store->save_action( $action );
|
||||||
|
}
|
||||||
|
|
||||||
|
$mock3 = new MockAction();
|
||||||
|
add_action( $random, array( $mock3, 'action' ) );
|
||||||
|
$actions_run = $runner->run();
|
||||||
|
remove_action( $random, array( $mock3, 'action' ) );
|
||||||
|
|
||||||
|
$this->assertEquals( 0, $mock3->get_call_count() );
|
||||||
|
$this->assertEquals( 0, $actions_run );
|
||||||
|
|
||||||
|
remove_filter( 'action_scheduler_queue_runner_concurrent_batches', array( $this, 'return_6' ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function return_6() {
|
||||||
|
return 6;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,45 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_CronSchedule_Test
|
||||||
|
* @group schedules
|
||||||
|
*/
|
||||||
|
class ActionScheduler_CronSchedule_Test extends ActionScheduler_UnitTestCase {
|
||||||
|
public function test_creation() {
|
||||||
|
$time = as_get_datetime_object('tomorrow');
|
||||||
|
$cron = CronExpression::factory('@daily');
|
||||||
|
$schedule = new ActionScheduler_CronSchedule(as_get_datetime_object(), $cron);
|
||||||
|
$this->assertEquals( $time, $schedule->next() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_next() {
|
||||||
|
$time = as_get_datetime_object('2013-06-14');
|
||||||
|
$cron = CronExpression::factory('@daily');
|
||||||
|
$schedule = new ActionScheduler_CronSchedule($time, $cron);
|
||||||
|
$this->assertEquals( as_get_datetime_object('tomorrow'), $schedule->next( as_get_datetime_object() ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_is_recurring() {
|
||||||
|
$schedule = new ActionScheduler_CronSchedule(as_get_datetime_object('2013-06-14'), CronExpression::factory('@daily'));
|
||||||
|
$this->assertTrue( $schedule->is_recurring() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_cron_format() {
|
||||||
|
$time = as_get_datetime_object('2014-01-01');
|
||||||
|
$cron = CronExpression::factory('0 0 10 10 *');
|
||||||
|
$schedule = new ActionScheduler_CronSchedule($time, $cron);
|
||||||
|
$this->assertEquals( as_get_datetime_object('2014-10-10'), $schedule->next() );
|
||||||
|
|
||||||
|
$cron = CronExpression::factory('0 0 L 1/2 *');
|
||||||
|
$schedule = new ActionScheduler_CronSchedule($time, $cron);
|
||||||
|
$this->assertEquals( as_get_datetime_object('2014-01-31'), $schedule->next() );
|
||||||
|
$this->assertEquals( as_get_datetime_object('2014-07-31'), $schedule->next( as_get_datetime_object('2014-06-01') ) );
|
||||||
|
$this->assertEquals( as_get_datetime_object('2028-11-30'), $schedule->next( as_get_datetime_object('2028-11-01') ) );
|
||||||
|
|
||||||
|
$cron = CronExpression::factory('30 14 * * MON#3 *');
|
||||||
|
$schedule = new ActionScheduler_CronSchedule($time, $cron);
|
||||||
|
$this->assertEquals( as_get_datetime_object('2014-01-20 14:30:00'), $schedule->next() );
|
||||||
|
$this->assertEquals( as_get_datetime_object('2014-05-19 14:30:00'), $schedule->next( as_get_datetime_object('2014-05-01') ) );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,28 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_IntervalSchedule_Test
|
||||||
|
* @group schedules
|
||||||
|
*/
|
||||||
|
class ActionScheduler_IntervalSchedule_Test extends ActionScheduler_UnitTestCase {
|
||||||
|
public function test_creation() {
|
||||||
|
$time = as_get_datetime_object();
|
||||||
|
$schedule = new ActionScheduler_IntervalSchedule($time, HOUR_IN_SECONDS);
|
||||||
|
$this->assertEquals( $time, $schedule->next() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_next() {
|
||||||
|
$now = time();
|
||||||
|
$start = $now - 30;
|
||||||
|
$schedule = new ActionScheduler_IntervalSchedule( as_get_datetime_object("@$start"), MINUTE_IN_SECONDS );
|
||||||
|
$this->assertEquals( $start, $schedule->next()->getTimestamp() );
|
||||||
|
$this->assertEquals( $now + MINUTE_IN_SECONDS, $schedule->next(as_get_datetime_object())->getTimestamp() );
|
||||||
|
$this->assertEquals( $start, $schedule->next(as_get_datetime_object("@$start"))->getTimestamp() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_is_recurring() {
|
||||||
|
$start = time() - 30;
|
||||||
|
$schedule = new ActionScheduler_IntervalSchedule( as_get_datetime_object("@$start"), MINUTE_IN_SECONDS );
|
||||||
|
$this->assertTrue( $schedule->is_recurring() );
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_NullSchedule_Test
|
||||||
|
* @group schedules
|
||||||
|
*/
|
||||||
|
class ActionScheduler_NullSchedule_Test extends ActionScheduler_UnitTestCase {
|
||||||
|
public function test_null_schedule() {
|
||||||
|
$schedule = new ActionScheduler_NullSchedule();
|
||||||
|
$this->assertNull( $schedule->next() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_is_recurring() {
|
||||||
|
$schedule = new ActionScheduler_NullSchedule();
|
||||||
|
$this->assertFalse( $schedule->is_recurring() );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,37 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_SimpleSchedule_Test
|
||||||
|
* @group schedules
|
||||||
|
*/
|
||||||
|
class ActionScheduler_SimpleSchedule_Test extends ActionScheduler_UnitTestCase {
|
||||||
|
public function test_creation() {
|
||||||
|
$time = as_get_datetime_object();
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$this->assertEquals( $time, $schedule->next() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_past_date() {
|
||||||
|
$time = as_get_datetime_object('-1 day');
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$this->assertEquals( $time, $schedule->next() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_future_date() {
|
||||||
|
$time = as_get_datetime_object('+1 day');
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$this->assertEquals( $time, $schedule->next() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_grace_period_for_next() {
|
||||||
|
$time = as_get_datetime_object('3 seconds ago');
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule($time);
|
||||||
|
$this->assertEquals( $time, $schedule->next() );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_is_recurring() {
|
||||||
|
$schedule = new ActionScheduler_SimpleSchedule(as_get_datetime_object('+1 day'));
|
||||||
|
$this->assertFalse( $schedule->is_recurring() );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,43 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class ActionScheduler_Versions_Test
|
||||||
|
*/
|
||||||
|
class ActionScheduler_Versions_Test extends ActionScheduler_UnitTestCase {
|
||||||
|
public function test_register_version() {
|
||||||
|
$versions = new ActionScheduler_Versions();
|
||||||
|
$versions->register('1.0-dev', 'callback_1_dot_0_dev');
|
||||||
|
$versions->register('1.0', 'callback_1_dot_0');
|
||||||
|
|
||||||
|
$registered = $versions->get_versions();
|
||||||
|
|
||||||
|
$this->assertArrayHasKey( '1.0-dev', $registered );
|
||||||
|
$this->assertArrayHasKey( '1.0', $registered );
|
||||||
|
$this->assertCount( 2, $registered );
|
||||||
|
|
||||||
|
$this->assertEquals( 'callback_1_dot_0_dev', $registered['1.0-dev'] );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_duplicate_version() {
|
||||||
|
$versions = new ActionScheduler_Versions();
|
||||||
|
$versions->register('1.0', 'callback_1_dot_0_a');
|
||||||
|
$versions->register('1.0', 'callback_1_dot_0_b');
|
||||||
|
|
||||||
|
$registered = $versions->get_versions();
|
||||||
|
|
||||||
|
$this->assertArrayHasKey( '1.0', $registered );
|
||||||
|
$this->assertCount( 1, $registered );
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_latest_version() {
|
||||||
|
$versions = new ActionScheduler_Versions();
|
||||||
|
$this->assertEquals('__return_null', $versions->latest_version_callback() );
|
||||||
|
$versions->register('1.2', 'callback_1_dot_2');
|
||||||
|
$versions->register('1.3', 'callback_1_dot_3');
|
||||||
|
$versions->register('1.0', 'callback_1_dot_0');
|
||||||
|
|
||||||
|
$this->assertEquals( '1.3', $versions->latest_version() );
|
||||||
|
$this->assertEquals( 'callback_1_dot_3', $versions->latest_version_callback() );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,38 @@
|
||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
# WordPress test setup script for Travis CI
|
||||||
|
#
|
||||||
|
# Author: Benjamin J. Balter ( ben@balter.com | ben.balter.com )
|
||||||
|
# License: GPL3
|
||||||
|
|
||||||
|
export WP_CORE_DIR=/tmp/wordpress
|
||||||
|
export WP_TESTS_DIR=/tmp/wordpress-tests/tests/phpunit
|
||||||
|
|
||||||
|
if [[ "$1" = "5.6" || "$1" > "5.6" ]]
|
||||||
|
then
|
||||||
|
wget -c https://phar.phpunit.de/phpunit-5.7.phar
|
||||||
|
chmod +x phpunit-5.7.phar
|
||||||
|
mv phpunit-5.7.phar `which phpunit`
|
||||||
|
fi
|
||||||
|
|
||||||
|
plugin_slug=$(basename $(pwd))
|
||||||
|
plugin_dir=$WP_CORE_DIR/wp-content/plugins/$plugin_slug
|
||||||
|
|
||||||
|
# Init database
|
||||||
|
mysql -e 'CREATE DATABASE wordpress_test;' -uroot
|
||||||
|
|
||||||
|
# Grab specified version of WordPress from github
|
||||||
|
wget -nv -O /tmp/wordpress.tar.gz https://github.com/WordPress/WordPress/tarball/$WP_VERSION
|
||||||
|
mkdir -p $WP_CORE_DIR
|
||||||
|
tar --strip-components=1 -zxmf /tmp/wordpress.tar.gz -C $WP_CORE_DIR
|
||||||
|
|
||||||
|
# Grab testing framework
|
||||||
|
svn co --quiet https://develop.svn.wordpress.org/tags/$WP_VERSION/ /tmp/wordpress-tests
|
||||||
|
|
||||||
|
# Put various components in proper folders
|
||||||
|
cp tests/travis/wp-tests-config.php $WP_TESTS_DIR/wp-tests-config.php
|
||||||
|
|
||||||
|
cd ..
|
||||||
|
mv $plugin_slug $plugin_dir
|
||||||
|
|
||||||
|
cd $plugin_dir
|
|
@ -0,0 +1,38 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
/* Path to the WordPress codebase you'd like to test. Add a backslash in the end. */
|
||||||
|
define( 'ABSPATH', getenv( 'WP_CORE_DIR' ) . '/' );
|
||||||
|
|
||||||
|
// Test with multisite enabled
|
||||||
|
define( 'WP_TESTS_MULTISITE', (bool) getenv( 'WP_MULTISITE' ) );
|
||||||
|
|
||||||
|
// Force known bugs
|
||||||
|
// define( 'WP_TESTS_FORCE_KNOWN_BUGS', true );
|
||||||
|
|
||||||
|
// Test with WordPress debug mode on
|
||||||
|
define( 'WP_DEBUG', true );
|
||||||
|
|
||||||
|
// ** MySQL settings ** //
|
||||||
|
|
||||||
|
// This configuration file will be used by the copy of WordPress being tested.
|
||||||
|
// wordpress/wp-config.php will be ignored.
|
||||||
|
|
||||||
|
// WARNING WARNING WARNING!
|
||||||
|
// These tests will DROP ALL TABLES in the database with the prefix named below.
|
||||||
|
// DO NOT use a production database or one that is shared with something else.
|
||||||
|
|
||||||
|
define( 'DB_NAME', 'wordpress_test' );
|
||||||
|
define( 'DB_USER', 'root' );
|
||||||
|
define( 'DB_PASSWORD', '' );
|
||||||
|
define( 'DB_HOST', 'localhost' );
|
||||||
|
define( 'DB_CHARSET', 'utf8' );
|
||||||
|
define( 'DB_COLLATE', '' );
|
||||||
|
|
||||||
|
define( 'WP_TESTS_DOMAIN', 'example.org' );
|
||||||
|
define( 'WP_TESTS_EMAIL', 'admin@example.org' );
|
||||||
|
define( 'WP_TESTS_TITLE', 'Test Blog' );
|
||||||
|
|
||||||
|
define( 'WP_PHP_BINARY', 'php' );
|
||||||
|
|
||||||
|
define( 'WPLANG', '' );
|
||||||
|
$table_prefix = 'wptests_';
|
Loading…
Reference in New Issue