| Current Path : /home/x/b/o/xbodynamge/namtation/wp-content/ |
| Current File : /home/x/b/o/xbodynamge/namtation/wp-content/WP_CLI.tar |
Action_Command.php 0000666 00000020224 15114242262 0010133 0 ustar 00 <?php
namespace Action_Scheduler\WP_CLI;
/**
* Action command for Action Scheduler.
*/
class Action_Command extends \WP_CLI_Command {
/**
* Cancel the next occurrence or all occurrences of a scheduled action.
*
* ## OPTIONS
*
* [<hook>]
* : Name of the action hook.
*
* [--group=<group>]
* : The group the job is assigned to.
*
* [--args=<args>]
* : JSON object of arguments assigned to the job.
* ---
* default: []
* ---
*
* [--all]
* : Cancel all occurrences of a scheduled action.
*
* @param array $args Positional arguments.
* @param array $assoc_args Keyed arguments.
* @return void
*/
public function cancel( array $args, array $assoc_args ) {
require_once 'Action/Cancel_Command.php';
$command = new Action\Cancel_Command( $args, $assoc_args );
$command->execute();
}
/**
* Creates a new scheduled action.
*
* ## OPTIONS
*
* <hook>
* : Name of the action hook.
*
* <start>
* : A unix timestamp representing the date you want the action to start. Also 'async' or 'now' to enqueue an async action.
*
* [--args=<args>]
* : JSON object of arguments to pass to callbacks when the hook triggers.
* ---
* default: []
* ---
*
* [--cron=<cron>]
* : A cron-like schedule string (https://crontab.guru/).
* ---
* default: ''
* ---
*
* [--group=<group>]
* : The group to assign this job to.
* ---
* default: ''
* ---
*
* [--interval=<interval>]
* : Number of seconds to wait between runs.
* ---
* default: 0
* ---
*
* ## EXAMPLES
*
* wp action-scheduler action create hook_async async
* wp action-scheduler action create hook_single 1627147598
* wp action-scheduler action create hook_recurring 1627148188 --interval=5
* wp action-scheduler action create hook_cron 1627147655 --cron='5 4 * * *'
*
* @param array $args Positional arguments.
* @param array $assoc_args Keyed arguments.
* @return void
*/
public function create( array $args, array $assoc_args ) {
require_once 'Action/Create_Command.php';
$command = new Action\Create_Command( $args, $assoc_args );
$command->execute();
}
/**
* Delete existing scheduled action(s).
*
* ## OPTIONS
*
* <id>...
* : One or more IDs of actions to delete.
* ---
* default: 0
* ---
*
* ## EXAMPLES
*
* # Delete the action with id 100
* $ wp action-scheduler action delete 100
*
* # Delete the actions with ids 100 and 200
* $ wp action-scheduler action delete 100 200
*
* # Delete the first five pending actions in 'action-scheduler' group
* $ wp action-scheduler action delete $( wp action-scheduler action list --status=pending --group=action-scheduler --format=ids )
*
* @param array $args Positional arguments.
* @param array $assoc_args Keyed arguments.
* @return void
*/
public function delete( array $args, array $assoc_args ) {
require_once 'Action/Delete_Command.php';
$command = new Action\Delete_Command( $args, $assoc_args );
$command->execute();
}
/**
* Generates some scheduled actions.
*
* ## OPTIONS
*
* <hook>
* : Name of the action hook.
*
* <start>
* : The Unix timestamp representing the date you want the action to start.
*
* [--count=<count>]
* : Number of actions to create.
* ---
* default: 1
* ---
*
* [--interval=<interval>]
* : Number of seconds to wait between runs.
* ---
* default: 0
* ---
*
* [--args=<args>]
* : JSON object of arguments to pass to callbacks when the hook triggers.
* ---
* default: []
* ---
*
* [--group=<group>]
* : The group to assign this job to.
* ---
* default: ''
* ---
*
* ## EXAMPLES
*
* wp action-scheduler action generate test_multiple 1627147598 --count=5 --interval=5
*
* @param array $args Positional arguments.
* @param array $assoc_args Keyed arguments.
* @return void
*/
public function generate( array $args, array $assoc_args ) {
require_once 'Action/Generate_Command.php';
$command = new Action\Generate_Command( $args, $assoc_args );
$command->execute();
}
/**
* Get details about a scheduled action.
*
* ## OPTIONS
*
* <id>
* : The ID of the action to get.
* ---
* default: 0
* ---
*
* [--field=<field>]
* : Instead of returning the whole action, returns the value of a single field.
*
* [--fields=<fields>]
* : Limit the output to specific fields (comma-separated). Defaults to all fields.
*
* [--format=<format>]
* : Render output in a particular format.
* ---
* default: table
* options:
* - table
* - csv
* - json
* - yaml
* ---
*
* @param array $args Positional arguments.
* @param array $assoc_args Keyed arguments.
* @return void
*/
public function get( array $args, array $assoc_args ) {
require_once 'Action/Get_Command.php';
$command = new Action\Get_Command( $args, $assoc_args );
$command->execute();
}
/**
* Get a list of scheduled actions.
*
* Display actions based on all arguments supported by
* [as_get_scheduled_actions()](https://actionscheduler.org/api/#function-reference--as_get_scheduled_actions).
*
* ## OPTIONS
*
* [--<field>=<value>]
* : One or more arguments to pass to as_get_scheduled_actions().
*
* [--field=<field>]
* : Prints the value of a single property for each action.
*
* [--fields=<fields>]
* : Limit the output to specific object properties.
*
* [--format=<format>]
* : Render output in a particular format.
* ---
* default: table
* options:
* - table
* - csv
* - ids
* - json
* - count
* - yaml
* ---
*
* ## AVAILABLE FIELDS
*
* These fields will be displayed by default for each action:
*
* * id
* * hook
* * status
* * group
* * recurring
* * scheduled_date
*
* These fields are optionally available:
*
* * args
* * log_entries
*
* @param array $args Positional arguments.
* @param array $assoc_args Keyed arguments.
* @return void
*
* @subcommand list
*/
public function subcommand_list( array $args, array $assoc_args ) {
require_once 'Action/List_Command.php';
$command = new Action\List_Command( $args, $assoc_args );
$command->execute();
}
/**
* Get logs for a scheduled action.
*
* ## OPTIONS
*
* <id>
* : The ID of the action to get.
* ---
* default: 0
* ---
*
* @param array $args Positional arguments.
* @return void
*/
public function logs( array $args ) {
$command = sprintf( 'action-scheduler action get %d --field=log_entries', $args[0] );
WP_CLI::runcommand( $command );
}
/**
* Get the ID or timestamp of the next scheduled action.
*
* ## OPTIONS
*
* <hook>
* : The hook of the next scheduled action.
*
* [--args=<args>]
* : JSON object of arguments to search for next scheduled action.
* ---
* default: []
* ---
*
* [--group=<group>]
* : The group to which the next scheduled action is assigned.
* ---
* default: ''
* ---
*
* [--raw]
* : Display the raw output of as_next_scheduled_action() (timestamp or boolean).
*
* @param array $args Positional arguments.
* @param array $assoc_args Keyed arguments.
* @return void
*/
public function next( array $args, array $assoc_args ) {
require_once 'Action/Next_Command.php';
$command = new Action\Next_Command( $args, $assoc_args );
$command->execute();
}
/**
* Run existing scheduled action(s).
*
* ## OPTIONS
*
* <id>...
* : One or more IDs of actions to run.
* ---
* default: 0
* ---
*
* ## EXAMPLES
*
* # Run the action with id 100
* $ wp action-scheduler action run 100
*
* # Run the actions with ids 100 and 200
* $ wp action-scheduler action run 100 200
*
* # Run the first five pending actions in 'action-scheduler' group
* $ wp action-scheduler action run $( wp action-scheduler action list --status=pending --group=action-scheduler --format=ids )
*
* @param array $args Positional arguments.
* @param array $assoc_args Keyed arguments.
* @return void
*/
public function run( array $args, array $assoc_args ) {
require_once 'Action/Run_Command.php';
$command = new Action\Run_Command( $args, $assoc_args );
$command->execute();
}
}
ActionScheduler_WPCLI_Scheduler_command.php 0000666 00000015307 15114242262 0014774 0 ustar 00 <?php
/**
* Commands for Action Scheduler.
*/
class ActionScheduler_WPCLI_Scheduler_command extends WP_CLI_Command {
/**
* Force tables schema creation for Action Scheduler
*
* ## OPTIONS
*
* @param array $args Positional arguments.
* @param array $assoc_args Keyed arguments.
*
* @subcommand fix-schema
*/
public function fix_schema( $args, $assoc_args ) {
$schema_classes = array( ActionScheduler_LoggerSchema::class, ActionScheduler_StoreSchema::class );
foreach ( $schema_classes as $classname ) {
if ( is_subclass_of( $classname, ActionScheduler_Abstract_Schema::class ) ) {
$obj = new $classname();
$obj->init();
$obj->register_tables( true );
WP_CLI::success(
sprintf(
/* translators: %s refers to the schema name*/
__( 'Registered schema for %s', 'action-scheduler' ),
$classname
)
);
}
}
}
/**
* 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.
*
* [--exclude-groups=<groups>]
* : Run actions from all groups except the specified group(s). Define multiple groups as a comma separated string (without spaces), e.g. '--group_a,group_b'. This option is ignored when `--group` is used.
*
* [--free-memory-on=<count>]
* : The number of actions to process between freeing memory. 0 disables freeing memory. Default 50.
*
* [--pause=<seconds>]
* : The number of seconds to pause when freeing memory. Default no pause.
*
* [--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.
*
* @subcommand run
*/
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', '' );
$exclude_groups = \WP_CLI\Utils\get_flag_value( $assoc_args, 'exclude-groups', '' );
$free_on = \WP_CLI\Utils\get_flag_value( $assoc_args, 'free-memory-on', 50 );
$sleep = \WP_CLI\Utils\get_flag_value( $assoc_args, 'pause', 0 );
$force = \WP_CLI\Utils\get_flag_value( $assoc_args, 'force', false );
ActionScheduler_DataController::set_free_ticks( $free_on );
ActionScheduler_DataController::set_sleep_time( $sleep );
$batches_completed = 0;
$actions_completed = 0;
$unlimited = 0 === $batches;
if ( is_callable( array( ActionScheduler::store(), 'set_claim_filter' ) ) ) {
$exclude_groups = $this->parse_comma_separated_string( $exclude_groups );
if ( ! empty( $exclude_groups ) ) {
ActionScheduler::store()->set_claim_filter( 'exclude-groups', $exclude_groups );
}
}
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 );
}
/**
* Converts a string of comma-separated values into an array of those same values.
*
* @param string $string The string of one or more comma separated values.
*
* @return array
*/
private function parse_comma_separated_string( $string ): array {
return array_filter( str_getcsv( $string ) );
}
/**
* Print WP CLI message about how many actions are about to be processed.
*
* @param int $total Number of actions found.
*/
protected function print_total_actions( $total ) {
WP_CLI::log(
sprintf(
/* translators: %d refers to how many scheduled tasks were found to run */
_n( 'Found %d scheduled task', 'Found %d scheduled tasks', $total, 'action-scheduler' ),
$total
)
);
}
/**
* Print WP CLI message about how many batches of actions were processed.
*
* @param int $batches_completed Number of completed batches.
*/
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' ),
$batches_completed
)
);
}
/**
* Convert an exception into a WP CLI error.
*
* @param Exception $e The error object.
*
* @throws \WP_CLI\ExitException Under some conditions WP CLI may throw an exception.
*/
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.
*
* @param int $actions_completed Number of completed actions.
*/
protected function print_success( $actions_completed ) {
WP_CLI::success(
sprintf(
/* translators: %d refers to the total number of tasks completed */
_n( '%d scheduled task completed.', '%d scheduled tasks completed.', $actions_completed, 'action-scheduler' ),
$actions_completed
)
);
}
}
Migration_Command.php 0000666 00000011670 15114242262 0010654 0 ustar 00 <?php
namespace Action_Scheduler\WP_CLI;
use Action_Scheduler\Migration\Config;
use Action_Scheduler\Migration\Runner;
use Action_Scheduler\Migration\Scheduler;
use Action_Scheduler\Migration\Controller;
use WP_CLI;
use WP_CLI_Command;
/**
* Class Migration_Command
*
* @package Action_Scheduler\WP_CLI
*
* @since 3.0.0
*
* @codeCoverageIgnore
*/
class Migration_Command extends WP_CLI_Command {
/**
* Number of actions migrated.
*
* @var int
*/
private $total_processed = 0;
/**
* Register the command with WP-CLI
*/
public function register() {
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command(
'action-scheduler migrate',
array( $this, 'migrate' ),
array(
'shortdesc' => 'Migrates actions to the DB tables store',
'synopsis' => array(
array(
'type' => 'assoc',
'name' => 'batch-size',
'optional' => true,
'default' => 100,
'description' => 'The number of actions to process in each batch',
),
array(
'type' => 'assoc',
'name' => 'free-memory-on',
'optional' => true,
'default' => 50,
'description' => 'The number of actions to process between freeing memory. 0 disables freeing memory',
),
array(
'type' => 'assoc',
'name' => 'pause',
'optional' => true,
'default' => 0,
'description' => 'The number of seconds to pause when freeing memory',
),
array(
'type' => 'flag',
'name' => 'dry-run',
'optional' => true,
'description' => 'Reports on the actions that would have been migrated, but does not change any data',
),
),
)
);
}
/**
* Process the data migration.
*
* @param array $positional_args Required for WP CLI. Not used in migration.
* @param array $assoc_args Optional arguments.
*
* @return void
*/
public function migrate( $positional_args, $assoc_args ) {
$this->init_logging();
$config = $this->get_migration_config( $assoc_args );
$runner = new Runner( $config );
$runner->init_destination();
$batch_size = isset( $assoc_args['batch-size'] ) ? (int) $assoc_args['batch-size'] : 100;
$free_on = isset( $assoc_args['free-memory-on'] ) ? (int) $assoc_args['free-memory-on'] : 50;
$sleep = isset( $assoc_args['pause'] ) ? (int) $assoc_args['pause'] : 0;
\ActionScheduler_DataController::set_free_ticks( $free_on );
\ActionScheduler_DataController::set_sleep_time( $sleep );
do {
$actions_processed = $runner->run( $batch_size );
$this->total_processed += $actions_processed;
} while ( $actions_processed > 0 );
if ( ! $config->get_dry_run() ) {
// let the scheduler know that there's nothing left to do.
$scheduler = new Scheduler();
$scheduler->mark_complete();
}
WP_CLI::success( sprintf( '%s complete. %d actions processed.', $config->get_dry_run() ? 'Dry run' : 'Migration', $this->total_processed ) );
}
/**
* Build the config object used to create the Runner
*
* @param array $args Optional arguments.
*
* @return ActionScheduler\Migration\Config
*/
private function get_migration_config( $args ) {
$args = wp_parse_args(
$args,
array(
'dry-run' => false,
)
);
$config = Controller::instance()->get_migration_config_object();
$config->set_dry_run( ! empty( $args['dry-run'] ) );
return $config;
}
/**
* Hook command line logging into migration actions.
*/
private function init_logging() {
add_action(
'action_scheduler/migrate_action_dry_run',
function ( $action_id ) {
WP_CLI::debug( sprintf( 'Dry-run: migrated action %d', $action_id ) );
}
);
add_action(
'action_scheduler/no_action_to_migrate',
function ( $action_id ) {
WP_CLI::debug( sprintf( 'No action found to migrate for ID %d', $action_id ) );
}
);
add_action(
'action_scheduler/migrate_action_failed',
function ( $action_id ) {
WP_CLI::warning( sprintf( 'Failed migrating action with ID %d', $action_id ) );
}
);
add_action(
'action_scheduler/migrate_action_incomplete',
function ( $source_id, $destination_id ) {
WP_CLI::warning( sprintf( 'Unable to remove source action with ID %d after migrating to new ID %d', $source_id, $destination_id ) );
},
10,
2
);
add_action(
'action_scheduler/migrated_action',
function ( $source_id, $destination_id ) {
WP_CLI::debug( sprintf( 'Migrated source action with ID %d to new store with ID %d', $source_id, $destination_id ) );
},
10,
2
);
add_action(
'action_scheduler/migration_batch_starting',
function ( $batch ) {
WP_CLI::debug( 'Beginning migration of batch: ' . print_r( $batch, true ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
}
);
add_action(
'action_scheduler/migration_batch_complete',
function ( $batch ) {
WP_CLI::log( sprintf( 'Completed migration of %d actions', count( $batch ) ) );
}
);
}
}
ActionScheduler_WPCLI_Clean_Command.php 0000666 00000007363 15114242262 0014043 0 ustar 00 <?php
/**
* Commands for Action Scheduler.
*/
class ActionScheduler_WPCLI_Clean_Command extends WP_CLI_Command {
/**
* Run the Action Scheduler Queue Cleaner
*
* ## OPTIONS
*
* [--batch-size=<size>]
* : The maximum number of actions to delete per batch. Defaults to 20.
*
* [--batches=<size>]
* : Limit execution to a number of batches. Defaults to 0, meaning batches will continue all eligible actions are deleted.
*
* [--status=<status>]
* : Only clean actions with the specified status. Defaults to Canceled, Completed. Define multiple statuses as a comma separated string (without spaces), e.g. `--status=complete,failed,canceled`
*
* [--before=<datestring>]
* : Only delete actions with scheduled date older than this. Defaults to 31 days. e.g `--before='7 days ago'`, `--before='02-Feb-2020 20:20:20'`
*
* [--pause=<seconds>]
* : The number of seconds to pause between batches. Default no pause.
*
* @param array $args Positional arguments.
* @param array $assoc_args Keyed arguments.
* @throws \WP_CLI\ExitException When an error occurs.
*
* @subcommand clean
*/
public function clean( $args, $assoc_args ) {
// Handle passed arguments.
$batch = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batch-size', 20 ) );
$batches = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batches', 0 ) );
$status = explode( ',', WP_CLI\Utils\get_flag_value( $assoc_args, 'status', '' ) );
$status = array_filter( array_map( 'trim', $status ) );
$before = \WP_CLI\Utils\get_flag_value( $assoc_args, 'before', '' );
$sleep = \WP_CLI\Utils\get_flag_value( $assoc_args, 'pause', 0 );
$batches_completed = 0;
$actions_deleted = 0;
$unlimited = 0 === $batches;
try {
$lifespan = as_get_datetime_object( $before );
} catch ( Exception $e ) {
$lifespan = null;
}
try {
// Custom queue cleaner instance.
$cleaner = new ActionScheduler_QueueCleaner( null, $batch );
// Clean actions for as long as possible.
while ( $unlimited || $batches_completed < $batches ) {
if ( $sleep && $batches_completed > 0 ) {
sleep( $sleep );
}
$deleted = count( $cleaner->clean_actions( $status, $lifespan, null, 'CLI' ) );
if ( $deleted <= 0 ) {
break;
}
$actions_deleted += $deleted;
$batches_completed++;
$this->print_success( $deleted );
}
} catch ( Exception $e ) {
$this->print_error( $e );
}
$this->print_total_batches( $batches_completed );
if ( $batches_completed > 1 ) {
$this->print_success( $actions_deleted );
}
}
/**
* Print WP CLI message about how many batches of actions were processed.
*
* @param int $batches_processed Number of batches processed.
*/
protected function print_total_batches( int $batches_processed ) {
WP_CLI::log(
sprintf(
/* translators: %d refers to the total number of batches processed */
_n( '%d batch processed.', '%d batches processed.', $batches_processed, 'action-scheduler' ),
$batches_processed
)
);
}
/**
* Convert an exception into a WP CLI error.
*
* @param Exception $e The error object.
*/
protected function print_error( Exception $e ) {
WP_CLI::error(
sprintf(
/* translators: %s refers to the exception error message */
__( 'There was an error deleting an action: %s', 'action-scheduler' ),
$e->getMessage()
)
);
}
/**
* Print a success message with the number of completed actions.
*
* @param int $actions_deleted Number of deleted actions.
*/
protected function print_success( int $actions_deleted ) {
WP_CLI::success(
sprintf(
/* translators: %d refers to the total number of actions deleted */
_n( '%d action deleted.', '%d actions deleted.', $actions_deleted, 'action-scheduler' ),
$actions_deleted
)
);
}
}
System_Command.php 0000666 00000016135 15114242262 0010210 0 ustar 00 <?php
namespace Action_Scheduler\WP_CLI;
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaping output is not necessary in WP CLI.
use ActionScheduler_SystemInformation;
use WP_CLI;
use function \WP_CLI\Utils\get_flag_value;
/**
* System info WP-CLI commands for Action Scheduler.
*/
class System_Command {
/**
* Data store for querying actions
*
* @var ActionScheduler_Store
*/
protected $store;
/**
* Construct.
*/
public function __construct() {
$this->store = \ActionScheduler::store();
}
/**
* Print in-use data store class.
*
* @param array $args Positional args.
* @param array $assoc_args Keyed args.
* @return void
*
* @subcommand data-store
*/
public function datastore( array $args, array $assoc_args ) {
echo $this->get_current_datastore();
}
/**
* Print in-use runner class.
*
* @param array $args Positional args.
* @param array $assoc_args Keyed args.
* @return void
*/
public function runner( array $args, array $assoc_args ) {
echo $this->get_current_runner();
}
/**
* Get system status.
*
* @param array $args Positional args.
* @param array $assoc_args Keyed args.
* @return void
*/
public function status( array $args, array $assoc_args ) {
/**
* Get runner status.
*
* @link https://github.com/woocommerce/action-scheduler-disable-default-runner
*/
$runner_enabled = has_action( 'action_scheduler_run_queue', array( \ActionScheduler::runner(), 'run' ) );
\WP_CLI::line( sprintf( 'Data store: %s', $this->get_current_datastore() ) );
\WP_CLI::line( sprintf( 'Runner: %s%s', $this->get_current_runner(), ( $runner_enabled ? '' : ' (disabled)' ) ) );
\WP_CLI::line( sprintf( 'Version: %s', $this->get_latest_version() ) );
$rows = array();
$action_counts = $this->store->action_counts();
$oldest_and_newest = $this->get_oldest_and_newest( array_keys( $action_counts ) );
foreach ( $action_counts as $status => $count ) {
$rows[] = array(
'status' => $status,
'count' => $count,
'oldest' => $oldest_and_newest[ $status ]['oldest'],
'newest' => $oldest_and_newest[ $status ]['newest'],
);
}
$formatter = new \WP_CLI\Formatter( $assoc_args, array( 'status', 'count', 'oldest', 'newest' ) );
$formatter->display_items( $rows );
}
/**
* Display the active version, or all registered versions.
*
* ## OPTIONS
*
* [--all]
* : List all registered versions.
*
* @param array $args Positional args.
* @param array $assoc_args Keyed args.
* @return void
*/
public function version( array $args, array $assoc_args ) {
$all = (bool) get_flag_value( $assoc_args, 'all' );
$latest = $this->get_latest_version();
if ( ! $all ) {
echo $latest;
\WP_CLI::halt( 0 );
}
$instance = \ActionScheduler_Versions::instance();
$versions = $instance->get_versions();
$rows = array();
foreach ( $versions as $version => $callback ) {
$active = $version === $latest;
$rows[ $version ] = array(
'version' => $version,
'callback' => $callback,
'active' => $active ? 'yes' : 'no',
);
}
uksort( $rows, 'version_compare' );
$formatter = new \WP_CLI\Formatter( $assoc_args, array( 'version', 'callback', 'active' ) );
$formatter->display_items( $rows );
}
/**
* Display the current source, or all registered sources.
*
* ## OPTIONS
*
* [--all]
* : List all registered sources.
*
* [--fullpath]
* : List full path of source(s).
*
* @param array $args Positional args.
* @param array $assoc_args Keyed args.
* @uses ActionScheduler_SystemInformation::active_source_path()
* @uses \WP_CLI\Formatter::display_items()
* @uses $this->get_latest_version()
* @return void
*/
public function source( array $args, array $assoc_args ) {
$all = (bool) get_flag_value( $assoc_args, 'all' );
$fullpath = (bool) get_flag_value( $assoc_args, 'fullpath' );
$source = ActionScheduler_SystemInformation::active_source_path();
$path = $source;
if ( ! $fullpath ) {
$path = str_replace( ABSPATH, '', $path );
}
if ( ! $all ) {
echo $path;
\WP_CLI::halt( 0 );
}
$sources = ActionScheduler_SystemInformation::get_sources();
if ( empty( $sources ) ) {
WP_CLI::log( __( 'Detailed information about registered sources is not currently available.', 'action-scheduler' ) );
return;
}
$rows = array();
foreach ( $sources as $check_source => $version ) {
$active = dirname( $check_source ) === $source;
$path = $check_source;
if ( ! $fullpath ) {
$path = str_replace( ABSPATH, '', $path );
}
$rows[ $check_source ] = array(
'source' => $path,
'version' => $version,
'active' => $active ? 'yes' : 'no',
);
}
ksort( $rows );
\WP_CLI::log( PHP_EOL . 'Please note there can only be one unique registered instance of Action Scheduler per ' . PHP_EOL . 'version number, so this list may not include all the currently present copies of ' . PHP_EOL . 'Action Scheduler.' . PHP_EOL );
$formatter = new \WP_CLI\Formatter( $assoc_args, array( 'source', 'version', 'active' ) );
$formatter->display_items( $rows );
}
/**
* Get current data store.
*
* @return string
*/
protected function get_current_datastore() {
return get_class( $this->store );
}
/**
* Get latest version.
*
* @param null|\ActionScheduler_Versions $instance Versions.
* @return string
*/
protected function get_latest_version( $instance = null ) {
if ( is_null( $instance ) ) {
$instance = \ActionScheduler_Versions::instance();
}
return $instance->latest_version();
}
/**
* Get current runner.
*
* @return string
*/
protected function get_current_runner() {
return get_class( \ActionScheduler::runner() );
}
/**
* Get oldest and newest scheduled dates for a given set of statuses.
*
* @param array $status_keys Set of statuses to find oldest & newest action for.
* @return array
*/
protected function get_oldest_and_newest( $status_keys ) {
$oldest_and_newest = array();
foreach ( $status_keys as $status ) {
$oldest_and_newest[ $status ] = array(
'oldest' => '–',
'newest' => '–',
);
if ( 'in-progress' === $status ) {
continue;
}
$oldest_and_newest[ $status ]['oldest'] = $this->get_action_status_date( $status, 'oldest' );
$oldest_and_newest[ $status ]['newest'] = $this->get_action_status_date( $status, 'newest' );
}
return $oldest_and_newest;
}
/**
* Get oldest or newest scheduled date for a given status.
*
* @param string $status Action status label/name string.
* @param string $date_type Oldest or Newest.
* @return string
*/
protected function get_action_status_date( $status, $date_type = 'oldest' ) {
$order = 'oldest' === $date_type ? 'ASC' : 'DESC';
$args = array(
'claimed' => false,
'status' => $status,
'per_page' => 1,
'order' => $order,
);
$action = $this->store->query_actions( $args );
if ( ! empty( $action ) ) {
$date_object = $this->store->get_date( $action[0] );
$action_date = $date_object->format( 'Y-m-d H:i:s O' );
} else {
$action_date = '–';
}
return $action_date;
}
}
Action/Create_Command.php 0000666 00000010476 15114242262 0011346 0 ustar 00 <?php
namespace Action_Scheduler\WP_CLI\Action;
/**
* WP-CLI command: action-scheduler action create
*/
class Create_Command extends \ActionScheduler_WPCLI_Command {
const ASYNC_OPTS = array( 'async', 0 );
/**
* Execute command.
*
* @return void
*/
public function execute() {
$hook = $this->args[0];
$schedule_start = $this->args[1];
$callback_args = get_flag_value( $this->assoc_args, 'args', array() );
$group = get_flag_value( $this->assoc_args, 'group', '' );
$interval = absint( get_flag_value( $this->assoc_args, 'interval', 0 ) );
$cron = get_flag_value( $this->assoc_args, 'cron', '' );
$unique = get_flag_value( $this->assoc_args, 'unique', false );
$priority = absint( get_flag_value( $this->assoc_args, 'priority', 10 ) );
if ( ! empty( $callback_args ) ) {
$callback_args = json_decode( $callback_args, true );
}
$function_args = array(
'start' => $schedule_start,
'cron' => $cron,
'interval' => $interval,
'hook' => $hook,
'callback_args' => $callback_args,
'group' => $group,
'unique' => $unique,
'priority' => $priority,
);
try {
// Generate schedule start if appropriate.
if ( ! in_array( $schedule_start, static::ASYNC_OPTS, true ) ) {
$schedule_start = as_get_datetime_object( $schedule_start );
$function_args['start'] = $schedule_start->format( 'U' );
}
} catch ( \Exception $e ) {
\WP_CLI::error( $e->getMessage() );
}
// Default to creating single action.
$action_type = 'single';
$function = 'as_schedule_single_action';
if ( ! empty( $interval ) ) { // Creating recurring action.
$action_type = 'recurring';
$function = 'as_schedule_recurring_action';
$function_args = array_filter(
$function_args,
static function( $key ) {
return in_array( $key, array( 'start', 'interval', 'hook', 'callback_args', 'group', 'unique', 'priority' ), true );
},
ARRAY_FILTER_USE_KEY
);
} elseif ( ! empty( $cron ) ) { // Creating cron action.
$action_type = 'cron';
$function = 'as_schedule_cron_action';
$function_args = array_filter(
$function_args,
static function( $key ) {
return in_array( $key, array( 'start', 'cron', 'hook', 'callback_args', 'group', 'unique', 'priority' ), true );
},
ARRAY_FILTER_USE_KEY
);
} elseif ( in_array( $function_args['start'], static::ASYNC_OPTS, true ) ) { // Enqueue async action.
$action_type = 'async';
$function = 'as_enqueue_async_action';
$function_args = array_filter(
$function_args,
static function( $key ) {
return in_array( $key, array( 'hook', 'callback_args', 'group', 'unique', 'priority' ), true );
},
ARRAY_FILTER_USE_KEY
);
} else { // Enqueue single action.
$function_args = array_filter(
$function_args,
static function( $key ) {
return in_array( $key, array( 'start', 'hook', 'callback_args', 'group', 'unique', 'priority' ), true );
},
ARRAY_FILTER_USE_KEY
);
}
$function_args = array_values( $function_args );
try {
$action_id = call_user_func_array( $function, $function_args );
} catch ( \Exception $e ) {
$this->print_error( $e );
}
if ( 0 === $action_id ) {
$e = new \Exception( __( 'Unable to create a scheduled action.', 'action-scheduler' ) );
$this->print_error( $e );
}
$this->print_success( $action_id, $action_type );
}
/**
* Print a success message with the action ID.
*
* @param int $action_id Created action ID.
* @param string $action_type Type of action.
*
* @return void
*/
protected function print_success( $action_id, $action_type ) {
\WP_CLI::success(
sprintf(
/* translators: %1$s: type of action, %2$d: ID of the created action */
__( '%1$s action (%2$d) scheduled.', 'action-scheduler' ),
ucfirst( $action_type ),
$action_id
)
);
}
/**
* Convert an exception into a WP CLI error.
*
* @param \Exception $e The error object.
* @throws \WP_CLI\ExitException When an error occurs.
* @return void
*/
protected function print_error( \Exception $e ) {
\WP_CLI::error(
sprintf(
/* translators: %s refers to the exception error message. */
__( 'There was an error creating the scheduled action: %s', 'action-scheduler' ),
$e->getMessage()
)
);
}
}
Action/List_Command.php 0000666 00000006067 15114242262 0011057 0 ustar 00 <?php
namespace Action_Scheduler\WP_CLI\Action;
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaping output is not necessary in WP CLI.
/**
* WP-CLI command: action-scheduler action list
*/
class List_Command extends \ActionScheduler_WPCLI_Command {
const PARAMETERS = array(
'hook',
'args',
'date',
'date_compare',
'modified',
'modified_compare',
'group',
'status',
'claimed',
'per_page',
'offset',
'orderby',
'order',
);
/**
* Execute command.
*
* @return void
*/
public function execute() {
$store = \ActionScheduler::store();
$logger = \ActionScheduler::logger();
$fields = array(
'id',
'hook',
'status',
'group',
'recurring',
'scheduled_date',
);
$this->process_csv_arguments_to_arrays();
if ( ! empty( $this->assoc_args['fields'] ) ) {
$fields = $this->assoc_args['fields'];
}
$formatter = new \WP_CLI\Formatter( $this->assoc_args, $fields );
$query_args = $this->assoc_args;
/**
* The `claimed` parameter expects a boolean or integer:
* check for string 'false', and set explicitly to `false` boolean.
*/
if ( array_key_exists( 'claimed', $query_args ) && 'false' === strtolower( $query_args['claimed'] ) ) {
$query_args['claimed'] = false;
}
$return_format = 'OBJECT';
if ( in_array( $formatter->format, array( 'ids', 'count' ), true ) ) {
$return_format = '\'ids\'';
}
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
$params = var_export( $query_args, true );
if ( empty( $query_args ) ) {
$params = 'array()';
}
\WP_CLI::debug(
sprintf(
'as_get_scheduled_actions( %s, %s )',
$params,
$return_format
)
);
if ( ! empty( $query_args['args'] ) ) {
$query_args['args'] = json_decode( $query_args['args'], true );
}
switch ( $formatter->format ) {
case 'ids':
$actions = as_get_scheduled_actions( $query_args, 'ids' );
echo implode( ' ', $actions );
break;
case 'count':
$actions = as_get_scheduled_actions( $query_args, 'ids' );
$formatter->display_items( $actions );
break;
default:
$actions = as_get_scheduled_actions( $query_args, OBJECT );
$actions_arr = array();
foreach ( $actions as $action_id => $action ) {
$action_arr = array(
'id' => $action_id,
'hook' => $action->get_hook(),
'status' => $store->get_status( $action_id ),
'args' => $action->get_args(),
'group' => $action->get_group(),
'recurring' => $action->get_schedule()->is_recurring() ? 'yes' : 'no',
'scheduled_date' => $this->get_schedule_display_string( $action->get_schedule() ),
'log_entries' => array(),
);
foreach ( $logger->get_logs( $action_id ) as $log_entry ) {
$action_arr['log_entries'][] = array(
'date' => $log_entry->get_date()->format( static::DATE_FORMAT ),
'message' => $log_entry->get_message(),
);
}
$actions_arr[] = $action_arr;
}
$formatter->display_items( $actions_arr );
break;
}
}
}
Action/Delete_Command.php 0000666 00000005145 15114242262 0011342 0 ustar 00 <?php
namespace Action_Scheduler\WP_CLI\Action;
/**
* WP-CLI command: action-scheduler action delete
*/
class Delete_Command extends \ActionScheduler_WPCLI_Command {
/**
* Array of action IDs to delete.
*
* @var int[]
*/
protected $action_ids = array();
/**
* Number of deleted, failed, and total actions deleted.
*
* @var array<string, int>
*/
protected $action_counts = array(
'deleted' => 0,
'failed' => 0,
'total' => 0,
);
/**
* Construct.
*
* @param string[] $args Positional arguments.
* @param array<string, string> $assoc_args Keyed arguments.
*/
public function __construct( array $args, array $assoc_args ) {
parent::__construct( $args, $assoc_args );
$this->action_ids = array_map( 'absint', $args );
$this->action_counts['total'] = count( $this->action_ids );
add_action( 'action_scheduler_deleted_action', array( $this, 'on_action_deleted' ) );
}
/**
* Execute.
*
* @return void
*/
public function execute() {
$store = \ActionScheduler::store();
$progress_bar = \WP_CLI\Utils\make_progress_bar(
sprintf(
/* translators: %d: number of actions to be deleted */
_n( 'Deleting %d action', 'Deleting %d actions', $this->action_counts['total'], 'action-scheduler' ),
number_format_i18n( $this->action_counts['total'] )
),
$this->action_counts['total']
);
foreach ( $this->action_ids as $action_id ) {
try {
$store->delete_action( $action_id );
} catch ( \Exception $e ) {
$this->action_counts['failed']++;
\WP_CLI::warning( $e->getMessage() );
}
$progress_bar->tick();
}
$progress_bar->finish();
/* translators: %1$d: number of actions deleted */
$format = _n( 'Deleted %1$d action', 'Deleted %1$d actions', $this->action_counts['deleted'], 'action-scheduler' ) . ', ';
/* translators: %2$d: number of actions deletions failed */
$format .= _n( '%2$d failure.', '%2$d failures.', $this->action_counts['failed'], 'action-scheduler' );
\WP_CLI::success(
sprintf(
$format,
number_format_i18n( $this->action_counts['deleted'] ),
number_format_i18n( $this->action_counts['failed'] )
)
);
}
/**
* Action: action_scheduler_deleted_action
*
* @param int $action_id Action ID.
* @return void
*/
public function on_action_deleted( $action_id ) {
if ( 'action_scheduler_deleted_action' !== current_action() ) {
return;
}
$action_id = absint( $action_id );
if ( ! in_array( $action_id, $this->action_ids, true ) ) {
return;
}
$this->action_counts['deleted']++;
\WP_CLI::debug( sprintf( 'Action %d was deleted.', $action_id ) );
}
}
Action/Get_Command.php 0000666 00000004240 15114242262 0010652 0 ustar 00 <?php
namespace Action_Scheduler\WP_CLI\Action;
/**
* WP-CLI command: action-scheduler action get
*/
class Get_Command extends \ActionScheduler_WPCLI_Command {
/**
* Execute command.
*
* @return void
*/
public function execute() {
$action_id = $this->args[0];
$store = \ActionScheduler::store();
$logger = \ActionScheduler::logger();
$action = $store->fetch_action( $action_id );
if ( is_a( $action, ActionScheduler_NullAction::class ) ) {
/* translators: %d is action ID. */
\WP_CLI::error( sprintf( esc_html__( 'Unable to retrieve action %d.', 'action-scheduler' ), $action_id ) );
}
$only_logs = ! empty( $this->assoc_args['field'] ) && 'log_entries' === $this->assoc_args['field'];
$only_logs = $only_logs || ( ! empty( $this->assoc_args['fields'] && 'log_entries' === $this->assoc_args['fields'] ) );
$log_entries = array();
foreach ( $logger->get_logs( $action_id ) as $log_entry ) {
$log_entries[] = array(
'date' => $log_entry->get_date()->format( static::DATE_FORMAT ),
'message' => $log_entry->get_message(),
);
}
if ( $only_logs ) {
$args = array(
'format' => \WP_CLI\Utils\get_flag_value( $this->assoc_args, 'format', 'table' ),
);
$formatter = new \WP_CLI\Formatter( $args, array( 'date', 'message' ) );
$formatter->display_items( $log_entries );
return;
}
try {
$status = $store->get_status( $action_id );
} catch ( \Exception $e ) {
\WP_CLI::error( $e->getMessage() );
}
$action_arr = array(
'id' => $this->args[0],
'hook' => $action->get_hook(),
'status' => $status,
'args' => $action->get_args(),
'group' => $action->get_group(),
'recurring' => $action->get_schedule()->is_recurring() ? 'yes' : 'no',
'scheduled_date' => $this->get_schedule_display_string( $action->get_schedule() ),
'log_entries' => $log_entries,
);
$fields = array_keys( $action_arr );
if ( ! empty( $this->assoc_args['fields'] ) ) {
$fields = explode( ',', $this->assoc_args['fields'] );
}
$formatter = new \WP_CLI\Formatter( $this->assoc_args, $fields );
$formatter->display_item( $action_arr );
}
}
Action/Run_Command.php 0000666 00000011161 15114242262 0010677 0 ustar 00 <?php
namespace Action_Scheduler\WP_CLI\Action;
/**
* WP-CLI command: action-scheduler action run
*/
class Run_Command extends \ActionScheduler_WPCLI_Command {
/**
* Array of action IDs to execute.
*
* @var int[]
*/
protected $action_ids = array();
/**
* Number of executed, failed, ignored, invalid, and total actions.
*
* @var array<string, int>
*/
protected $action_counts = array(
'executed' => 0,
'failed' => 0,
'ignored' => 0,
'invalid' => 0,
'total' => 0,
);
/**
* Construct.
*
* @param string[] $args Positional arguments.
* @param array<string, string> $assoc_args Keyed arguments.
*/
public function __construct( array $args, array $assoc_args ) {
parent::__construct( $args, $assoc_args );
$this->action_ids = array_map( 'absint', $args );
$this->action_counts['total'] = count( $this->action_ids );
add_action( 'action_scheduler_execution_ignored', array( $this, 'on_action_ignored' ) );
add_action( 'action_scheduler_after_execute', array( $this, 'on_action_executed' ) );
add_action( 'action_scheduler_failed_execution', array( $this, 'on_action_failed' ), 10, 2 );
add_action( 'action_scheduler_failed_validation', array( $this, 'on_action_invalid' ), 10, 2 );
}
/**
* Execute.
*
* @return void
*/
public function execute() {
$runner = \ActionScheduler::runner();
$progress_bar = \WP_CLI\Utils\make_progress_bar(
sprintf(
/* translators: %d: number of actions */
_n( 'Executing %d action', 'Executing %d actions', $this->action_counts['total'], 'action-scheduler' ),
number_format_i18n( $this->action_counts['total'] )
),
$this->action_counts['total']
);
foreach ( $this->action_ids as $action_id ) {
$runner->process_action( $action_id, 'Action Scheduler CLI' );
$progress_bar->tick();
}
$progress_bar->finish();
foreach ( array(
'ignored',
'invalid',
'failed',
) as $type ) {
$count = $this->action_counts[ $type ];
if ( empty( $count ) ) {
continue;
}
/*
* translators:
* %1$d: count of actions evaluated.
* %2$s: type of action evaluated.
*/
$format = _n( '%1$d action %2$s.', '%1$d actions %2$s.', $count, 'action-scheduler' );
\WP_CLI::warning(
sprintf(
$format,
number_format_i18n( $count ),
$type
)
);
}
\WP_CLI::success(
sprintf(
/* translators: %d: number of executed actions */
_n( 'Executed %d action.', 'Executed %d actions.', $this->action_counts['executed'], 'action-scheduler' ),
number_format_i18n( $this->action_counts['executed'] )
)
);
}
/**
* Action: action_scheduler_execution_ignored
*
* @param int $action_id Action ID.
* @return void
*/
public function on_action_ignored( $action_id ) {
if ( 'action_scheduler_execution_ignored' !== current_action() ) {
return;
}
$action_id = absint( $action_id );
if ( ! in_array( $action_id, $this->action_ids, true ) ) {
return;
}
$this->action_counts['ignored']++;
\WP_CLI::debug( sprintf( 'Action %d was ignored.', $action_id ) );
}
/**
* Action: action_scheduler_after_execute
*
* @param int $action_id Action ID.
* @return void
*/
public function on_action_executed( $action_id ) {
if ( 'action_scheduler_after_execute' !== current_action() ) {
return;
}
$action_id = absint( $action_id );
if ( ! in_array( $action_id, $this->action_ids, true ) ) {
return;
}
$this->action_counts['executed']++;
\WP_CLI::debug( sprintf( 'Action %d was executed.', $action_id ) );
}
/**
* Action: action_scheduler_failed_execution
*
* @param int $action_id Action ID.
* @param \Exception $e Exception.
* @return void
*/
public function on_action_failed( $action_id, \Exception $e ) {
if ( 'action_scheduler_failed_execution' !== current_action() ) {
return;
}
$action_id = absint( $action_id );
if ( ! in_array( $action_id, $this->action_ids, true ) ) {
return;
}
$this->action_counts['failed']++;
\WP_CLI::debug( sprintf( 'Action %d failed execution: %s', $action_id, $e->getMessage() ) );
}
/**
* Action: action_scheduler_failed_validation
*
* @param int $action_id Action ID.
* @param \Exception $e Exception.
* @return void
*/
public function on_action_invalid( $action_id, \Exception $e ) {
if ( 'action_scheduler_failed_validation' !== current_action() ) {
return;
}
$action_id = absint( $action_id );
if ( ! in_array( $action_id, $this->action_ids, true ) ) {
return;
}
$this->action_counts['invalid']++;
\WP_CLI::debug( sprintf( 'Action %d failed validation: %s', $action_id, $e->getMessage() ) );
}
}
Action/Cancel_Command.php 0000666 00000006410 15114242262 0011321 0 ustar 00 <?php
namespace Action_Scheduler\WP_CLI\Action;
use function \WP_CLI\Utils\get_flag_value;
/**
* WP-CLI command: action-scheduler action cancel
*/
class Cancel_Command extends \ActionScheduler_WPCLI_Command {
/**
* Execute command.
*
* @return void
*/
public function execute() {
$hook = '';
$group = get_flag_value( $this->assoc_args, 'group', '' );
$callback_args = get_flag_value( $this->assoc_args, 'args', null );
$all = get_flag_value( $this->assoc_args, 'all', false );
if ( ! empty( $this->args[0] ) ) {
$hook = $this->args[0];
}
if ( ! empty( $callback_args ) ) {
$callback_args = json_decode( $callback_args, true );
}
if ( $all ) {
$this->cancel_all( $hook, $callback_args, $group );
return;
}
$this->cancel_single( $hook, $callback_args, $group );
}
/**
* Cancel single action.
*
* @param string $hook The hook that the job will trigger.
* @param array $callback_args Args that would have been passed to the job.
* @param string $group The group the job is assigned to.
* @return void
*/
protected function cancel_single( $hook, $callback_args, $group ) {
if ( empty( $hook ) ) {
\WP_CLI::error( __( 'Please specify hook of action to cancel.', 'action-scheduler' ) );
}
try {
$result = as_unschedule_action( $hook, $callback_args, $group );
} catch ( \Exception $e ) {
$this->print_error( $e, false );
}
if ( null === $result ) {
$e = new \Exception( __( 'Unable to cancel scheduled action: check the logs.', 'action-scheduler' ) );
$this->print_error( $e, false );
}
$this->print_success( false );
}
/**
* Cancel all actions.
*
* @param string $hook The hook that the job will trigger.
* @param array $callback_args Args that would have been passed to the job.
* @param string $group The group the job is assigned to.
* @return void
*/
protected function cancel_all( $hook, $callback_args, $group ) {
if ( empty( $hook ) && empty( $group ) ) {
\WP_CLI::error( __( 'Please specify hook and/or group of actions to cancel.', 'action-scheduler' ) );
}
try {
$result = as_unschedule_all_actions( $hook, $callback_args, $group );
} catch ( \Exception $e ) {
$this->print_error( $e, $multiple );
}
/**
* Because as_unschedule_all_actions() does not provide a result,
* neither confirm or deny actions cancelled.
*/
\WP_CLI::success( __( 'Request to cancel scheduled actions completed.', 'action-scheduler' ) );
}
/**
* Print a success message.
*
* @return void
*/
protected function print_success() {
\WP_CLI::success( __( 'Scheduled action cancelled.', 'action-scheduler' ) );
}
/**
* Convert an exception into a WP CLI error.
*
* @param \Exception $e The error object.
* @param bool $multiple Boolean if multiple actions.
* @throws \WP_CLI\ExitException When an error occurs.
* @return void
*/
protected function print_error( \Exception $e, $multiple ) {
\WP_CLI::error(
sprintf(
/* translators: %1$s: singular or plural %2$s: refers to the exception error message. */
__( 'There was an error cancelling the %1$s: %2$s', 'action-scheduler' ),
$multiple ? __( 'scheduled actions', 'action-scheduler' ) : __( 'scheduled action', 'action-scheduler' ),
$e->getMessage()
)
);
}
}
Action/Next_Command.php 0000666 00000003503 15114242262 0011052 0 ustar 00 <?php
namespace Action_Scheduler\WP_CLI\Action;
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaping output is not necessary in WP CLI.
use function \WP_CLI\Utils\get_flag_value;
/**
* WP-CLI command: action-scheduler action next
*/
class Next_Command extends \ActionScheduler_WPCLI_Command {
/**
* Execute command.
*
* @return void
*/
public function execute() {
$hook = $this->args[0];
$group = get_flag_value( $this->assoc_args, 'group', '' );
$callback_args = get_flag_value( $this->assoc_args, 'args', null );
$raw = (bool) get_flag_value( $this->assoc_args, 'raw', false );
if ( ! empty( $callback_args ) ) {
$callback_args = json_decode( $callback_args, true );
}
if ( $raw ) {
\WP_CLI::line( as_next_scheduled_action( $hook, $callback_args, $group ) );
return;
}
$params = array(
'hook' => $hook,
'orderby' => 'date',
'order' => 'ASC',
'group' => $group,
);
if ( is_array( $callback_args ) ) {
$params['args'] = $callback_args;
}
$params['status'] = \ActionScheduler_Store::STATUS_RUNNING;
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
\WP_CLI::debug( 'ActionScheduler()::store()->query_action( ' . var_export( $params, true ) . ' )' );
$store = \ActionScheduler::store();
$action_id = $store->query_action( $params );
if ( $action_id ) {
echo $action_id;
return;
}
$params['status'] = \ActionScheduler_Store::STATUS_PENDING;
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_var_export
\WP_CLI::debug( 'ActionScheduler()::store()->query_action( ' . var_export( $params, true ) . ' )' );
$action_id = $store->query_action( $params );
if ( $action_id ) {
echo $action_id;
return;
}
\WP_CLI::warning( 'No matching next action.' );
}
}
Action/Generate_Command.php 0000666 00000006737 15114242262 0011702 0 ustar 00 <?php
namespace Action_Scheduler\WP_CLI\Action;
use function \WP_CLI\Utils\get_flag_value;
/**
* WP-CLI command: action-scheduler action generate
*/
class Generate_Command extends \ActionScheduler_WPCLI_Command {
/**
* Execute command.
*
* @return void
*/
public function execute() {
$hook = $this->args[0];
$schedule_start = $this->args[1];
$callback_args = get_flag_value( $this->assoc_args, 'args', array() );
$group = get_flag_value( $this->assoc_args, 'group', '' );
$interval = (int) get_flag_value( $this->assoc_args, 'interval', 0 ); // avoid absint() to support negative intervals
$count = absint( get_flag_value( $this->assoc_args, 'count', 1 ) );
if ( ! empty( $callback_args ) ) {
$callback_args = json_decode( $callback_args, true );
}
$schedule_start = as_get_datetime_object( $schedule_start );
$function_args = array(
'start' => absint( $schedule_start->format( 'U' ) ),
'interval' => $interval,
'count' => $count,
'hook' => $hook,
'callback_args' => $callback_args,
'group' => $group,
);
$function_args = array_values( $function_args );
try {
$actions_added = $this->generate( ...$function_args );
} catch ( \Exception $e ) {
$this->print_error( $e );
}
$num_actions_added = count( (array) $actions_added );
$this->print_success( $num_actions_added, 'single' );
}
/**
* Schedule multiple single actions.
*
* @param int $schedule_start Starting timestamp of first action.
* @param int $interval How long to wait between runs.
* @param int $count Limit number of actions to schedule.
* @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 int[] IDs of actions added.
*/
protected function generate( $schedule_start, $interval, $count, $hook, array $args = array(), $group = '' ) {
$actions_added = array();
$progress_bar = \WP_CLI\Utils\make_progress_bar(
sprintf(
/* translators: %d is number of actions to create */
_n( 'Creating %d action', 'Creating %d actions', $count, 'action-scheduler' ),
number_format_i18n( $count )
),
$count
);
for ( $i = 0; $i < $count; $i++ ) {
$actions_added[] = as_schedule_single_action( $schedule_start + ( $i * $interval ), $hook, $args, $group );
$progress_bar->tick();
}
$progress_bar->finish();
return $actions_added;
}
/**
* Print a success message with the action ID.
*
* @param int $actions_added Number of actions generated.
* @param string $action_type Type of actions scheduled.
* @return void
*/
protected function print_success( $actions_added, $action_type ) {
\WP_CLI::success(
sprintf(
/* translators: %1$d refers to the total number of tasks added, %2$s is the action type */
_n( '%1$d %2$s action scheduled.', '%1$d %2$s actions scheduled.', $actions_added, 'action-scheduler' ),
number_format_i18n( $actions_added ),
$action_type
)
);
}
/**
* Convert an exception into a WP CLI error.
*
* @param \Exception $e The error object.
* @throws \WP_CLI\ExitException When an error occurs.
* @return void
*/
protected function print_error( \Exception $e ) {
\WP_CLI::error(
sprintf(
/* translators: %s refers to the exception error message. */
__( 'There was an error creating the scheduled action: %s', 'action-scheduler' ),
$e->getMessage()
)
);
}
}
ProgressBar.php 0000666 00000005316 15114242262 0007516 0 ustar 00 <?php
namespace Action_Scheduler\WP_CLI;
/**
* WP_CLI progress bar for Action Scheduler.
*/
/**
* Class ProgressBar
*
* @package Action_Scheduler\WP_CLI
*
* @since 3.0.0
*
* @codeCoverageIgnore
*/
class ProgressBar {
/**
* Current number of ticks.
*
* @var integer
*/
protected $total_ticks;
/**
* Total number of ticks.
*
* @var integer
*/
protected $count;
/**
* Progress bar update interval.
*
* @var integer
*/
protected $interval;
/**
* Progress bar message.
*
* @var string
*/
protected $message;
/**
* Instance.
*
* @var \cli\progress\Bar
*/
protected $progress_bar;
/**
* ProgressBar constructor.
*
* @param string $message Text to display before the progress bar.
* @param integer $count Total number of ticks to be performed.
* @param integer $interval Optional. The interval in milliseconds between updates. Default 100.
*
* @throws \Exception When this is not run within WP CLI.
*/
public function __construct( $message, $count, $interval = 100 ) {
if ( ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
/* translators: %s php class name */
throw new \Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), __CLASS__ ) );
}
$this->total_ticks = 0;
$this->message = $message;
$this->count = $count;
$this->interval = $interval;
}
/**
* Increment the progress bar ticks.
*/
public function tick() {
if ( null === $this->progress_bar ) {
$this->setup_progress_bar();
}
$this->progress_bar->tick();
$this->total_ticks++;
do_action( 'action_scheduler/progress_tick', $this->total_ticks ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
}
/**
* Get the progress bar tick count.
*
* @return int
*/
public function current() {
return $this->progress_bar ? $this->progress_bar->current() : 0;
}
/**
* Finish the current progress bar.
*/
public function finish() {
if ( null !== $this->progress_bar ) {
$this->progress_bar->finish();
}
$this->progress_bar = null;
}
/**
* Set the message used when creating the progress bar.
*
* @param string $message The message to be used when the next progress bar is created.
*/
public function set_message( $message ) {
$this->message = $message;
}
/**
* Set the count for a new progress bar.
*
* @param integer $count The total number of ticks expected to complete.
*/
public function set_count( $count ) {
$this->count = $count;
$this->finish();
}
/**
* Set up the progress bar.
*/
protected function setup_progress_bar() {
$this->progress_bar = \WP_CLI\Utils\make_progress_bar(
$this->message,
$this->count,
$this->interval
);
}
}
ActionScheduler_WPCLI_QueueRunner.php 0000666 00000014331 15114242262 0013632 0 ustar 00 <?php
use Action_Scheduler\WP_CLI\ProgressBar;
/**
* WP CLI Queue runner.
*
* This class can only be called from within a WP CLI instance.
*/
class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
/**
* Claimed actions.
*
* @var array
*/
protected $actions;
/**
* ActionScheduler_ActionClaim instance.
*
* @var ActionScheduler_ActionClaim
*/
protected $claim;
/**
* Progress bar instance.
*
* @var \cli\progress\Bar
*/
protected $progress_bar;
/**
* ActionScheduler_WPCLI_QueueRunner constructor.
*
* @param ActionScheduler_Store|null $store Store object.
* @param ActionScheduler_FatalErrorMonitor|null $monitor Monitor object.
* @param ActionScheduler_QueueCleaner|null $cleaner Cleaner object.
*
* @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 ) ) {
/* translators: %s php class name */
throw new Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), __CLASS__ ) );
}
parent::__construct( $store, $monitor, $cleaner );
}
/**
* Set up the Queue before processing.
*
* @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.
if ( $this->has_maximum_concurrent_batches() ) {
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.
*/
protected function add_hooks() {
add_action( 'action_scheduler_before_execute', array( $this, 'before_execute' ) );
add_action( 'action_scheduler_after_execute', array( $this, 'after_execute' ), 10, 2 );
add_action( 'action_scheduler_failed_execution', array( $this, 'action_failed' ), 10, 2 );
}
/**
* Set up the WP CLI progress bar.
*/
protected function setup_progress_bar() {
$count = count( $this->actions );
$this->progress_bar = new ProgressBar(
/* translators: %d: amount of actions */
sprintf( _n( 'Running %d action', 'Running %d actions', $count, 'action-scheduler' ), $count ),
$count
);
}
/**
* Process actions in the queue.
*
* @param string $context Optional runner context. Default 'WP CLI'.
*
* @return int The number of actions processed.
*/
public function run( $context = 'WP CLI' ) {
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() ), true ) ) {
WP_CLI::warning( __( 'The claim has been lost. Aborting current batch.', 'action-scheduler' ) );
break;
}
$this->process_action( $action_id, $context );
$this->progress_bar->tick();
}
$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.
*
* @param int $action_id 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.
*
* @param int $action_id ActionID.
* @param null|ActionScheduler_Action $action The instance of the action. Default to null for backward compatibility.
*/
public function after_execute( $action_id, $action = null ) {
// backward compatibility.
if ( null === $action ) {
$action = $this->store->fetch_action( $action_id );
}
/* translators: 1: action ID 2: hook name */
WP_CLI::log( sprintf( __( 'Completed processing action %1$s with hook: %2$s', 'action-scheduler' ), $action_id, $action->get_hook() ) );
}
/**
* Handle WP CLI message when the action has failed.
*
* @param int $action_id Action ID.
* @param Exception $exception Exception.
* @throws \WP_CLI\ExitException With failure message.
*/
public function action_failed( $action_id, $exception ) {
WP_CLI::error(
/* translators: 1: action ID 2: 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.
* @deprecated 3.0.0
*/
protected function stop_the_insanity( $sleep_time = 0 ) {
_deprecated_function( 'ActionScheduler_WPCLI_QueueRunner::stop_the_insanity', '3.0.0', 'ActionScheduler_DataController::free_memory' );
ActionScheduler_DataController::free_memory();
}
/**
* Maybe trigger the stop_the_insanity() method to free up memory.
*/
protected function maybe_stop_the_insanity() {
// The value returned by progress_bar->current() might be padded. Remove padding, and convert to int.
$current_iteration = intval( trim( $this->progress_bar->current() ) );
if ( 0 === $current_iteration % 50 ) {
$this->stop_the_insanity();
}
}
}