deleted plugin WPScan
version 1.15.5
This commit is contained in:
parent
903552dde7
commit
30f6692a58
@ -1,160 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace WPScan;
|
||||
|
||||
// Exit if accessed directly.
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Account.
|
||||
*
|
||||
* Deals with user's wpvulndb API user accounts.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Account {
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @param object $parent parent.
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function __construct( $parent ) {
|
||||
$this->parent = $parent;
|
||||
|
||||
add_action( 'admin_init', array( $this, 'add_account_summary_meta_box' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Update account status by calling the /status endpoint.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @param string $api_token
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function update_account_status( $api_token = null ) {
|
||||
$current = get_option( $this->parent->OPT_ACCOUNT_STATUS, array() );
|
||||
$updated = $current;
|
||||
|
||||
$req = $this->parent->api_get( '/status', $api_token );
|
||||
|
||||
if ( is_object( $req ) ) {
|
||||
$updated['plan'] = $req->plan;
|
||||
|
||||
// Enterprise users.
|
||||
if ( -1 === $req->requests_remaining ) {
|
||||
$updated['limit'] = __( 'unlimited', 'wpscan' );
|
||||
$updated['remaining'] = __( 'unlimited', 'wpscan' );
|
||||
$updated['reset'] = __( 'unlimited', 'wpscan' );
|
||||
} else {
|
||||
$updated['limit'] = $req->requests_limit;
|
||||
$updated['remaining'] = $req->requests_remaining;
|
||||
$updated['reset'] = $req->requests_reset;
|
||||
}
|
||||
|
||||
update_option( $this->parent->OPT_ACCOUNT_STATUS, $updated );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add meta box
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function add_account_summary_meta_box() {
|
||||
if ( $this->parent->classes['settings']->api_token_set() ) {
|
||||
add_meta_box(
|
||||
'wpscan-account-summary',
|
||||
__( 'Account Status', 'wpscan' ),
|
||||
array( $this, 'do_meta_box_account_summary' ),
|
||||
'wpscan',
|
||||
'side',
|
||||
'low'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get account status
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function get_account_status() {
|
||||
$defaults = array(
|
||||
'plan' => 'None',
|
||||
'limit' => 25,
|
||||
'remaining' => 25,
|
||||
'reset' => time(),
|
||||
);
|
||||
|
||||
return get_option( $this->parent->OPT_ACCOUNT_STATUS, $defaults );
|
||||
}
|
||||
|
||||
/**
|
||||
* Render account status metabox
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function do_meta_box_account_summary() {
|
||||
extract( $this->get_account_status() );
|
||||
|
||||
if ( 'enterprise' !== $plan ) {
|
||||
if ( ! isset( $limit ) || ! is_numeric( $limit ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Reset time in hours.
|
||||
$diff = $reset - time();
|
||||
$days = floor( $diff / ( 60 * 60 * 24 ) );
|
||||
$hours = round( ( $diff - $days * 60 * 60 * 24 ) / ( 60 * 60 ) );
|
||||
$hours_display = $hours > 1 ? __( 'Hours', 'wpscan' ) : __( 'Hour', 'wpscan' );
|
||||
|
||||
// Used.
|
||||
$used = $limit - $remaining;
|
||||
|
||||
// Usage percentage.
|
||||
$percentage = 0 !== $limit ? ( $used * 100 ) / $limit : 0;
|
||||
|
||||
// Usage color.
|
||||
if ( $percentage < 50 ) {
|
||||
$usage_color = 'wpscan-status-green';
|
||||
} elseif ( $percentage >= 50 && $percentage < 95 ) {
|
||||
$usage_color = 'wpscan-status-orange';
|
||||
} else {
|
||||
$usage_color = 'wpscan-status-red';
|
||||
}
|
||||
} else {
|
||||
// For enterprise users.
|
||||
$used = $limit;
|
||||
$hours = $reset;
|
||||
$hours_display = null;
|
||||
$usage_color = 'wpscan-status-green';
|
||||
}
|
||||
|
||||
// Upgrade button.
|
||||
$btn_text = 'free' === $plan ? __( 'Upgrade', 'wpscan' ) : __( 'Manage', 'wpscan' );
|
||||
$btn_url = WPSCAN_PROFILE_URL;
|
||||
|
||||
// Output data.
|
||||
echo '<ul>';
|
||||
echo '<li>' . __( 'Plan', 'wpscan' ) . '<span>' . esc_html( $plan ) . '</span></li>';
|
||||
|
||||
if ( 'enterprise' !== $plan ) {
|
||||
echo '<li>' . __( 'Usage', 'wpscan' ) . "<span class='$usage_color'> $used / $limit </span></li>";
|
||||
echo '<li>' . __( 'Resets In', 'wpscan' ) . "<span> $hours $hours_display </span></li>";
|
||||
}
|
||||
echo '</ul>';
|
||||
|
||||
// Output upgrade/manage button.
|
||||
echo "<a class='button button-primary' href='$btn_url' target='_blank'>$btn_text</a>";
|
||||
}
|
||||
}
|
@ -1,244 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace WPScan\Checks;
|
||||
|
||||
// Exit if accessed directly.
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Security Checks.
|
||||
*
|
||||
* Handles the security checks system.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
abstract class Check {
|
||||
/**
|
||||
* A list of identified vulnerabilities for this check.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @var array|null
|
||||
*/
|
||||
public $vulnerabilities;
|
||||
|
||||
/**
|
||||
* Actions list.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @var array|null
|
||||
*/
|
||||
public $actions = array();
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $id id.
|
||||
* @param string $dir dir.
|
||||
* @param string $parent parent.
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public final function __construct( $id, $dir, $parent ) {
|
||||
$this->id = $id;
|
||||
$this->dir = $dir;
|
||||
$this->parent = $parent;
|
||||
|
||||
$count = $this->get_vulnerabilities_count();
|
||||
|
||||
$this->actions[] = array(
|
||||
'id' => 'run',
|
||||
'title' => __( 'Run', 'wpscan' ),
|
||||
'method' => 'run',
|
||||
);
|
||||
|
||||
if ( $count > 0 ) {
|
||||
$this->actions[] = array(
|
||||
'id' => 'dismiss',
|
||||
'title' => __( 'Dismiss', 'wpscan' ),
|
||||
'method' => 'dismiss',
|
||||
'confirm' => true,
|
||||
);
|
||||
}
|
||||
|
||||
if ( method_exists( $this, 'init' ) ) {
|
||||
$this->init();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check title.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
abstract public function title();
|
||||
|
||||
/**
|
||||
* Check description.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
abstract public function description();
|
||||
|
||||
/**
|
||||
* Success message.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
abstract public function success_message();
|
||||
|
||||
/**
|
||||
* Add vulnerability
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $title The vulnerability title.
|
||||
* @param string $severity The severity, can be critical, high, medium, low and info.
|
||||
* @param string $id Unique string to represent the vulnerability in the report object.
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
final public function add_vulnerability( $title, $severity, $id, $remediation_url ) {
|
||||
$vulnerability = array(
|
||||
'title' => $title,
|
||||
'severity' => $severity,
|
||||
'id' => $id,
|
||||
'remediation_url' => $remediation_url,
|
||||
);
|
||||
|
||||
$this->vulnerabilities[] = $vulnerability;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get vulnerabilities.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return array|null
|
||||
*/
|
||||
final public function get_vulnerabilities() {
|
||||
if ( ! empty( $this->vulnerabilities ) ) {
|
||||
return $this->vulnerabilities;
|
||||
}
|
||||
|
||||
$report = $this->parent->get_report();
|
||||
|
||||
if ( isset( $report['security-checks'] ) ) {
|
||||
if ( isset( $report['security-checks'][ $this->id ] ) ) {
|
||||
return $report['security-checks'][ $this->id ]['vulnerabilities'];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get item non-ignored vulnerabilities count
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @access public
|
||||
* @return int
|
||||
*/
|
||||
public function get_vulnerabilities_count() {
|
||||
$vulnerabilities = $this->get_vulnerabilities();
|
||||
$ignored = $this->parent->get_ignored_vulnerabilities();
|
||||
|
||||
if ( empty( $vulnerabilities ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
foreach ( $vulnerabilities as $key => &$item ) {
|
||||
if ( in_array( $item['id'], $ignored, true ) ) {
|
||||
unset( $vulnerabilities[ $key ] );
|
||||
}
|
||||
}
|
||||
|
||||
return count( $vulnerabilities );
|
||||
}
|
||||
|
||||
/**
|
||||
* Dismiss action
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return bool
|
||||
*/
|
||||
public function dismiss() {
|
||||
$report = $this->parent->get_report();
|
||||
$updated = $report;
|
||||
|
||||
if ( isset( $updated['security-checks'] ) ) {
|
||||
if ( isset( $updated['security-checks'][ $this->id ] ) ) {
|
||||
$updated['security-checks'][ $this->id ]['vulnerabilities'] = array();
|
||||
}
|
||||
}
|
||||
|
||||
if ( $report === $updated ) {
|
||||
return true;
|
||||
} else {
|
||||
return update_option( $this->parent->OPT_REPORT, $updated );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run action.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return bool
|
||||
*/
|
||||
public function run() {
|
||||
$report = $this->parent->get_report();
|
||||
$updated = $report;
|
||||
|
||||
if ( empty( $updated ) ) {
|
||||
$updated = array(
|
||||
'security-checks' => array(),
|
||||
'plugins' => array(),
|
||||
'themes' => array(),
|
||||
'wordpress' => array(),
|
||||
);
|
||||
}
|
||||
|
||||
if ( isset( $updated['security-checks'][ $this->id ] ) ) {
|
||||
$updated['security-checks'][ $this->id ] = array();
|
||||
}
|
||||
|
||||
$this->perform();
|
||||
|
||||
if ( is_array( $this->vulnerabilities ) ) {
|
||||
$updated['security-checks'][ $this->id ]['vulnerabilities'] = $this->vulnerabilities;
|
||||
|
||||
$this->parent->maybe_fire_issue_found_action('security-check', $this->id, $updated['security-checks'][ $this->id ]);
|
||||
} else {
|
||||
$updated['security-checks'][ $this->id ]['vulnerabilities'] = array();
|
||||
}
|
||||
|
||||
if ( $report === $updated ) {
|
||||
return true;
|
||||
} else {
|
||||
return update_option( $this->parent->OPT_REPORT, $updated );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform the check and save the results.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
abstract public function perform();
|
||||
}
|
@ -1,377 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace WPScan\Checks;
|
||||
|
||||
// Exit if accessed directly.
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* System.
|
||||
*
|
||||
* General system functions.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class System {
|
||||
|
||||
public $OPT_FATAL_ERRORS = 'wpscan_fatal_errors';
|
||||
|
||||
// Schedule.
|
||||
public $WPSCAN_SECURITY_SCHEDULE = 'wpscan_security_schedule';
|
||||
|
||||
// Events Inline.
|
||||
public $OPT_EVENTS_INLINE = 'wpscan_events_inline';
|
||||
|
||||
// Current running events.
|
||||
public $current_running = '';
|
||||
|
||||
/**
|
||||
* A list of registered checks.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @var array
|
||||
*/
|
||||
public $checks = array();
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @param object $parent parent.
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
*
|
||||
*/
|
||||
public function __construct( $parent ) {
|
||||
$this->parent = $parent;
|
||||
$this->current_running = get_option( $this->OPT_EVENTS_INLINE );
|
||||
|
||||
register_shutdown_function( array( $this, 'catch_errors' ) );
|
||||
|
||||
add_action( 'admin_notices', array( $this, 'display_errors' ) );
|
||||
|
||||
add_action( 'plugins_loaded', array( $this, 'load_checks' ) );
|
||||
add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue' ) );
|
||||
add_action( 'wp_ajax_wpscan_check_action', array( $this, 'handle_actions' ) );
|
||||
|
||||
add_action( $this->WPSCAN_SECURITY_SCHEDULE, array( $this, 'security_check_now' ), 99 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register Admin Scripts
|
||||
*
|
||||
* @param string $hook parent.
|
||||
*
|
||||
* @access public
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public function admin_enqueue( $hook ) {
|
||||
if ( $hook === $this->parent->page_hook ) {
|
||||
wp_enqueue_script(
|
||||
'wpscan-security-checks',
|
||||
plugins_url( 'assets/js/security-checks.js', WPSCAN_PLUGIN_FILE ),
|
||||
array( 'jquery-ui-tooltip' )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load checks files.
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function load_checks() {
|
||||
$dir = $this->parent->plugin_dir . 'security-checks';
|
||||
$folders = array_diff( scandir( $dir ), array( '..', '.' ) );
|
||||
|
||||
foreach ( $folders as $folder ) {
|
||||
$file = "$dir/$folder/check.php";
|
||||
|
||||
if ( '.' === $folder[0] ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
require_once $file;
|
||||
|
||||
$data = get_file_data( $file, array( 'classname' => 'classname' ) );
|
||||
|
||||
$data['instance'] = new $data['classname']( $folder, "$dir/$folder", $this->parent );
|
||||
|
||||
$this->checks[ $folder ] = $data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a shutdown hook to catch errors
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function catch_errors() {
|
||||
$error = error_get_last();
|
||||
|
||||
if ( $error && $error['type'] ) {
|
||||
|
||||
if ( basename( $error['file'] ) == 'check.php' ) {
|
||||
$errors = get_option( $this->OPT_FATAL_ERRORS, array() );
|
||||
|
||||
array_push( $errors, $error );
|
||||
|
||||
update_option( $this->OPT_FATAL_ERRORS, array_unique( $errors ) );
|
||||
|
||||
$report = $this->parent->get_report();
|
||||
|
||||
$report['cache'] = strtotime( current_time( 'mysql' ) );
|
||||
|
||||
update_option( $this->parent->OPT_REPORT, $report );
|
||||
|
||||
$this->parent->classes['account']->update_account_status();
|
||||
|
||||
delete_transient( $this->parent->WPSCAN_TRANSIENT_CRON );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Display fatal errors
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function display_errors() {
|
||||
$screen = get_current_screen();
|
||||
$errors = get_option( $this->OPT_FATAL_ERRORS, array() );
|
||||
|
||||
if ( strstr( $screen->id, $this->parent->classes['report']->page ) ) {
|
||||
foreach ( $errors as $err ) {
|
||||
$msg = explode( 'Stack', $err['message'] )[0];
|
||||
$msg = trim( $msg );
|
||||
|
||||
echo "<div class='notice notice-error'><p>$msg</p></div>";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return vulnerabilities in the report.
|
||||
*
|
||||
* This is very similar, but subtly different to
|
||||
* Report->list_security_check_vulnerabilities().
|
||||
* Should see if they could be merged.
|
||||
*
|
||||
* @param object $check - The check instance.
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
* @since 1.14.4
|
||||
*
|
||||
*/
|
||||
public function get_check_vulnerabilities( $instance ) {
|
||||
$vulnerabilities = $instance->get_vulnerabilities();
|
||||
$count = $instance->get_vulnerabilities_count();
|
||||
$ignored = $this->parent->get_ignored_vulnerabilities();
|
||||
|
||||
$not_checked_text = __( 'Not checked yet. Click the Run button to run a scan', 'wpscan' );
|
||||
|
||||
if ( ! isset( $vulnerabilities ) ) {
|
||||
return esc_html( $not_checked_text );
|
||||
} elseif ( empty( $vulnerabilities ) || 0 === $count ) {
|
||||
return esc_html( $instance->success_message() );
|
||||
} else {
|
||||
$list = array();
|
||||
|
||||
foreach ( $vulnerabilities as $item ) {
|
||||
if ( in_array( $item['id'], $ignored, true ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$html = "<div class='vulnerability'>";
|
||||
$html .= "<div class='vulnerability-severity'>";
|
||||
$html .= "<span class='wpscan-" . esc_attr( $item['severity'] ) . "'>" . esc_html( $item['severity'] ) . '</span>';
|
||||
$html .= '</div>';
|
||||
$html .= "<div class='vulnerability-title'>" . wp_kses( $item['title'], array( 'a' => array( 'href' => array() ) ) ) . '</div>';
|
||||
$html .= '</div>';
|
||||
$list[] = $html;
|
||||
}
|
||||
|
||||
return join( '<br>', $list );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Display actions buttons
|
||||
*
|
||||
* @param object $instance - The check instance.
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
* @since 1.0.0
|
||||
*
|
||||
*/
|
||||
public function list_actions( $instance ) {
|
||||
foreach ( $instance->actions as $action ) {
|
||||
$confirm = isset( $action['confirm'] ) ? $action['confirm'] : false;
|
||||
$button_text = ( $this->current_running && array_key_exists( $instance->id, $this->current_running ) && 'dismiss' !== $action['id'] ) ? esc_html__( 'Running', 'wpscan' ) : esc_html( $action['title'] );
|
||||
$button_disabled = ( $this->current_running && array_key_exists( $instance->id, $this->current_running ) && 'dismiss' !== $action['id'] ) ? ' disabled' : '';
|
||||
|
||||
echo sprintf(
|
||||
"<button class='button' data-check-id='%s' data-confirm='%s' data-action='%s'%s> %s</button>",
|
||||
esc_attr( $instance->id ),
|
||||
esc_attr( $confirm ),
|
||||
esc_attr( $action['id'] ),
|
||||
$button_disabled,
|
||||
$button_text
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get actions buttons
|
||||
*
|
||||
* @param object $instance - The check instance.
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
* @since 1.14.4
|
||||
*
|
||||
*/
|
||||
public function get_list_actions( $instance ) {
|
||||
foreach ( $instance->actions as $action ) {
|
||||
$confirm = isset( $action['confirm'] ) ? $action['confirm'] : false;
|
||||
$button_text = ( $this->current_running && array_key_exists( $instance->id, $this->current_running ) && 'dismiss' !== $action['id'] ) ? esc_html__( 'Running', 'wpscan' ) : esc_html( $action['title'] );
|
||||
$button_disabled = ( $this->current_running && array_key_exists( $instance->id, $this->current_running ) && 'dismiss' !== $action['id'] ) ? ' disabled' : '';
|
||||
|
||||
return sprintf(
|
||||
"<button class='button' data-check-id='%s' data-confirm='%s' data-action='%s'%s> %s</button>",
|
||||
esc_attr( $instance->id ),
|
||||
esc_attr( $confirm ),
|
||||
esc_attr( $action['id'] ),
|
||||
$button_disabled,
|
||||
$button_text
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load checks files.
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function handle_actions() {
|
||||
check_ajax_referer( 'wpscan' );
|
||||
|
||||
if ( ! current_user_can( $this->parent->WPSCAN_ROLE ) ) {
|
||||
wp_die();
|
||||
}
|
||||
|
||||
$check = isset( $_POST['check'] ) ? $_POST['check'] : false;
|
||||
$action = isset( $_POST['action_id'] ) ? $_POST['action_id'] : false;
|
||||
|
||||
if ( $action && $check ) {
|
||||
$res = 0;
|
||||
if ( 'run' === $action ) {
|
||||
$event_type[ $check ] = $action;
|
||||
$this->add_event_inline( $event_type );
|
||||
|
||||
if ( false === as_next_scheduled_action( $this->WPSCAN_SECURITY_SCHEDULE ) ) {
|
||||
as_schedule_single_action( strtotime( 'now' ), $this->WPSCAN_SECURITY_SCHEDULE );
|
||||
}
|
||||
$res = 1;
|
||||
} else {
|
||||
$action = array_filter(
|
||||
$this->checks[ $check ]['instance']->actions,
|
||||
function ( $i ) use ( $action ) {
|
||||
return $i['id'] === $action;
|
||||
}
|
||||
);
|
||||
|
||||
$action = current( $action );
|
||||
|
||||
if ( method_exists( $this->checks[ $check ]['instance'], $action['method'] ) ) {
|
||||
$res = call_user_func( array( $this->checks[ $check ]['instance'], $action['method'] ) );
|
||||
}
|
||||
}
|
||||
|
||||
if ( $res ) {
|
||||
wp_send_json_success( $check );
|
||||
} else {
|
||||
wp_send_json_error();
|
||||
}
|
||||
}
|
||||
|
||||
wp_send_json_error();
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the Security checks
|
||||
*
|
||||
* @since 1.15
|
||||
* @acces public
|
||||
*/
|
||||
public function security_check_now() {
|
||||
if ( ! empty( $this->current_running ) ) {
|
||||
foreach ( $this->current_running as $key => $to_check ) {
|
||||
$check = $key;
|
||||
$action = $to_check;
|
||||
$action = array_filter(
|
||||
$this->checks[ $check ]['instance']->actions,
|
||||
function ( $i ) use ( $action ) {
|
||||
return $i['id'] === $action;
|
||||
}
|
||||
);
|
||||
|
||||
$action = current( $action );
|
||||
|
||||
if ( method_exists( $this->checks[ $check ]['instance'], $action['method'] ) ) {
|
||||
call_user_func( array( $this->checks[ $check ]['instance'], $action['method'] ) );
|
||||
}
|
||||
$this->remove_event_from_list( $check );
|
||||
as_schedule_single_action( strtotime( 'now' ) + 10, $this->WPSCAN_SECURITY_SCHEDULE );
|
||||
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
delete_option( $this->OPT_EVENTS_INLINE );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register event to wait inline
|
||||
*
|
||||
* @param $event_type
|
||||
*
|
||||
* @since 1.15
|
||||
* @acces public
|
||||
*/
|
||||
public function add_event_inline( $event_type ) {
|
||||
if ( $this->current_running ) {
|
||||
update_option( $this->OPT_EVENTS_INLINE, $this->current_running + $event_type );
|
||||
} else {
|
||||
update_option( $this->OPT_EVENTS_INLINE, $event_type );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove event from the waiting line
|
||||
*
|
||||
* @param $event
|
||||
*
|
||||
* @since 1.15
|
||||
* @acces public
|
||||
*/
|
||||
public function remove_event_from_list( $event ) {
|
||||
if ( $event ) {
|
||||
unset( $this->current_running[ $event ] );
|
||||
update_option( $this->OPT_EVENTS_INLINE, $this->current_running );
|
||||
}
|
||||
}
|
||||
}
|
@ -1,84 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace WPScan;
|
||||
|
||||
// Exit if accessed directly.
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Dashboard.
|
||||
*
|
||||
* Used for the dashboard widgets.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Dashboard {
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @param object $parent parent.
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function __construct( $parent ) {
|
||||
$this->parent = $parent;
|
||||
|
||||
add_action( 'wp_dashboard_setup', array( $this, 'add_dashboard_widgets' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the widget
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function add_dashboard_widgets() {
|
||||
if ( ! current_user_can( $this->parent->WPSCAN_ROLE ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
wp_add_dashboard_widget(
|
||||
$this->parent->WPSCAN_DASHBOARD,
|
||||
__( 'WPScan Status', 'wpscan' ),
|
||||
array( $this, 'dashboard_widget_content' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the widget
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function dashboard_widget_content() {
|
||||
$report = $this->parent->get_report();
|
||||
|
||||
if ( ! $this->parent->classes['settings']->api_token_set() ) {
|
||||
echo esc_html( '<div>' . __( 'To use WPScan you have to setup your WPScan API Token.', 'wpscan' ) . '</div>' );
|
||||
return;
|
||||
}
|
||||
|
||||
if ( empty( $report ) ) {
|
||||
echo esc_html( __( 'No Report available', 'wpscan' ) );
|
||||
return;
|
||||
}
|
||||
|
||||
$vulns = $this->parent->classes['report']->get_all_vulnerabilities();
|
||||
|
||||
if ( empty( $vulns ) ) {
|
||||
echo esc_html( __( 'No vulnerabilities found', 'wpscan' ) );
|
||||
}
|
||||
|
||||
echo '<div>';
|
||||
|
||||
foreach ( $vulns as $vuln ) {
|
||||
$vuln = wp_kses( $vuln, array( 'a' => array( 'href' => array() ) ) ); // Only allow a href HTML tags.
|
||||
echo "<div><span class='dashicons dashicons-warning is-red'></span> " . $vuln . "</div><br/>";
|
||||
}
|
||||
|
||||
echo '</div>';
|
||||
}
|
||||
}
|
@ -1,347 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace WPScan;
|
||||
|
||||
// Exit if accessed directly.
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Notification.
|
||||
*
|
||||
* Used for the Notifications logic.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Notification {
|
||||
// Page slug.
|
||||
private $page;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @param object $parent parent.
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function __construct($parent) {
|
||||
$this->parent = $parent;
|
||||
$this->page = 'wpscan_notification';
|
||||
|
||||
add_action( 'admin_init', array( $this, 'admin_init' ) );
|
||||
add_action( 'admin_init', array( $this, 'add_meta_box_notification' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Notification Options
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function admin_init() {
|
||||
$total = $this->parent->get_total();
|
||||
|
||||
register_setting( $this->page, $this->parent->OPT_EMAIL, array( $this, 'sanitize_email' ) );
|
||||
register_setting( $this->page, $this->parent->OPT_INTERVAL, array( $this, 'sanitize_interval' ) );
|
||||
|
||||
$section = $this->page . '_section';
|
||||
|
||||
add_settings_section(
|
||||
$section,
|
||||
null,
|
||||
array( $this, 'introduction' ),
|
||||
$this->page
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
$this->parent->OPT_EMAIL,
|
||||
__( 'E-mail', 'wpscan' ),
|
||||
array( $this, 'field_email' ),
|
||||
$this->page,
|
||||
$section
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
$this->parent->OPT_INTERVAL,
|
||||
__( 'Send Alerts', 'wpscan' ),
|
||||
array( $this, 'field_interval' ),
|
||||
$this->page,
|
||||
$section
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add meta box
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function add_meta_box_notification() {
|
||||
add_meta_box(
|
||||
'wpscan-metabox-notification',
|
||||
__( 'Notification', 'wpscan' ),
|
||||
array( $this, 'do_meta_box_notification' ),
|
||||
'wpscan',
|
||||
'side',
|
||||
'low'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render meta box
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function do_meta_box_notification() {
|
||||
echo '<form action="options.php" method="post">';
|
||||
|
||||
settings_fields( $this->page );
|
||||
|
||||
do_settings_sections( $this->page );
|
||||
|
||||
submit_button();
|
||||
|
||||
echo '</form>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Introduction
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function introduction() {
|
||||
echo '<p>' . __( 'Fill in the options below if you want to be notified by mail about new vulnerabilities. To add multiple e-mail addresses comma separate them.', 'wpscan' ) . '</p>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Email field
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function field_email()
|
||||
{
|
||||
echo sprintf(
|
||||
'<input type="text" name="%s" value="%s" class="regular-text" placeholder="email@domain.com, copy@domain.com">',
|
||||
esc_attr( $this->parent->OPT_EMAIL ),
|
||||
esc_attr( get_option( $this->parent->OPT_EMAIL, '' ) )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Interval field
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function field_interval() {
|
||||
$interval = get_option( $this->parent->OPT_INTERVAL, 'd' );
|
||||
|
||||
echo '<select name="' . $this->parent->OPT_INTERVAL . '">';
|
||||
echo '<option value="o" ' . selected( 'o', $interval, false ) . '>' . __( 'Disabled', 'wpscan' ) . '</option>';
|
||||
echo '<option value="d" ' . selected( 'd', $interval, false ) . '>' . __( 'Daily', 'wpscan' ) . '</option>';
|
||||
echo '<option value="1" ' . selected( 1, $interval, false ) . '>' . __( 'Every Monday', 'wpscan' ) . '</option>';
|
||||
echo '<option value="2" ' . selected( 2, $interval, false ) . '>' . __( 'Every Tuesday', 'wpscan' ) . '</option>';
|
||||
echo '<option value="3" ' . selected( 3, $interval, false ) . '>' . __( 'Every Wednesday', 'wpscan' ) . '</option>';
|
||||
echo '<option value="4" ' . selected( 4, $interval, false ) . '>' . __( 'Every Thursday', 'wpscan' ) . '</option>';
|
||||
echo '<option value="5" ' . selected( 5, $interval, false ) . '>' . __( 'Every Friday', 'wpscan' ) . '</option>';
|
||||
echo '<option value="6" ' . selected( 6, $interval, false ) . '>' . __( 'Every Saturday', 'wpscan' ) . '</option>';
|
||||
echo '<option value="7" ' . selected( 7, $interval, false ) . '>' . __( 'Every Sunday', 'wpscan' ) . '</option>';
|
||||
echo '<option value="m" ' . selected( 'm', $interval, false ) . '>' . __( 'Every Month', 'wpscan' ) . '</option>';
|
||||
echo '</selected>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize email
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function sanitize_email( $value ) {
|
||||
if ( ! empty( $value ) ) {
|
||||
$emails = explode( ',', $value );
|
||||
|
||||
foreach ( $emails as $email ) {
|
||||
if ( ! is_email( trim( $email ) ) ) {
|
||||
add_settings_error( $this->parent->OPT_EMAIL, 'invalid-email', __( 'You have entered an invalid e-mail address.', 'wpscan' ) );
|
||||
$value = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize interval
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function sanitize_interval( $value ) {
|
||||
$allowed_values = array( 'o', 'd', 1, 2, 3, 4, 5, 6, 7, 'm' );
|
||||
|
||||
if ( ! in_array( $value, $allowed_values ) ) {
|
||||
// return default value.
|
||||
return 'd';
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the notification
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function notify() {
|
||||
if ( ! function_exists( 'get_plugins' ) ) {
|
||||
require_once ABSPATH . 'wp-admin/includes/plugin.php';
|
||||
}
|
||||
|
||||
$email = get_option( $this->parent->OPT_EMAIL );
|
||||
$interval = get_option( $this->parent->OPT_INTERVAL, 'd' );
|
||||
|
||||
// Check email or if notifications are disabled.
|
||||
if ( empty( $email ) || 'o' === $interval ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check weekly interval.
|
||||
if ( is_numeric( $interval ) && date( 'N' ) !== $interval ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check monthly interval.
|
||||
if ( $interval === 'm' && date( 'j' ) !== 1 ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Send email.
|
||||
$has_vulnerabilities = false;
|
||||
|
||||
$msg = '<!doctype html><html><head><meta charset="utf-8"></head><body>';
|
||||
$msg .= '<p>' . __( 'Hello,', 'wpscan' ) . '</p>';
|
||||
$msg .= '<p>' . sprintf(__( 'The %s found some vulnerabilities in %s, listed below.', 'wpscan' ), '<a href="https://wordpress.org/plugins/wpscan/">WPScan WordPress security plugin</a>' , '<a href="' . get_bloginfo( 'url' ) . '">' . get_bloginfo( 'name' ) . '</a>' ) . '</p>';
|
||||
|
||||
// WordPress
|
||||
$list = $this->email_vulnerabilities( 'wordpress' , get_bloginfo( 'version' ));
|
||||
|
||||
if ( ! empty( $list ) ) {
|
||||
$has_vulnerabilities = true;
|
||||
|
||||
$msg .= '<p><b>WordPress</b><br>';
|
||||
$msg .= join( '<br>', $list ) . '</p>';
|
||||
}
|
||||
|
||||
// Plugins.
|
||||
foreach ( get_plugins() as $name => $details ) {
|
||||
$slug = $this->parent->get_plugin_slug( $name, $details );
|
||||
$list = $this->email_vulnerabilities( 'plugins', $slug );
|
||||
|
||||
if ( ! empty( $list ) ) {
|
||||
$has_vulnerabilities = true;
|
||||
|
||||
$msg .= '<p><b>' . __( 'Plugin', 'wpscan' ) . ' ' . esc_html( $details['Name'] ) . '</b><br>';
|
||||
$msg .= join( '<br>', $list ) . '</p>';
|
||||
}
|
||||
}
|
||||
|
||||
// Themes.
|
||||
foreach ( wp_get_themes() as $name => $details ) {
|
||||
$slug = $this->parent->get_theme_slug( $name, $details );
|
||||
$list = $this->email_vulnerabilities( 'themes', $slug );
|
||||
|
||||
if ( ! empty( $list ) ) {
|
||||
$has_vulnerabilities = true;
|
||||
|
||||
$msg .= '<p><b>' . __( 'Theme', 'wpscan' ) . ' ' . esc_html( $details['Name'] ) . '</b><br>';
|
||||
$msg .= join( '<br>', $list ) . '</p>';
|
||||
}
|
||||
}
|
||||
|
||||
// Security checks.
|
||||
foreach ( $this->parent->classes['checks/system']->checks as $id => $data ) {
|
||||
$list = $this->email_vulnerabilities( 'security-checks', $id );
|
||||
|
||||
if ( ! empty( $list ) ) {
|
||||
$has_vulnerabilities = true;
|
||||
|
||||
$msg .= '<p><b>' . __( 'Security check', 'wpscan' ) . ' ' . esc_html( $data['instance']->title() ) . '</b><br>';
|
||||
$msg .= join( '<br>', $list ) . '</p>';
|
||||
}
|
||||
}
|
||||
|
||||
$msg .= '<p>' . sprintf(__( 'Found our WPScan security plugin helpful? Please %s', 'wpscan' ), '<a href="https://wordpress.org/support/plugin/wpscan/reviews/#new-post">leave a review.</a></p>');
|
||||
|
||||
$msg .= '<p>' . __( 'Thank you,', 'wpscan' ) . '<br/>' . __( 'The WPScan Team', 'wpscan' ) . '</p>';
|
||||
|
||||
$msg .= '</body></html>';
|
||||
|
||||
if ( $has_vulnerabilities ) {
|
||||
$subject = sprintf(
|
||||
__( '[WPScan Alert] Some vulnerabilities were found in %s!', 'wpscan' ),
|
||||
get_bloginfo( 'name' )
|
||||
);
|
||||
|
||||
$headers = array( 'Content-Type: text/html; charset=UTF-8' );
|
||||
|
||||
wp_mail( $email, $subject, $msg, $headers );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List of vulnerabilities to send by mail
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function email_vulnerabilities( $type, $name ) {
|
||||
$report = $this->parent->get_report()[ $type ];
|
||||
$ignored = $this->parent->get_ignored_vulnerabilities();
|
||||
|
||||
if ( array_key_exists( $name, $report ) ) {
|
||||
$report = $report[ $name ];
|
||||
}
|
||||
|
||||
if ( ! isset( $report['vulnerabilities'] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$list = [];
|
||||
|
||||
foreach ( $report['vulnerabilities'] as $item ) {
|
||||
$id = 'security-checks' === $type ? $item['id'] : $item->id;
|
||||
$title = 'security-checks' === $type ? $item['title'] : $this->parent->get_sanitized_vulnerability_title( $item );
|
||||
|
||||
if ( in_array( $id, $ignored ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( 'security-checks' !== $type ) {
|
||||
$html = '<a href="' . esc_url( 'https://wpscan.com/vulnerability/' . $id ) . '" target="_blank">';
|
||||
$html .= esc_html( $title );
|
||||
$html .= '</a>';
|
||||
} else {
|
||||
$html = esc_html( $title );
|
||||
}
|
||||
|
||||
$list[] = $html;
|
||||
}
|
||||
|
||||
return $list;
|
||||
}
|
||||
}
|
@ -1,912 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace WPScan;
|
||||
|
||||
// Exit if accessed directly.
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Plugin.
|
||||
*
|
||||
* General WPScan plugin logic.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Plugin {
|
||||
// Settings.
|
||||
public $OPT_API_TOKEN = 'wpscan_api_token';
|
||||
public $OPT_SCANNING_INTERVAL = 'wpscan_scanning_interval';
|
||||
public $OPT_SCANNING_TIME = 'wpscan_scanning_time';
|
||||
public $OPT_IGNORE_ITEMS = 'wpscan_ignore_items';
|
||||
public $OPT_DISABLE_CHECKS = 'wpscan_disable_security_checks';
|
||||
|
||||
// Account.
|
||||
public $OPT_ACCOUNT_STATUS = 'wpscan_account_status';
|
||||
|
||||
// Notifications.
|
||||
public $OPT_EMAIL = 'wpscan_mail';
|
||||
public $OPT_INTERVAL = 'wpscan_interval';
|
||||
public $OPT_IGNORED = 'wpscan_ignored';
|
||||
|
||||
// Report.
|
||||
public $OPT_REPORT = 'wpscan_report';
|
||||
public $OPT_ERRORS = 'wpscan_errors';
|
||||
|
||||
// Schedule.
|
||||
public $WPSCAN_SCHEDULE = 'wpscan_schedule';
|
||||
|
||||
// Run All schedule.
|
||||
public $WPSCAN_RUN_ALL = 'wpscan_run_all';
|
||||
|
||||
// Run Security schedule.
|
||||
public $WPSCAN_RUN_SECURITY = 'wpscan_events_inline';
|
||||
|
||||
// Dashboard.
|
||||
public $WPSCAN_DASHBOARD = 'wpscan_dashboard';
|
||||
|
||||
// Transient.
|
||||
public $WPSCAN_TRANSIENT_CRON = 'wpscan_doing_cron';
|
||||
|
||||
// Required minimal role.
|
||||
public $WPSCAN_ROLE = 'manage_options';
|
||||
|
||||
// Plugin path.
|
||||
public $plugin_dir = '';
|
||||
|
||||
// Plugin URI.
|
||||
public $plugin_url = '';
|
||||
|
||||
// Page.
|
||||
public $page_hook = 'toplevel_page_wpscan';
|
||||
|
||||
// Report.
|
||||
public $report;
|
||||
|
||||
// Action fired when an issue is found
|
||||
public $WPSCAN_ISSUE_FOUND = 'wpscan_issue_found';
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->plugin_dir = trailingslashit( str_replace( '\\', '/', dirname( WPSCAN_PLUGIN_FILE ) ) );
|
||||
$this->plugin_url = site_url( str_replace( str_replace( '\\', '/', ABSPATH ), '', $this->plugin_dir ) );
|
||||
|
||||
// Languages.
|
||||
load_plugin_textdomain( 'wpscan', false, $this->plugin_dir . 'languages' );
|
||||
|
||||
// Cache values in memory.
|
||||
$this->report = get_option( $this->OPT_REPORT, array() );
|
||||
$this->ignored_vulnerabilities = get_option( $this->OPT_IGNORED, array() );
|
||||
|
||||
// Actions.
|
||||
add_action( 'admin_menu', array( $this, 'menu' ) );
|
||||
add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue' ) );
|
||||
add_action( 'admin_bar_menu', array( $this, 'admin_bar' ), 65 );
|
||||
add_action( $this->WPSCAN_SCHEDULE, array( $this, 'check_now' ) );
|
||||
add_action( $this->WPSCAN_RUN_ALL, array( $this, 'check_now' ) );
|
||||
add_action( 'in_admin_header', array( $this, 'deactivate_screen' ) );
|
||||
|
||||
if ( defined( 'WPSCAN_API_TOKEN' ) ) {
|
||||
add_action( 'admin_init', array( $this, 'api_token_from_constant' ) );
|
||||
}
|
||||
|
||||
// Filters.
|
||||
add_filter( 'plugin_action_links_' . plugin_basename( WPSCAN_PLUGIN_FILE ), array( $this, 'add_action_links' ) );
|
||||
|
||||
// Micro apps (modules).
|
||||
$this->classes['report'] = new Report( $this );
|
||||
$this->classes['settings'] = new Settings( $this );
|
||||
$this->classes['account'] = new Account( $this );
|
||||
$this->classes['notification'] = new Notification( $this );
|
||||
$this->classes['summary'] = new Summary( $this );
|
||||
$this->classes['ignoreVulnerabilities'] = new ignoreVulnerabilities( $this );
|
||||
$this->classes['dashboard'] = new Dashboard( $this );
|
||||
$this->classes['sitehealth'] = new SiteHealth( $this );
|
||||
$this->classes['checks/system'] = new Checks\System( $this );
|
||||
}
|
||||
|
||||
/**
|
||||
* Plugin Loaded
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function loaded() {
|
||||
load_plugin_textdomain( 'wpscan', false, $this->plugin_dir . 'languages' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Activate actions. Runs when the plugin is activated.
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function activate() {
|
||||
$this->delete_doing_cron_transient();
|
||||
}
|
||||
|
||||
/**
|
||||
* Deactivate actions
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function deactivate() {
|
||||
delete_option( $this->OPT_SCANNING_INTERVAL );
|
||||
|
||||
delete_option( $this->OPT_SCANNING_TIME );
|
||||
|
||||
as_unschedule_all_actions( $this->WPSCAN_SCHEDULE );
|
||||
}
|
||||
|
||||
/**
|
||||
* Deactivate screen
|
||||
*
|
||||
* @return void
|
||||
* @since 1.14.0
|
||||
* @access public
|
||||
*/
|
||||
public function deactivate_screen() {
|
||||
global $pagenow;
|
||||
|
||||
if ( 'plugins.php' === $pagenow ) {
|
||||
include_once plugin_dir_path( WPSCAN_PLUGIN_FILE ) . 'views/deactivate.php';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Use the global constant WPSCAN_API_TOKEN if defined.
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @example define('WPSCAN_API_TOKEN', 'xxx');
|
||||
*
|
||||
*/
|
||||
public function api_token_from_constant() {
|
||||
if ( get_option( $this->OPT_API_TOKEN ) !== WPSCAN_API_TOKEN ) {
|
||||
$sanitize = $this->classes['settings']->sanitize_api_token( WPSCAN_API_TOKEN );
|
||||
|
||||
if ( $sanitize ) {
|
||||
update_option( $this->OPT_API_TOKEN, WPSCAN_API_TOKEN );
|
||||
} else {
|
||||
delete_option( $this->OPT_API_TOKEN );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register Admin Scripts
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function admin_enqueue( $hook ) {
|
||||
global $pagenow;
|
||||
$screen = get_current_screen();
|
||||
|
||||
if ( $hook === $this->page_hook || 'dashboard' === $screen->id ) {
|
||||
wp_enqueue_style(
|
||||
'wpscan',
|
||||
plugins_url( 'assets/css/style.css', WPSCAN_PLUGIN_FILE ),
|
||||
array(),
|
||||
$this->wpscan_plugin_version()
|
||||
);
|
||||
}
|
||||
|
||||
if ( $hook === $this->page_hook ) {
|
||||
wp_enqueue_script( 'common' );
|
||||
wp_enqueue_script( 'wp-lists' );
|
||||
wp_enqueue_script( 'postbox' );
|
||||
|
||||
wp_enqueue_script(
|
||||
'wpscan',
|
||||
plugins_url( 'assets/js/scripts.js', WPSCAN_PLUGIN_FILE ),
|
||||
array( 'jquery' ),
|
||||
$this->wpscan_plugin_version()
|
||||
);
|
||||
|
||||
|
||||
wp_enqueue_script(
|
||||
'wpscan-download-report',
|
||||
plugins_url( 'assets/js/download-report.js', WPSCAN_PLUGIN_FILE ),
|
||||
array( 'pdfmake' ),
|
||||
$this->wpscan_plugin_version()
|
||||
);
|
||||
|
||||
|
||||
wp_enqueue_script(
|
||||
'pdfmake',
|
||||
plugins_url( 'assets/vendor/pdfmake/pdfmake.min.js', WPSCAN_PLUGIN_FILE ),
|
||||
array( 'wpscan' ),
|
||||
$this->wpscan_plugin_version()
|
||||
);
|
||||
|
||||
wp_enqueue_script(
|
||||
'wpscan-download-report-fonts',
|
||||
plugins_url( 'assets/vendor/pdfmake/vfs_fonts.js', WPSCAN_PLUGIN_FILE ),
|
||||
array( 'wpscan' ),
|
||||
$this->wpscan_plugin_version()
|
||||
);
|
||||
|
||||
$localized = array(
|
||||
'ajaxurl' => admin_url( 'admin-ajax.php' ),
|
||||
'action_check' => 'wpscan_check_now',
|
||||
'action_security_check' => 'wpscan_security_check_now',
|
||||
'action_cron' => $this->WPSCAN_TRANSIENT_CRON,
|
||||
'ajax_nonce' => wp_create_nonce( 'wpscan' ),
|
||||
'doing_cron' => false !== as_next_scheduled_action( $this->WPSCAN_RUN_ALL ) ? 'YES' : 'NO',
|
||||
'doing_security_cron' => get_option( $this->WPSCAN_RUN_SECURITY ),
|
||||
'running' => esc_html__( 'Running', 'wpscan' ),
|
||||
'not_running' => esc_html__( 'Run', 'wpscan' ),
|
||||
);
|
||||
|
||||
wp_localize_script( 'wpscan', 'wpscan', $localized );
|
||||
}
|
||||
|
||||
if ( 'plugins.php' === $pagenow ) {
|
||||
wp_enqueue_style(
|
||||
'wpscan-deactivate',
|
||||
plugins_url( 'assets/css/deactivate.css', WPSCAN_PLUGIN_FILE ),
|
||||
array(),
|
||||
$this->wpscan_plugin_version()
|
||||
);
|
||||
|
||||
wp_enqueue_script(
|
||||
'wpscan-deactivate',
|
||||
plugins_url( 'assets/js/deactivate.js', WPSCAN_PLUGIN_FILE ),
|
||||
array( 'jquery' ),
|
||||
$this->wpscan_plugin_version()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the latest report
|
||||
*
|
||||
* @return array|bool
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function get_report() {
|
||||
if ( ! empty( $this->report ) ) {
|
||||
return ( $this->report );
|
||||
}
|
||||
|
||||
return get_option( $this->OPT_REPORT, array() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the latest report
|
||||
*
|
||||
* @return array|bool
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function get_ignored_vulnerabilities() {
|
||||
if ( ! empty( $this->ignored_vulnerabilities ) ) {
|
||||
return ( $this->ignored_vulnerabilities );
|
||||
}
|
||||
|
||||
return get_option( $this->OPT_IGNORED, array() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the total of vulnerabilities found or -1 if errors
|
||||
*
|
||||
* @return int
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function get_total() {
|
||||
$report = get_option( $this->OPT_REPORT );
|
||||
|
||||
if ( empty( $report ) ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$total = 0;
|
||||
|
||||
foreach ( array( 'wordpress', 'themes', 'plugins', 'security-checks' ) as $type ) {
|
||||
if ( isset( $report[ $type ] ) ) {
|
||||
if ( isset( $report[ $type ]['total'] ) ) {
|
||||
unset( $report[ $type ]['total'] );
|
||||
}
|
||||
|
||||
foreach ( $report[ $type ] as $slug => $item ) {
|
||||
$p = $report[ $type ][ $slug ];
|
||||
|
||||
if ( isset( $p['vulnerabilities'] ) && is_array( $p['vulnerabilities'] ) ) {
|
||||
$total += count( $p['vulnerabilities'] );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $total;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the total of vulnerabilities found but not ignored
|
||||
*
|
||||
* @return int
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function get_total_not_ignored() {
|
||||
$report = $this->get_report();
|
||||
$ignored = get_option( $this->OPT_IGNORED, array() );
|
||||
|
||||
$total = $this->get_total();
|
||||
|
||||
$types = array( 'wordpress', 'plugins', 'themes', 'security-checks' );
|
||||
|
||||
foreach ( $types as $type ) {
|
||||
if ( isset( $report[ $type ] ) ) {
|
||||
foreach ( $report[ $type ] as $item ) {
|
||||
if ( empty( $item['vulnerabilities'] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ( $item['vulnerabilities'] as $vuln ) {
|
||||
$id = 'security-checks' === $type ? $vuln['id'] : $vuln->id;
|
||||
|
||||
if ( in_array( $id, $ignored, true ) ) {
|
||||
-- $total;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $total;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a menu on Tools section
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function menu() {
|
||||
$total = $this->get_total_not_ignored();
|
||||
$count = $total > 0 ? ' <span class="update-plugins">' . $total . '</span>' : null;
|
||||
|
||||
add_menu_page(
|
||||
'WPScan',
|
||||
'WPScan' . $count,
|
||||
$this->WPSCAN_ROLE,
|
||||
'wpscan',
|
||||
array( $this->classes['report'], 'page' ),
|
||||
plugin_dir_url( dirname( __FILE__ ) ) . 'assets/svg/menu-icon.svg',
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Include a shortcut on Plugins Page
|
||||
*
|
||||
* @param array $links - Array of links provided by the filter
|
||||
*
|
||||
* @access public
|
||||
* @return array
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public function add_action_links( $links ) {
|
||||
$links[] = '<a href="' . admin_url( 'admin.php?page=wpscan' ) . '">' . __( 'View' ) . '</a>';
|
||||
|
||||
return $links;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the WPScan plugin version.
|
||||
*
|
||||
* @return string
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function wpscan_plugin_version() {
|
||||
if ( ! function_exists( 'get_plugin_data' ) ) {
|
||||
require_once ABSPATH . 'wp-admin/includes/plugin.php';
|
||||
}
|
||||
|
||||
return get_plugin_data( $this->plugin_dir . 'wpscan.php' )['Version'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get information from the API
|
||||
*
|
||||
* @return object|int the JSON object or the response code.
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function api_get( $endpoint, $api_token = null ) {
|
||||
if ( empty( $api_token ) ) {
|
||||
$api_token = get_option( $this->OPT_API_TOKEN );
|
||||
}
|
||||
|
||||
// Make sure endpoint starts with a slash.
|
||||
if ( substr( $endpoint, 0, 1 ) !== '/' ) {
|
||||
$endpoint = '/' . $endpoint;
|
||||
}
|
||||
|
||||
$args = array(
|
||||
'headers' => array(
|
||||
'Authorization' => 'Token token=' . $api_token,
|
||||
'user-agent' => 'WordPress/' . get_bloginfo( 'version' ) . '; ' . home_url() . ' WPScan/' . $this->wpscan_plugin_version(),
|
||||
),
|
||||
);
|
||||
|
||||
// Hook before the request.
|
||||
//do_action( 'wpscan/api/get/before', $endpoint );
|
||||
|
||||
// Start the request.
|
||||
$response = wp_remote_get( WPSCAN_API_URL . $endpoint, $args );
|
||||
$code = wp_remote_retrieve_response_code( $response );
|
||||
|
||||
// Hook after the request.
|
||||
//do_action( 'wpscan/api/get/after', $endpoint, $response );
|
||||
|
||||
if ( 200 === $code ) {
|
||||
return json_decode( wp_remote_retrieve_body( $response ) );
|
||||
} else {
|
||||
$errors = get_option( $this->OPT_ERRORS, array() );
|
||||
|
||||
switch ( $code ) {
|
||||
case 401:
|
||||
array_push( $errors, __( 'Your API Token expired', 'wpscan' ) );
|
||||
break;
|
||||
case 403:
|
||||
array_push( $errors, __( 'You have entered an invalid API Token', 'wpscan' ) );
|
||||
break;
|
||||
case 404:
|
||||
// We don't have the plugin/theme, do nothing.
|
||||
break;
|
||||
case 429:
|
||||
array_push( $errors, sprintf( '%s <a href="%s" target="_blank">%s</a>.', __( 'You hit your API limit. To increase your daily API limit please upgrade via your ', 'wpscan' ), WPSCAN_PROFILE_URL, __( 'WPScan profile page', 'wpscan' ) ) );
|
||||
break;
|
||||
case 500:
|
||||
array_push( $errors, sprintf( '%s <a href="%s" target="_blank">%s</a>', __( 'There seems to be a problem with the WPScan API. Status: 500. Check the ', 'wpscan' ), WPSCAN_STATUS_URL, __( 'API Status', 'wpscan' ) ) );
|
||||
break;
|
||||
case 502:
|
||||
array_push( $errors, sprintf( '%s <a href="%s" target="_blank">%s</a>', __( 'There seems to be a problem with the WPScan API. Status: 502. Check the ', 'wpscan' ), WPSCAN_STATUS_URL, __( 'API Status', 'wpscan' ) ) );
|
||||
break;
|
||||
case '':
|
||||
array_push( $errors, sprintf( '%s <a href="%s" target="_blank">%s</a>', __( 'We were unable to connect to the WPScan API. Check the ', 'wpscan' ), WPSCAN_STATUS_URL, __( 'API Status', 'wpscan' ) ) );
|
||||
break;
|
||||
default:
|
||||
array_push( $errors, sprintf( '%s <a href="%s" target="_blank">%s</a>.', __( 'We received an unknown response from the API. Status: ' . esc_html( $code ), 'wpscan' ), WPSCAN_STATUS_URL, __( 'Check API Status', 'wpscan' ) ) );
|
||||
break;
|
||||
}
|
||||
|
||||
// Save the errors.
|
||||
update_option( $this->OPT_ERRORS, array_unique( $errors ) );
|
||||
}
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to start checking right now
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function check_now() {
|
||||
if ( get_transient( $this->WPSCAN_TRANSIENT_CRON ) || empty( get_option( $this->OPT_API_TOKEN ) ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Start cron job and set timeout.
|
||||
set_transient( $this->WPSCAN_TRANSIENT_CRON, time(), 60 );
|
||||
|
||||
$this->verify();
|
||||
|
||||
delete_transient( $this->WPSCAN_TRANSIENT_CRON );
|
||||
|
||||
// Notify by mail when solicited.
|
||||
$this->classes['notification']->notify();
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to verify on WpScan Database for vulnerabilities
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function verify() {
|
||||
$ignored = get_option( $this->OPT_IGNORE_ITEMS );
|
||||
|
||||
$ignored = wp_parse_args(
|
||||
$ignored,
|
||||
array(
|
||||
'plugins' => array(),
|
||||
'themes' => array(),
|
||||
)
|
||||
);
|
||||
|
||||
// Reset errors.
|
||||
update_option( $this->OPT_ERRORS, array() );
|
||||
update_option( $this->classes['checks/system']->OPT_FATAL_ERRORS, array() );
|
||||
|
||||
// Plugins.
|
||||
$this->report['plugins'] = $this->verify_plugins( $ignored['plugins'] );
|
||||
|
||||
// Themes.
|
||||
$this->report['themes'] = $this->verify_themes( $ignored['themes'] );
|
||||
|
||||
// WordPress.
|
||||
if ( ! isset( $ignored['wordpress'] ) ) {
|
||||
$this->report['wordpress'] = $this->verify_wordpress();
|
||||
} else {
|
||||
$this->report['wordpress'] = array();
|
||||
}
|
||||
|
||||
// Security checks.
|
||||
if ( get_option( $this->OPT_DISABLE_CHECKS, array() ) !== '1' ) {
|
||||
$this->report['security-checks'] = array();
|
||||
|
||||
foreach ( $this->classes['checks/system']->checks as $id => $data ) {
|
||||
$data['instance']->perform();
|
||||
$this->report['security-checks'][ $id ]['vulnerabilities'] = array();
|
||||
|
||||
if ( $data['instance']->vulnerabilities ) {
|
||||
$this->report['security-checks'][ $id ]['vulnerabilities'] = $data['instance']->get_vulnerabilities();
|
||||
|
||||
$this->maybe_fire_issue_found_action( 'security-check', $id, $this->report['security-checks'][ $id ] );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Caching.
|
||||
$this->report['cache'] = strtotime( current_time( 'mysql' ) );
|
||||
|
||||
// Saving.
|
||||
update_option( $this->OPT_REPORT, $this->report, true );
|
||||
|
||||
// Updates account status (API calls etc).
|
||||
$this->classes['account']->update_account_status();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fires the wpscan_issue_found action if needed
|
||||
*
|
||||
* @param string $type - The affected component type: plugin, theme, WordPress or security-check
|
||||
* @param string $slug - The affected component slug.
|
||||
* For WordPress, it will be the version (ie 5.5.3)
|
||||
* For security-checks, it will be the id of the check, ie xmlrpc-enabled
|
||||
* @param array $details - An array containing some keys, such as vulnerabilities
|
||||
* @param array additional_details - An array with the plugin details, such as Version etc
|
||||
**@since 1.14.0
|
||||
*
|
||||
*/
|
||||
public function maybe_fire_issue_found_action( $type, $slug, $details, $additional_details = array() ) {
|
||||
if ( ! count( $details['vulnerabilities'] ) > 0 ) {
|
||||
return;
|
||||
}
|
||||
|
||||
do_action( $this->WPSCAN_ISSUE_FOUND, $type, $slug, $details, $additional_details );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check plugins for any known vulnerabilities
|
||||
*
|
||||
* @param array $ignored - An array of plugins slug to ignore
|
||||
*
|
||||
* @access public
|
||||
* @return array
|
||||
* @since 1.0.0
|
||||
*
|
||||
*/
|
||||
public function verify_plugins( $ignored ) {
|
||||
$plugins = array();
|
||||
$ignored[] = 'latest'; // ignore the plugin with the slug 'latest' as this conflicts with our API.
|
||||
|
||||
if ( ! function_exists( 'get_plugins' ) ) {
|
||||
require_once ABSPATH . 'wp-admin/includes/plugin.php';
|
||||
}
|
||||
|
||||
foreach ( get_plugins() as $name => $details ) {
|
||||
$slug = $this->get_plugin_slug( $name, $details );
|
||||
|
||||
if ( isset( $ignored[ $slug ] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$result = $this->api_get( '/plugins/' . $slug );
|
||||
|
||||
if ( is_object( $result ) ) {
|
||||
$plugins[ $slug ]['vulnerabilities'] = $this->get_vulnerabilities( $result, $details['Version'] );
|
||||
|
||||
if ( isset( $result->$slug->closed ) ) {
|
||||
$plugins[ $slug ]['closed'] = is_object( $result->$slug->closed ) ? true : false;
|
||||
} else {
|
||||
$plugins[ $slug ]['closed'] = false;
|
||||
}
|
||||
|
||||
$this->maybe_fire_issue_found_action( 'plugin', $slug, $plugins[ $slug ], $details );
|
||||
} else {
|
||||
if ( 404 === $result ) {
|
||||
$plugins[ $slug ]['not_found'] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $plugins;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check themes for any known vulnerabilities
|
||||
*
|
||||
* @param array $ignored - An array of themes slug to ignore.
|
||||
*
|
||||
* @access public
|
||||
* @return array
|
||||
* @since 1.0.0
|
||||
*
|
||||
*/
|
||||
public function verify_themes( $ignored ) {
|
||||
$themes = array();
|
||||
$ignored[] = 'latest'; // ignore the theme with the slug 'latest' as this conflicts with our API.
|
||||
|
||||
if ( ! function_exists( 'wp_get_themes' ) ) {
|
||||
require_once ABSPATH . 'wp-admin/includes/theme.php';
|
||||
}
|
||||
|
||||
$filter = array(
|
||||
'errors' => null,
|
||||
'allowed' => null,
|
||||
'blog_id' => 0,
|
||||
);
|
||||
|
||||
foreach ( wp_get_themes( $filter ) as $name => $details ) {
|
||||
$slug = $this->get_theme_slug( $name, $details );
|
||||
|
||||
if ( isset( $ignored[ $slug ] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$result = $this->api_get( '/themes/' . $slug );
|
||||
|
||||
if ( is_object( $result ) ) {
|
||||
$themes[ $slug ]['vulnerabilities'] = $this->get_vulnerabilities( $result, $details['Version'] );
|
||||
|
||||
if ( isset( $result->$slug->closed ) ) {
|
||||
$themes[ $slug ]['closed'] = is_object( $result->$slug->closed ) ? true : false;
|
||||
} else {
|
||||
$themes[ $slug ]['closed'] = false;
|
||||
}
|
||||
|
||||
$this->maybe_fire_issue_found_action( 'theme', $slug, $themes[ $slug ], $details );
|
||||
} else {
|
||||
if ( 404 === $result ) {
|
||||
$themes[ $slug ]['not_found'] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $themes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check WordPress for any known vulnerabilities.
|
||||
*
|
||||
* @return array
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function verify_wordpress() {
|
||||
$wordpress = array();
|
||||
|
||||
$version = get_bloginfo( 'version' );
|
||||
$result = $this->api_get( '/wordpresses/' . str_replace( '.', '', $version ) );
|
||||
|
||||
if ( is_object( $result ) ) {
|
||||
$wordpress[ $version ]['vulnerabilities'] = $this->get_vulnerabilities( $result, $version );
|
||||
|
||||
$this->maybe_fire_issue_found_action( 'WordPress', $version, $wordpress[ $version ] );
|
||||
}
|
||||
|
||||
return $wordpress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter vulnerability list from WPScan
|
||||
*
|
||||
* @param array $data - Report data for the element to check.
|
||||
* @param string $version - Installed version.
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
* @since 1.0.0
|
||||
*
|
||||
*/
|
||||
public function get_vulnerabilities( $data, $version ) {
|
||||
$list = array();
|
||||
$key = key( $data );
|
||||
|
||||
if ( empty( $data->$key->vulnerabilities ) ) {
|
||||
return $list;
|
||||
}
|
||||
|
||||
// Trim and remove potential leading 'v'.
|
||||
$version = ltrim( trim( $version ), 'v' );
|
||||
|
||||
foreach ( $data->$key->vulnerabilities as $item ) {
|
||||
if ( $item->fixed_in ) {
|
||||
if ( version_compare( $version, $item->fixed_in, '<' ) ) {
|
||||
$list[] = $item;
|
||||
}
|
||||
} else {
|
||||
$list[] = $item;
|
||||
}
|
||||
}
|
||||
|
||||
return $list;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get vulnerability title.
|
||||
*
|
||||
* @param string $vulnerability - element array.
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
* @since 1.0.0
|
||||
*
|
||||
*/
|
||||
public function get_sanitized_vulnerability_title( $vulnerability ) {
|
||||
$title = esc_html( $vulnerability->title ) . ' - ';
|
||||
|
||||
$title .= empty( $vulnerability->fixed_in )
|
||||
? __( 'Not fixed', 'wpscan' )
|
||||
: sprintf( __( 'Fixed in version %s', 'wpscan' ), esc_html( $vulnerability->fixed_in ) );
|
||||
|
||||
return $title;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the plugin slug for the given name
|
||||
*
|
||||
* @param string $name - plugin name "folder/file.php" or "hello.php".
|
||||
* @param string $details details.
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
* @since 1.0.0
|
||||
*
|
||||
*/
|
||||
public function get_plugin_slug( $name, $details ) {
|
||||
$name = $this->get_name( $name );
|
||||
$name = $this->get_real_slug( $name, $details['PluginURI'] );
|
||||
|
||||
return sanitize_title( $name );
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the theme slug for the given name.
|
||||
*
|
||||
* @param string $name - plugin name "folder/file.php" or "hello.php".
|
||||
* @param string $details details.
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
* @since 1.0.0
|
||||
*
|
||||
*/
|
||||
public function get_theme_slug( $name, $details ) {
|
||||
$name = $this->get_name( $name );
|
||||
$name = $this->get_real_slug( $name, $details['ThemeURI'] );
|
||||
|
||||
return sanitize_title( $name );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the plugin/theme name
|
||||
*
|
||||
* @param string $name - plugin name "folder/file.php" or "hello.php".
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
* @since 1.0.0
|
||||
*
|
||||
*/
|
||||
private function get_name( $name ) {
|
||||
return strstr( $name, '/' ) ? dirname( $name ) : $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get plugin/theme slug.
|
||||
*
|
||||
* The name returned by get_plugins or get_themes is not always the real slug.
|
||||
* If the pluginURI is a WordPress url, we take the slug from there.
|
||||
* this also fixes folder renames on plugins if the readme is correct.
|
||||
*
|
||||
* @param string $name - asset name from get_plugins or wp_get_themes.
|
||||
* @param string $url - either the value or ThemeURI or PluginURI.
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
* @since 1.0.0
|
||||
*
|
||||
*/
|
||||
private function get_real_slug( $name, $url ) {
|
||||
$slug = $name;
|
||||
$match = preg_match( '/https?:\/\/wordpress\.org\/(?:extend\/)?(?:plugins|themes)\/([^\/]+)\/?/', $url, $matches );
|
||||
|
||||
if ( 1 === $match ) {
|
||||
$slug = $matches[1];
|
||||
}
|
||||
|
||||
return sanitize_title( $slug );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a shortcut on Admin Bar to show the total of vulnerabilities found.
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function admin_bar( $wp_admin_bar ) {
|
||||
if ( ! current_user_can( $this->WPSCAN_ROLE ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$total = $this->get_total_not_ignored();
|
||||
|
||||
if ( $total > 0 ) {
|
||||
$args = array(
|
||||
'id' => 'wpscan',
|
||||
'title' => '<span class="ab-icon dashicons-shield"></span><span class="ab-label">' . $total . '</span>',
|
||||
'href' => admin_url( 'admin.php?page=wpscan' ),
|
||||
'meta' => array(
|
||||
'title' => sprintf( _n( '%d vulnerability found', '%d vulnerabilities found', $total, 'wpscan' ), $total ),
|
||||
),
|
||||
);
|
||||
|
||||
$wp_admin_bar->add_node( $args );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if interval scanning is disabled
|
||||
*
|
||||
* @return bool
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @example define('WPSCAN_DISABLE_SCANNING_INTERVAL', true);
|
||||
*
|
||||
*/
|
||||
public function is_interval_scanning_disabled() {
|
||||
if ( defined( 'WPSCAN_DISABLE_SCANNING_INTERVAL' ) ) {
|
||||
return WPSCAN_DISABLE_SCANNING_INTERVAL;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete doing_cron transient, as they could hang in older versions
|
||||
*
|
||||
* @return void
|
||||
* @since 1.12.2
|
||||
* @access public
|
||||
*/
|
||||
public function delete_doing_cron_transient() {
|
||||
delete_transient( $this->WPSCAN_TRANSIENT_CRON );
|
||||
}
|
||||
}
|
@ -1,368 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace WPScan;
|
||||
|
||||
// Exit if accessed directly.
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Report.
|
||||
*
|
||||
* Generates the main report.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Report
|
||||
{
|
||||
// Page slug.
|
||||
public $page;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @param object $parent parent.
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function __construct( $parent ) {
|
||||
$this->parent = $parent;
|
||||
$this->page = 'wpscan';
|
||||
|
||||
add_action( 'admin_menu', array( $this, 'menu' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin menu
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function menu() {
|
||||
$title = __( 'Report', 'wpscan' );
|
||||
|
||||
add_submenu_page(
|
||||
'wpscan',
|
||||
$title,
|
||||
$title,
|
||||
$this->parent->WPSCAN_ROLE,
|
||||
$this->page,
|
||||
array( $this, 'page' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render report page
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function page() {
|
||||
include $this->parent->plugin_dir . '/views/report.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get vulnerability status based on fixed_in
|
||||
*
|
||||
* @since 1.15.2
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function status( $vulnerability ) {
|
||||
return empty( $vulnerability->fixed_in )
|
||||
? __( 'We are not aware of a fix for this vulnerability.', 'wpscan' )
|
||||
: sprintf( __( 'This vulnerability was fixed in version %s. We recommend that you update as soon as possible.', 'wpscan' ), esc_html( $vulnerability->fixed_in ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* HTML markup for the vulnerability details
|
||||
*
|
||||
* @since 1.15.2
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function vulnerability_output( $vulnerability ) {
|
||||
$html = '<div class="vulnerability">';
|
||||
$html .= '<p class="vulnerability-title"><b>' . esc_html( $vulnerability->title ) . '</b></p>';
|
||||
$html .= '<p class="vulnerability-status">' . $this->status( $vulnerability ) . '</p>';
|
||||
$html .= $this->vulnerability_severity( $vulnerability );
|
||||
$html .= '<br /><p class="vulnerability-link"><a href="' . esc_url( 'https://wpscan.com/vulnerability/' . $vulnerability->id ) . '" target="_blank">Click here for further details</a></p>';
|
||||
$html .= '</div>';
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* List vulnerabilities on screen
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $type - Type of report: WordPress, plugins, themes.
|
||||
* @param string $name - key name of the element.
|
||||
*
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function list_api_vulnerabilities( $type, $name ) {
|
||||
$report = $this->parent->get_report();
|
||||
$ignored = $this->parent->get_ignored_vulnerabilities();
|
||||
|
||||
$null_text = __( 'No known vulnerabilities found to affect this version', 'wpscan' );
|
||||
$not_checked_text = __( 'Not checked yet. Click the Run All button to run a scan', 'wpscan' );
|
||||
|
||||
if ( empty( $report ) || ! isset( $report[ $type ] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$report = $report[ $type ];
|
||||
|
||||
if ( array_key_exists( $name, $report ) ) {
|
||||
$report = $report[ $name ];
|
||||
} else {
|
||||
echo esc_html( $not_checked_text );
|
||||
return;
|
||||
}
|
||||
|
||||
if ( isset( $report['vulnerabilities'] ) ) {
|
||||
$list = array();
|
||||
|
||||
usort( $report['vulnerabilities'], array( 'self', 'sort_vulnerabilities' ) );
|
||||
|
||||
foreach ( $report['vulnerabilities'] as $vulnerability ) {
|
||||
$id = 'security-checks' === $type ? $vulnerability['id'] : $vulnerability->id;
|
||||
|
||||
if ( in_array( $id, $ignored, true ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$list[] = $this->vulnerability_output( $vulnerability );
|
||||
}
|
||||
|
||||
echo empty( $list ) ? $null_text : join( '<br>', $list );
|
||||
|
||||
} else {
|
||||
echo esc_html( $null_text );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List security check vulnerabilities in the report.
|
||||
* This should be merged with the list_api_vulnerabilities() function,
|
||||
* in the future, if anyone can figure out how...
|
||||
*
|
||||
* @param object $check - The check instance.
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
* @since 1.0.0
|
||||
*
|
||||
*/
|
||||
public function list_security_check_vulnerabilities( $instance ) {
|
||||
$vulnerabilities = $instance->get_vulnerabilities();
|
||||
$count = $instance->get_vulnerabilities_count();
|
||||
$ignored = $this->parent->get_ignored_vulnerabilities();
|
||||
|
||||
$not_checked_text = __( 'Not checked yet. Click the Run button to run a scan', 'wpscan' );
|
||||
|
||||
if ( ! isset( $vulnerabilities ) ) {
|
||||
echo esc_html( $not_checked_text );
|
||||
} elseif ( empty( $vulnerabilities ) || 0 === $count ) {
|
||||
echo esc_html( $instance->success_message() );
|
||||
} else {
|
||||
$list = array();
|
||||
|
||||
foreach ( $vulnerabilities as $vulnerability ) {
|
||||
if ( in_array( $vulnerability['id'], $ignored, true ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$html = "<div class='vulnerability'>";
|
||||
$html .= "<p class='vulnerability-title'>" . wp_kses( $vulnerability['title'], array( 'a' => array( 'href' => array() ) ) ) . '</p><br />';
|
||||
$html .= "<p class='vulnerability-severity'>";
|
||||
$html .= "<span class='wpscan-" . esc_attr( $vulnerability['severity'] ) . "'>" . esc_html( $vulnerability['severity'] ) ." Severity</span>";
|
||||
$html .= '</p>';
|
||||
$html .= "<br /><br /><p class='vulnerability-link'><a href='" . esc_url( $vulnerability['remediation_url'] ) . "' target='_blank'>Click here for further details</a></p>";
|
||||
$html .= '</div>';
|
||||
|
||||
$list[] = $html;
|
||||
}
|
||||
|
||||
echo join( '<br>', $list );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sort vulnerabilities by severity
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return int
|
||||
*/
|
||||
public function sort_vulnerabilities( $a, $b ) {
|
||||
$a = isset( $a->cvss->score ) ? intval( $a->cvss->score ) : 0;
|
||||
$b = isset( $b->cvss->score ) ? intval( $b->cvss->score ) : 0;
|
||||
|
||||
return $b > $a ? 1 : -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vulnerability severity
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function vulnerability_severity( $vulnerability ) {
|
||||
$plan = $this->parent->classes['account']->get_account_status()['plan'];
|
||||
|
||||
if ( 'enterprise' !== $plan ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$html = "<div class='vulnerability-severity'>";
|
||||
|
||||
if ( isset( $vulnerability->cvss->severity ) ) {
|
||||
$severity = $vulnerability->cvss->severity;
|
||||
$html .= "<span class='wpscan-" . esc_attr( $severity ) . "'>" . esc_html( $severity ) . ' Severity</span>';
|
||||
}
|
||||
|
||||
$html .= '</div>';
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the plugin/theme is closed
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return boolean
|
||||
*/
|
||||
public function is_item_closed( $type, $name ) {
|
||||
$report = $this->parent->get_report();
|
||||
|
||||
if ( empty( $report ) || ! isset( $report[ $type ] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$report = $report[ $type ];
|
||||
|
||||
if ( array_key_exists( $name, $report ) ) {
|
||||
$report = $report[ $name ];
|
||||
}
|
||||
|
||||
return isset( $report['closed'] ) ? $report['closed'] : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all vulnerabilities
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function get_all_vulnerabilities() {
|
||||
$ret = array();
|
||||
$report = $this->parent->get_report();
|
||||
$ignored = $this->parent->get_ignored_vulnerabilities();
|
||||
|
||||
$types = array( 'wordpress', 'plugins', 'themes', 'security-checks' );
|
||||
|
||||
foreach ( $types as $type ) {
|
||||
if ( isset( $report[ $type ] ) ) {
|
||||
|
||||
foreach ( $report[ $type ] as $item ) {
|
||||
if ( isset( $item['vulnerabilities'] ) ) {
|
||||
foreach ( $item['vulnerabilities'] as $vuln ) {
|
||||
$id = 'security-checks' === $type ? $vuln['id'] : $vuln->id;
|
||||
$title = 'security-checks' === $type ? $vuln['title'] : $this->parent->get_sanitized_vulnerability_title( $vuln );
|
||||
|
||||
if ( in_array( $id, $ignored, true ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$ret[] = $title;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get item non-ignored vulnerabilities count
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $type - Type of report: WordPress, plugins, themes.
|
||||
* @param string $name - key name of the element.
|
||||
*
|
||||
* @access public
|
||||
* @return int|null
|
||||
*/
|
||||
public function get_item_vulnerabilities_count( $type, $name ) {
|
||||
$report = $this->parent->get_report();
|
||||
$ignored = $this->parent->get_ignored_vulnerabilities();
|
||||
|
||||
if ( empty( $report ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ( isset( $report[ $type ] ) && array_key_exists( $name, $report[ $type ] ) ) {
|
||||
$report = $report[ $type ][ $name ];
|
||||
}
|
||||
|
||||
foreach ( $report['vulnerabilities'] as $key => &$item ) {
|
||||
$id = 'security-checks' === $type ? $item['id'] : $item->id;
|
||||
|
||||
if ( in_array( $id, $ignored, true ) ) {
|
||||
unset( $report['vulnerabilities'][ $key ] );
|
||||
}
|
||||
}
|
||||
|
||||
return count( $report['vulnerabilities'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Show status icons: checked, attention and error
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $type - Type of report: WordPress, plugins, themes.
|
||||
* @param string $name - key name of the element.
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function get_status( $type, $name ) {
|
||||
$report = $this->parent->get_report();
|
||||
$ignored = $this->parent->get_ignored_vulnerabilities();
|
||||
|
||||
if ( empty( $report ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ( isset( $report[ $type ] ) && array_key_exists( $name, $report[ $type ] ) ) {
|
||||
$report = $report[ $type ][ $name ];
|
||||
}
|
||||
|
||||
|
||||
if ( array_key_exists( 'not_found', $report ) ) {
|
||||
$icon = 'dashicons-yes is-green';
|
||||
} elseif ( ! isset( $report['vulnerabilities'] ) ) {
|
||||
$icon = 'dashicons-no-alt is-gray';
|
||||
} elseif ( empty( $report['vulnerabilities'] ) ) {
|
||||
$icon = 'dashicons-yes is-green';
|
||||
} else {
|
||||
$count = $this->get_item_vulnerabilities_count( $type, $name );
|
||||
$icon = 0 === $count ? 'dashicons-yes is-green' : 'dashicons-warning is-red';
|
||||
}
|
||||
|
||||
return " <span class='dashicons $icon'></span>";
|
||||
}
|
||||
}
|
@ -1,519 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace WPScan;
|
||||
|
||||
// Exit if accessed directly.
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Settings.
|
||||
*
|
||||
* Handles the plugin's settings page.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Settings {
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function __construct( $parent ) {
|
||||
$this->parent = $parent;
|
||||
$this->page = 'wpscan_settings';
|
||||
|
||||
add_action( 'admin_menu', array( $this, 'menu' ) );
|
||||
add_action( 'admin_init', array( $this, 'admin_init' ) );
|
||||
add_action( 'admin_notices', array( $this, 'got_api_token' ) );
|
||||
add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue' ) );
|
||||
add_action( 'add_option_' . $this->parent->OPT_SCANNING_INTERVAL, array( $this, 'schedule_event' ), 10, 2 );
|
||||
add_action( 'update_option_' . $this->parent->OPT_SCANNING_INTERVAL, array( $this, 'schedule_event' ), 10, 2 );
|
||||
add_action( 'update_option_' . $this->parent->OPT_SCANNING_TIME, array( $this, 'schedule_event' ), 10, 2 );
|
||||
add_action( 'update_option_' . $this->parent->OPT_IGNORE_ITEMS, array( $this, 'update_ignored_items' ), 10, 2 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Introduction
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function introduction() {}
|
||||
|
||||
/**
|
||||
* Register Admin Scripts
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function admin_enqueue( $hook ) {
|
||||
$screen = get_current_screen();
|
||||
|
||||
if ( strstr( $screen->id, $this->page ) ) {
|
||||
wp_enqueue_style(
|
||||
'wpscan-settings',
|
||||
plugins_url( 'assets/css/settings.css', WPSCAN_PLUGIN_FILE ),
|
||||
array(),
|
||||
$this->parent->wpscan_plugin_version()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings Options
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function admin_init() {
|
||||
// No need to sanitise the API token from the Settings form if we are using the token from the
|
||||
// WPSCAN_API_TOKEN constant. register_setting() is run before WPSCAN_API_TOKEN is placed in the database,
|
||||
// causing a NULL API token to be passed to some functions if called when using a WPSCAN_API_TOKEN constant.
|
||||
if ( ! defined( 'WPSCAN_API_TOKEN' ) ) {
|
||||
register_setting( $this->page, $this->parent->OPT_API_TOKEN, array( 'sanitize_callback' => array( $this, 'sanitize_api_token' ) ) );
|
||||
}
|
||||
|
||||
register_setting( $this->page, $this->parent->OPT_IGNORE_ITEMS );
|
||||
register_setting( $this->page, $this->parent->OPT_SCANNING_INTERVAL, 'sanitize_text_field' );
|
||||
register_setting( $this->page, $this->parent->OPT_SCANNING_TIME, 'sanitize_text_field' );
|
||||
register_setting( $this->page, $this->parent->OPT_DISABLE_CHECKS, array( 'type' => 'boolean', 'default' => '0' ) );
|
||||
|
||||
$section = $this->page . '_section';
|
||||
|
||||
add_settings_section(
|
||||
$section,
|
||||
null,
|
||||
array( $this, 'introduction' ),
|
||||
$this->page
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
$this->parent->OPT_API_TOKEN,
|
||||
__( 'WPScan API Token', 'wpscan' ),
|
||||
array( $this, 'field_api_token' ),
|
||||
$this->page,
|
||||
$section
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
$this->parent->OPT_SCANNING_INTERVAL,
|
||||
__( 'Automated Scanning', 'wpscan' ),
|
||||
array( $this, 'field_scanning_interval' ),
|
||||
$this->page,
|
||||
$section
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
$this->parent->OPT_SCANNING_TIME,
|
||||
__( 'Scanning Time', 'wpscan' ),
|
||||
array( $this, 'field_scanning_time' ),
|
||||
$this->page,
|
||||
$section
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
$this->parent->OPT_DISABLE_CHECKS,
|
||||
__( 'Disable Security Checks', 'wpscan' ),
|
||||
array( $this, 'field_disable_security_checks' ),
|
||||
$this->page,
|
||||
$section
|
||||
);
|
||||
|
||||
add_settings_field(
|
||||
$this->parent->OPT_IGNORE_ITEMS,
|
||||
__( 'Ignore Items', 'wpscan' ),
|
||||
array( $this, 'field_ignore_items' ),
|
||||
$this->page,
|
||||
$section
|
||||
);
|
||||
|
||||
if ( $this->parent->is_interval_scanning_disabled() ) {
|
||||
as_unschedule_all_actions( $this->parent->WPSCAN_SCHEDULE );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if API Token is set
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return bool
|
||||
*/
|
||||
public function api_token_set() {
|
||||
$api_token = get_option( $this->parent->OPT_API_TOKEN );
|
||||
|
||||
if ( empty( $api_token ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Warn if no API Token is set
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function got_api_token() {
|
||||
$screen = get_current_screen();
|
||||
|
||||
if ( ! $this->api_token_set() && ! strstr( $screen->id, $this->page ) ) {
|
||||
printf(
|
||||
'<div class="%s"><p>%s <a href="%s">%s</a>%s</p></div>',
|
||||
'notice notice-error',
|
||||
__( 'To use WPScan you have to setup your WPScan API Token. Either in the ', 'wpscan' ),
|
||||
admin_url( 'admin.php?page=' . $this->page ),
|
||||
__( 'Settings', 'wpscan' ),
|
||||
__( ' page, or, within the wp-config.php file.', 'wpscan' )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add submenu
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function menu() {
|
||||
$title = __( 'Settings', 'wpscan' );
|
||||
|
||||
add_submenu_page(
|
||||
'wpscan',
|
||||
$title,
|
||||
$title,
|
||||
$this->parent->WPSCAN_ROLE,
|
||||
$this->page,
|
||||
array( $this, 'page' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the page
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function page() {
|
||||
echo '<div class="wrap">';
|
||||
echo '<h1><img src="' . plugin_dir_url( dirname( __FILE__ ) ) . 'assets/svg/logo.svg" alt="WPScan"></h1>';
|
||||
|
||||
echo '<h2>' . __( 'Settings', 'wpscan' ) . '</h2>';
|
||||
|
||||
echo '<p>' . __( 'The WPScan WordPress security plugin uses our own constantly updated vulnerability database to stay up to date with the latest WordPress core, plugin and theme vulnerabilities. For the WPScan plugin to retrieve the potential vulnerabilities that may affect your site, you first need to configure your API token, that you can get for free from our database\'s website. Alternatively you can also set your API token in the wp-config.php file using the WPSCAN_API_TOKEN constant.', 'wpscan' ) . '</p><br/>';
|
||||
|
||||
settings_errors();
|
||||
|
||||
echo '<form action="options.php" method="post">';
|
||||
settings_fields( $this->page );
|
||||
do_settings_sections( $this->page );
|
||||
|
||||
submit_button();
|
||||
echo '</form>';
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* API token field
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function field_api_token() {
|
||||
$api_token = esc_attr( get_option( $this->parent->OPT_API_TOKEN ) );
|
||||
|
||||
if ( defined( 'WPSCAN_API_TOKEN' ) ) {
|
||||
$api_token = esc_attr( WPSCAN_API_TOKEN );
|
||||
$disabled = "disabled='true'";
|
||||
} else {
|
||||
$disabled = null;
|
||||
}
|
||||
|
||||
// Field.
|
||||
echo "<input type='text' name='" . $this->parent->OPT_API_TOKEN . "' value='$api_token' class='blur-on-lose-focus regular-text' $disabled>";
|
||||
|
||||
// Messages.
|
||||
echo '<p class="description">';
|
||||
|
||||
if ( defined( 'WPSCAN_API_TOKEN' ) ) {
|
||||
_e( 'Your API Token has been set in a PHP file and been disabled here.', 'wpscan' );
|
||||
echo '<br>';
|
||||
}
|
||||
|
||||
if ( ! empty( $api_token ) ) {
|
||||
echo sprintf(
|
||||
__( 'To regenerate your token, or upgrade your plan, %s.', 'wpscan' ),
|
||||
'<a href="' . WPSCAN_PROFILE_URL . '" target="_blank">' . __( 'check your profile', 'wpscan' ) . '</a>'
|
||||
);
|
||||
} else {
|
||||
echo sprintf(
|
||||
__( '%s to get your free API Token.', 'wpscan' ),
|
||||
'<a href="' . WPSCAN_SIGN_UP_URL . '" target="_blank">' . __( 'Sign up', 'wpscan' ) . '</a>'
|
||||
);
|
||||
}
|
||||
|
||||
echo '</p><br>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Scanning interval field
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function field_scanning_interval() {
|
||||
$opt_name = $this->parent->OPT_SCANNING_INTERVAL;
|
||||
$value = esc_attr( get_option( $opt_name, 'daily' ) );
|
||||
|
||||
$disabled = $this->parent->is_interval_scanning_disabled() ? "disabled='true'" : null;
|
||||
|
||||
$options = array(
|
||||
'daily' => __( 'Daily', 'wpscan' ),
|
||||
'twicedaily' => __( 'Twice daily', 'wpscan' ),
|
||||
'hourly' => __( 'Hourly', 'wpscan' ),
|
||||
);
|
||||
|
||||
echo "<select name='$opt_name' $disabled>";
|
||||
foreach ( $options as $id => $title ) {
|
||||
$selected = selected( $value, $id, false );
|
||||
echo "<option value='$id' $selected>$title</option>";
|
||||
}
|
||||
echo '</select>';
|
||||
|
||||
echo '<p class="description">';
|
||||
|
||||
if ( $this->parent->is_interval_scanning_disabled() ) {
|
||||
_e( 'Automated scanning is currently disabled using the <code>WPSCAN_DISABLE_SCANNING_INTERVAL</code> constant.', 'wpscan' );
|
||||
} else {
|
||||
_e( 'This setting will change the frequency that the WPScan plugin will run an automatic scan. This is useful if you want your report, or notifications, to be updated more frequently. Please note that the more frequent scans are run, the more API requests are consumed.', 'wpscan' );
|
||||
}
|
||||
|
||||
echo '</p><br>';
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Scanning time field.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function field_scanning_time() {
|
||||
$opt = $this->parent->OPT_SCANNING_TIME;
|
||||
$value = esc_attr( get_option( $opt, date( 'H:i' ) ) );
|
||||
$disabled = $this->parent->is_interval_scanning_disabled() ? "disabled='true'" : null;
|
||||
|
||||
echo "<input type='time' name='$opt' value='$value' $disabled> ";
|
||||
|
||||
if ( ! $this->parent->is_interval_scanning_disabled() ) {
|
||||
echo __( 'Current server time is ', 'wpscan' ) . '<code>' . date( 'H:i' ) . '</code>';
|
||||
}
|
||||
|
||||
echo '<p class="description">';
|
||||
|
||||
if ( $this->parent->is_interval_scanning_disabled() ) {
|
||||
_e( 'Automated scanning is currently disabled using the <code>WPSCAN_DISABLE_SCANNING_INTERVAL</code> constant.', 'wpscan' );
|
||||
} else {
|
||||
_e( 'This setting allows you to set the scanning hour for the <code>Daily</code> option. For the <code>Twice Daily</code> this will be the first scan and the second will be 12 hours later. For the <code>Hourly</code> it will affect the first scan only.', 'wpscan' );
|
||||
}
|
||||
|
||||
echo '</p><br/>';
|
||||
}
|
||||
/**
|
||||
* Disable security checks field
|
||||
*
|
||||
* @since 1.15.2
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function field_disable_security_checks() {
|
||||
$opt = $this->parent->OPT_DISABLE_CHECKS;
|
||||
|
||||
$value = get_option( $opt, array() );
|
||||
$checked = $value === '1' ? 'checked' : null;
|
||||
|
||||
echo "<input name='{$opt}' type='checkbox' $checked value='1' >";
|
||||
}
|
||||
|
||||
/**
|
||||
* Ignore items field
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function field_ignore_items() {
|
||||
$opt = $this->parent->OPT_IGNORE_ITEMS;
|
||||
$value = get_option( $opt, array() );
|
||||
$wp = isset( $value['wordpress'] ) ? 'checked' : null;
|
||||
|
||||
// WordPress.
|
||||
echo "<div class='wpscan-ignore-items-section'>";
|
||||
|
||||
echo "<label><input name='{$opt}[WordPress]' type='checkbox' $wp value='1' > " .
|
||||
__( 'WordPress Core', 'wpscan' ) . '</label>';
|
||||
|
||||
echo '</div>';
|
||||
|
||||
// Plugins list.
|
||||
$this->ignore_items_section( 'plugins', $value );
|
||||
|
||||
// Themes list
|
||||
$this->ignore_items_section( 'themes', $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Ignore items section
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function ignore_items_section( $type, $value ) {
|
||||
$opt = $this->parent->OPT_IGNORE_ITEMS;
|
||||
|
||||
$items = 'themes' === $type
|
||||
? wp_get_themes()
|
||||
: get_plugins();
|
||||
|
||||
$title = 'themes' === $type
|
||||
? __( 'Themes', 'wpscan' )
|
||||
: __( 'Plugins', 'wpscan' );
|
||||
|
||||
echo "<div class='wpscan-ignore-items-section'>";
|
||||
|
||||
echo "<h4>$title</h4>";
|
||||
|
||||
foreach ( $items as $name => $details ) {
|
||||
$slug = 'themes' === $type
|
||||
? $this->parent->get_theme_slug( $name, $details )
|
||||
: $this->parent->get_plugin_slug( $name, $details );
|
||||
|
||||
$checked = isset( $value[ $type ][ $slug ] ) ? 'checked' : null;
|
||||
|
||||
echo '<label>' .
|
||||
"<input name='{$opt}[$type][$slug]' type='checkbox' $checked value='1'> " .
|
||||
esc_html( $details['Name'] ) .
|
||||
'</label>';
|
||||
}
|
||||
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize API token
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function sanitize_api_token( $value ) {
|
||||
$value = trim( $value );
|
||||
|
||||
// update_account_status() calls the /status API endpoint, verifying the validity of the Token passed via $value and updates the account status if needed.
|
||||
if ( empty( $value ) ) {
|
||||
delete_option( $this->parent->OPT_ACCOUNT_STATUS );
|
||||
} else {
|
||||
$this->parent->classes['account']->update_account_status( $value );
|
||||
}
|
||||
|
||||
$errors = get_option( $this->parent->OPT_ERRORS );
|
||||
|
||||
if ( ! empty( $errors ) ) {
|
||||
foreach ( $errors as $error ) {
|
||||
add_settings_error(
|
||||
$this->page,
|
||||
'api_token',
|
||||
$error
|
||||
);
|
||||
}
|
||||
|
||||
update_option( $this->parent->OPT_ERRORS, array() ); // Clear errors.
|
||||
} else {
|
||||
if ( $this->parent->is_interval_scanning_disabled() ) {
|
||||
as_unschedule_all_actions( $this->parent->WPSCAN_SCHEDULE );
|
||||
}
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule CRON scanning event
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function schedule_event( $old_value, $value ) {
|
||||
$api_token = get_option( $this->parent->OPT_API_TOKEN );
|
||||
|
||||
if ( ! empty( $api_token ) && $old_value !== $value ) {
|
||||
$interval = esc_attr( get_option( $this->parent->OPT_SCANNING_INTERVAL, 'daily' ) );
|
||||
$time = esc_attr( get_option( $this->parent->OPT_SCANNING_TIME, date( 'H:i' ) . ' +1day' ) );
|
||||
|
||||
as_unschedule_all_actions( $this->parent->WPSCAN_SCHEDULE );
|
||||
|
||||
switch ( $interval ) {
|
||||
case 'daily':
|
||||
$interval = DAY_IN_SECONDS;
|
||||
break;
|
||||
case 'twicedaily':
|
||||
$interval = HOUR_IN_SECONDS * 12;
|
||||
break;
|
||||
case 'hourly':
|
||||
$interval = HOUR_IN_SECONDS;
|
||||
break;
|
||||
}
|
||||
|
||||
if ( ! $this->parent->is_interval_scanning_disabled() ) {
|
||||
if ( false === as_next_scheduled_action( $this->parent->WPSCAN_SCHEDULE ) ) {
|
||||
as_schedule_recurring_action( $time, $interval, $this->parent->WPSCAN_SCHEDULE );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update ignored items
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function update_ignored_items( $old_value, $value ) {
|
||||
$report = $this->parent->get_report();
|
||||
|
||||
if ( empty( $report ) || $old_value === $value ) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ( array( 'themes', 'plugins' ) as $type ) {
|
||||
if ( ! isset( $value[ $type ] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ( $value[ $type ] as $slug => $checked ) {
|
||||
if ( isset( $report[ $type ][ $slug ] ) ) {
|
||||
// Remove from the report.
|
||||
unset( $report[ $type ][ $slug ] );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
update_option( $this->parent->OPT_REPORT, $report, true );
|
||||
}
|
||||
}
|
@ -1,93 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace WPScan;
|
||||
|
||||
// Exit if accessed directly.
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* SiteHealth.
|
||||
*
|
||||
* Displays vulnerabilities in WordPress site health page.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class SiteHealth {
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function __construct( $parent ) {
|
||||
$this->parent = $parent;
|
||||
|
||||
add_filter( 'site_status_tests', array( $this, 'add_site_health_tests' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add site-health page tests.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function add_site_health_tests( $tests ) {
|
||||
$tests['direct']['wpscan_check'] = array(
|
||||
'label' => __( 'WPScan Vulnerabilities Check' ),
|
||||
'test' => array( $this, 'site_health_tests' ),
|
||||
);
|
||||
|
||||
return $tests;
|
||||
}
|
||||
|
||||
/**
|
||||
* Do site-health page tests
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return array
|
||||
*/
|
||||
public function site_health_tests() {
|
||||
$report = $this->parent->get_report();
|
||||
$total = $this->parent->get_total_not_ignored();
|
||||
$vulns = $this->parent->classes['report']->get_all_vulnerabilities();
|
||||
|
||||
/**
|
||||
* Default, no vulnerabilities found
|
||||
*/
|
||||
$result = array(
|
||||
'label' => __( 'No known vulnerabilities found', 'wpscan' ),
|
||||
'status' => 'good',
|
||||
'badge' => array(
|
||||
'label' => __( 'Security', 'wpscan' ),
|
||||
'color' => 'gray',
|
||||
),
|
||||
'description' => sprintf(
|
||||
'<p>%s</p>',
|
||||
__( 'Vulnerabilities can be exploited by hackers and cause harm to your website.', 'wpscan' )
|
||||
),
|
||||
'actions' => '',
|
||||
'test' => 'wpscan_check',
|
||||
);
|
||||
|
||||
/**
|
||||
* If vulnerabilities found.
|
||||
*/
|
||||
if ( ! empty($report) && $total > 0 ) {
|
||||
$result['status'] = 'critical';
|
||||
$result['label'] = sprintf( _n( 'Your site is affected by %d security vulnerability', 'Your site is affected by %d security vulnerabilities', $total, 'wpscan' ), $total );
|
||||
$result['description'] = 'WPScan detected the following security vulnerabilities in your site:';
|
||||
|
||||
foreach ( $vulns as $vuln ) {
|
||||
$result['description'] .= '<p>';
|
||||
$result['description'] .= "<span class='dashicons dashicons-warning' style='color: crimson;'></span>  ";
|
||||
$result['description'] .= wp_kses( $vuln, array( 'a' => array( 'href' => array() ) ) ); // Only allow a href HTML tags.
|
||||
$result['description'] .= '</p>';
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
@ -1,221 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace WPScan;
|
||||
|
||||
// Exit if accessed directly.
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* Summary.
|
||||
*
|
||||
* Displays the Summary box.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Summary {
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function __construct( $parent ) {
|
||||
$this->parent = $parent;
|
||||
|
||||
add_action( 'admin_init', array( $this, 'add_meta_box_summary' ) );
|
||||
add_action( 'wp_ajax_wpscan_check_now', array( $this, 'ajax_check_now' ) );
|
||||
|
||||
if ( get_option( $this->parent->OPT_DISABLE_CHECKS, array() ) !== '1' ) {
|
||||
add_action( 'wp_ajax_wpscan_security_check_now', array( $this, 'ajax_security_check_now' ) );
|
||||
}
|
||||
|
||||
add_action( 'wp_ajax_' . $this->parent->WPSCAN_TRANSIENT_CRON, array( $this, 'ajax_doing_cron' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add meta box
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function add_meta_box_summary() {
|
||||
$report = $this->parent->get_report();
|
||||
|
||||
add_meta_box(
|
||||
'wpscan-metabox-summary',
|
||||
__( 'Summary', 'wpscan' ),
|
||||
array( $this, 'do_meta_box_summary' ),
|
||||
'wpscan',
|
||||
'side',
|
||||
'high'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render meta box
|
||||
*
|
||||
* @return string
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function do_meta_box_summary() {
|
||||
$report = $this->parent->get_report();
|
||||
$errors = get_option( $this->parent->OPT_ERRORS );
|
||||
$total = $this->parent->get_total_not_ignored();
|
||||
?>
|
||||
|
||||
<?php
|
||||
// Check if we have run a scan yet.
|
||||
if ( ! empty( $this->parent->get_report() ) ) {
|
||||
?>
|
||||
|
||||
<?php
|
||||
if ( ! empty( $errors ) ) {
|
||||
foreach ( $errors as $err ) {
|
||||
// $err should not contain user input. If you like to add an esc_html() here, be sure to update the error text that use HTML
|
||||
echo '<p class="wpscan-summary-res is-red"><span class="dashicons dashicons-megaphone"></span> <strong>' . $err . '</strong></p>';
|
||||
}
|
||||
} elseif ( empty( $this->parent->get_report() ) ) { // No scan run yet.
|
||||
echo '<p class="wpscan-summary-res is-red"><span class="dashicons dashicons-megaphone"></span> <strong>' . __( 'No scan run yet!', 'wpscan' ) . '</strong></p>';
|
||||
} elseif ( empty( $errors ) && 0 === $total ) {
|
||||
echo '<p class="wpscan-summary-res is-green"><span class="dashicons dashicons-awards"></span> <strong>' . __( 'No known vulnerabilities found', 'wpscan' ) . '</strong></p>';
|
||||
} elseif ( ! get_option( $this->parent->OPT_API_TOKEN ) ) {
|
||||
echo '<p class="wpscan-summary-res is-red"><span class="dashicons dashicons-megaphone"></span> <strong>' . __( 'You need to add a WPScan API Token to the settings page', 'wpscan' ) . '</strong></p>';
|
||||
} else {
|
||||
echo '<p class="wpscan-summary-res is-red"><span class="dashicons dashicons-megaphone"></span> <strong>' . __( 'Some vulnerabilities were found', 'wpscan' ) . '</strong></p>';
|
||||
}
|
||||
?>
|
||||
|
||||
<p>
|
||||
<?php _e( 'The last full scan was run on: ', 'wpscan' ); ?>
|
||||
</p>
|
||||
<p>
|
||||
<span class="dashicons dashicons-calendar-alt"></span>
|
||||
|
||||
<strong>
|
||||
<?php
|
||||
if ( array_key_exists( 'cache', $report ) ) {
|
||||
echo date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $report['cache'] );
|
||||
} else {
|
||||
echo _e( 'No full scan yet', 'wpscan' );
|
||||
}
|
||||
?>
|
||||
</strong>
|
||||
</p>
|
||||
|
||||
<?php if ( false !== as_next_scheduled_action( $this->parent->WPSCAN_SCHEDULE ) ) { ?>
|
||||
<p>
|
||||
<?php _e( 'The next scan will automatically be run on ', 'wpscan' ); ?>
|
||||
<?php echo date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), as_next_scheduled_action( $this->parent->WPSCAN_SCHEDULE ) ); ?>
|
||||
</p>
|
||||
<?php } ?>
|
||||
|
||||
<?php } ?>
|
||||
|
||||
<p class="description">
|
||||
<?php
|
||||
if ( get_option( $this->parent->OPT_API_TOKEN ) ) {
|
||||
_e( 'Click the Run All button to run a full vulnerability scan against your WordPress website.', 'wpscan' );
|
||||
} else {
|
||||
_e( 'Add your API token to the settings page to be able to run a full scan.', 'wpscan' );
|
||||
}
|
||||
?>
|
||||
</p>
|
||||
|
||||
<?php if ( get_option( $this->parent->OPT_API_TOKEN ) ) : ?>
|
||||
<p class="check-now">
|
||||
<?php
|
||||
$spinner_display = '';
|
||||
$button_disabled = '';
|
||||
if ( false !== as_next_scheduled_action( $this->parent->WPSCAN_RUN_ALL ) ) {
|
||||
$spinner_display = ' style="visibility: visible;"';
|
||||
$button_disabled = 'disabled';
|
||||
}
|
||||
?>
|
||||
<span class="spinner"<?php echo $spinner_display; ?>></span>
|
||||
<button type="button" class="button button-primary"<?php echo $button_disabled; ?>><?php _e( 'Run All', 'wpscan' ); ?></button>
|
||||
</p>
|
||||
<?php endif ?>
|
||||
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajax check now
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function ajax_check_now() {
|
||||
check_ajax_referer( 'wpscan' );
|
||||
|
||||
if ( ! current_user_can( $this->parent->WPSCAN_ROLE ) ) {
|
||||
wp_redirect( home_url() );
|
||||
wp_die();
|
||||
}
|
||||
|
||||
if ( false === as_next_scheduled_action( $this->parent->WPSCAN_RUN_ALL ) ) {
|
||||
as_schedule_single_action( strtotime( 'now' ), $this->parent->WPSCAN_RUN_ALL );
|
||||
}
|
||||
|
||||
wp_die();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajax security check now
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function ajax_security_check_now() {
|
||||
check_ajax_referer( 'wpscan' );
|
||||
|
||||
if ( ! current_user_can( $this->parent->WPSCAN_ROLE ) ) {
|
||||
wp_redirect( home_url() );
|
||||
wp_die();
|
||||
}
|
||||
|
||||
$items_inline = get_option( $this->parent->WPSCAN_RUN_SECURITY );
|
||||
|
||||
$plugins = array();
|
||||
foreach ( $this->parent->classes['checks/system']->checks as $id => $data ) {
|
||||
$plugins[ $id ] = array(
|
||||
'status' => $this->parent->classes['report']->get_status( 'security-checks', $id ),
|
||||
'vulnerabilities' => $this->parent->classes['checks/system']->get_check_vulnerabilities( $data['instance'] ),
|
||||
'security-check-actions' => $this->parent->classes['checks/system']->get_list_actions( $data['instance'] ),
|
||||
);
|
||||
}
|
||||
|
||||
$response = array(
|
||||
'inline' => $items_inline,
|
||||
'plugins' => $plugins,
|
||||
);
|
||||
|
||||
wp_die( wp_json_encode( $response ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajax to check when the cron task has finished
|
||||
*
|
||||
* @return void
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
*/
|
||||
public function ajax_doing_cron() {
|
||||
check_ajax_referer( 'wpscan' );
|
||||
|
||||
if ( ! current_user_can( $this->parent->WPSCAN_ROLE ) ) {
|
||||
wp_redirect( home_url() );
|
||||
wp_die();
|
||||
}
|
||||
|
||||
// echo get_transient( $this->parent->WPSCAN_TRANSIENT_CRON ) ? 'YES' : 'NO';
|
||||
echo false !== as_next_scheduled_action( $this->parent->WPSCAN_RUN_ALL ) ? 'YES' : 'NO';
|
||||
|
||||
wp_die();
|
||||
}
|
||||
}
|
@ -1,191 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace WPScan;
|
||||
|
||||
// Exit if accessed directly.
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* IgnoreVulnerabilities.
|
||||
*
|
||||
* Used for the ignore vulnerabilities logic.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class ignoreVulnerabilities {
|
||||
// Page slug.
|
||||
private $page;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @param object $parent parent.
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function __construct( $parent ) {
|
||||
$this->parent = $parent;
|
||||
$this->page = 'wpscan_ignore_vulnerabilities';
|
||||
|
||||
add_action( 'admin_init', array( $this, 'admin_init' ) );
|
||||
add_action( 'admin_init', array( $this, 'add_meta_box_ignore_vulnerabilities' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Ignore vulnerabilities option
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function admin_init() {
|
||||
$total = $this->parent->get_total();
|
||||
|
||||
register_setting( $this->page, $this->parent->OPT_IGNORED, array( $this, 'sanitize_ignored' ) );
|
||||
|
||||
$section = $this->page . '_section';
|
||||
|
||||
add_settings_section(
|
||||
$section,
|
||||
null,
|
||||
array( $this, 'introduction' ),
|
||||
$this->page
|
||||
);
|
||||
|
||||
if ( $total > 0 ) {
|
||||
add_settings_field(
|
||||
$this->parent->OPT_IGNORED,
|
||||
null,
|
||||
array( $this, 'field_ignored' ),
|
||||
$this->page,
|
||||
$section
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add meta box
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function add_meta_box_ignore_vulnerabilities() {
|
||||
add_meta_box(
|
||||
'wpscan-metabox-ignore-vulnerabilities',
|
||||
__( 'Ignore Vulnerabilities', 'wpscan' ),
|
||||
array( $this, 'do_meta_box_ignore_vulnerabilities' ),
|
||||
'wpscan',
|
||||
'side',
|
||||
'low'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render meta box
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function do_meta_box_ignore_vulnerabilities() {
|
||||
echo '<form action="options.php" method="post">';
|
||||
|
||||
settings_fields( $this->page );
|
||||
|
||||
do_settings_sections( $this->page );
|
||||
|
||||
submit_button();
|
||||
|
||||
echo '</form>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Introduction
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function introduction() { }
|
||||
|
||||
/**
|
||||
* Ignored field
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @access public
|
||||
* @return void
|
||||
*/
|
||||
public function field_ignored() {
|
||||
$this->list_vulnerabilities_to_ignore( 'wordpress', get_bloginfo( 'version' ) );
|
||||
|
||||
foreach ( get_plugins() as $name => $details ) {
|
||||
$this->list_vulnerabilities_to_ignore( 'plugins', $this->parent->get_plugin_slug( $name, $details ) );
|
||||
}
|
||||
|
||||
foreach ( wp_get_themes() as $name => $details ) {
|
||||
$this->list_vulnerabilities_to_ignore( 'themes', $this->parent->get_theme_slug( $name, $details ) );
|
||||
}
|
||||
|
||||
if ( get_option( $this->parent->OPT_DISABLE_CHECKS, array() ) !== '1' ) {
|
||||
foreach ( $this->parent->classes['checks/system']->checks as $id => $data ) {
|
||||
$this->list_vulnerabilities_to_ignore( 'security-checks', $id );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize ignored
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @param string $value value.
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function sanitize_ignored( $value ) {
|
||||
if ( empty( $value ) ) {
|
||||
return array();
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* List of vulnerabilities
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $type - Type of report: wordpress, plugins, themes.
|
||||
* @param string $name - key name of the element.
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
public function list_vulnerabilities_to_ignore( $type, $name ) {
|
||||
$report = $this->parent->get_report();
|
||||
|
||||
if ( isset( $report[ $type ] ) && isset( $report[ $type ][ $name ] ) ) {
|
||||
$report = $report[ $type ][ $name ];
|
||||
}
|
||||
|
||||
if ( ! isset( $report['vulnerabilities'] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$ignored = $this->parent->get_ignored_vulnerabilities();
|
||||
|
||||
foreach ( $report['vulnerabilities'] as $item ) {
|
||||
$id = 'security-checks' === $type ? $item['id'] : $item->id;
|
||||
$title = 'security-checks' === $type ? $item['title'] : $this->parent->get_sanitized_vulnerability_title( $item );
|
||||
|
||||
echo sprintf(
|
||||
'<label><input type="checkbox" name="%s[]" value="%s" %s> %s</label><br>',
|
||||
esc_attr( $this->parent->OPT_IGNORED ),
|
||||
esc_attr( $id ),
|
||||
esc_html( in_array( $id, $ignored, true ) ? 'checked="checked"' : null ),
|
||||
wp_kses( $title, array( 'a' => array( 'href' => array() ) ) ) // Only allow a href HTML tags.
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,57 +0,0 @@
|
||||
.wpscan-model {
|
||||
position: fixed;
|
||||
overflow: auto;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
top: 0;
|
||||
left: 0;
|
||||
z-index: 100000;
|
||||
display: none;
|
||||
background: rgba(0,0,0,0.6);
|
||||
}
|
||||
|
||||
.wpscan-model.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.wpscan-modal-dialog {
|
||||
background: white;
|
||||
z-index: 100001;
|
||||
width: 500px;
|
||||
margin: auto;
|
||||
position: absolute;
|
||||
top: -30px;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
height: 60px;
|
||||
}
|
||||
|
||||
.wpscan-model-content {
|
||||
background: #f2f2f2;
|
||||
height: 100%;
|
||||
padding: 15px 20px 20px 20px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
h4 {
|
||||
border-bottom: #eeeeee solid 1px;
|
||||
background: #fbfbfb;
|
||||
padding: 15px 20px;
|
||||
position: relative;
|
||||
text-transform: uppercase;
|
||||
margin: 0;
|
||||
font-size: 1.2em;
|
||||
font-weight: bold;
|
||||
color: #cacaca;
|
||||
text-shadow: 1px 1px 1px #fff;
|
||||
letter-spacing: 0.6px;
|
||||
}
|
||||
|
||||
.wpscan-model-footer {
|
||||
border: 0;
|
||||
background: #fefefe;
|
||||
padding: 10px;
|
||||
border-top: #eeeeee solid 1px;
|
||||
text-align: right;
|
||||
}
|
@ -1,23 +0,0 @@
|
||||
.wpscan-ignore-items-section {
|
||||
display: block;
|
||||
margin-bottom: 25px;
|
||||
float: left;
|
||||
width: 800px;
|
||||
}
|
||||
|
||||
.wpscan-ignore-items-section label {
|
||||
width: 30%;
|
||||
float: left;
|
||||
margin-bottom: 12px;
|
||||
padding-right: 20px;
|
||||
line-break: anywhere;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.blur-on-lose-focus:not(:focus) {
|
||||
color: transparent;
|
||||
text-shadow: 0 0 5px rgba(0,0,0,0.5);
|
||||
}
|
@ -1,254 +0,0 @@
|
||||
|
||||
/* Table list */
|
||||
|
||||
.wpscan-report-section {
|
||||
margin: 0px 0px 20px 0px;
|
||||
}
|
||||
|
||||
.wp-list-table.plugins .plugin-title strong {
|
||||
float: left;
|
||||
margin-bottom: 5px;
|
||||
margin-right: 12px;
|
||||
white-space: normal !important;
|
||||
}
|
||||
|
||||
.column-name {
|
||||
word-break: break-word;
|
||||
width: 250px;
|
||||
}
|
||||
|
||||
.is-gray {
|
||||
color: gray;
|
||||
}
|
||||
|
||||
.is-green {
|
||||
color: green;
|
||||
}
|
||||
|
||||
.is-red {
|
||||
color: crimson;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 782px) {
|
||||
.wp-list-table.plugins tr th.check-column { padding: 0 0 0 10px; }
|
||||
}
|
||||
|
||||
/* Summary */
|
||||
|
||||
#wpscan-metabox-summary .check-now { padding: 0; text-align: right; }
|
||||
#wpscan-metabox-summary .spinner { float: none; margin-top: 0; }
|
||||
|
||||
@media screen and (max-width: 850px) {
|
||||
#wpscan-metabox-summary { margin-top: 20px; }
|
||||
}
|
||||
|
||||
/* Notification */
|
||||
|
||||
#wpscan-metabox-notification table,
|
||||
#wpscan-metabox-notification tbody,
|
||||
#wpscan-metabox-notification tr,
|
||||
#wpscan-metabox-notification th,
|
||||
#wpscan-metabox-notification td { display: block; width: 100%; }
|
||||
#wpscan-metabox-notification th { padding: .5em 0; }
|
||||
#wpscan-metabox-notification td { padding: 0; }
|
||||
#wpscan-metabox-notification th,
|
||||
#wpscan-metabox-notification td,
|
||||
#wpscan-metabox-notification td p { font-size: 13px; }
|
||||
#wpscan-metabox-notification input[type="text"] { width: 100%; }
|
||||
#wpscan-metabox-notification .submit { padding: 0; text-align: right; }
|
||||
|
||||
@media screen and (max-width: 782px) {
|
||||
#wpscan-metabox-notification label { padding-left: 35px; }
|
||||
#wpscan-metabox-notification input[type="checkbox"] { margin-left: -35px; }
|
||||
}
|
||||
|
||||
/* Ignore vulnerabilities */
|
||||
|
||||
#wpscan-metabox-ignore-vulnerabilities table,
|
||||
#wpscan-metabox-ignore-vulnerabilities tbody,
|
||||
#wpscan-metabox-ignore-vulnerabilities tr,
|
||||
#wpscan-metabox-ignore-vulnerabilities th,
|
||||
#wpscan-metabox-ignore-vulnerabilities td { display: block; width: 100%; }
|
||||
#wpscan-metabox-ignore-vulnerabilities th { padding: .5em 0; }
|
||||
#wpscan-metabox-ignore-vulnerabilities td { padding: 0; }
|
||||
#wpscan-metabox-ignore-vulnerabilities th,
|
||||
#wpscan-metabox-ignore-vulnerabilities td,
|
||||
#wpscan-metabox-ignore-vulnerabilities td p { font-size: 13px; }
|
||||
#wpscan-metabox-ignore-vulnerabilities input[type="text"] { width: 100%; }
|
||||
#wpscan-metabox-ignore-vulnerabilities label { position: relative; display: block; padding-left: 25px; margin: 0 0 10px; }
|
||||
#wpscan-metabox-ignore-vulnerabilities label + br { display: none; }
|
||||
#wpscan-metabox-ignore-vulnerabilities input[type="checkbox"] { margin-left: -25px; }
|
||||
#wpscan-metabox-ignore-vulnerabilities .submit { padding: 0; text-align: right; }
|
||||
|
||||
@media screen and (max-width: 782px) {
|
||||
#wpscan-metabox-ignore-vulnerabilities label { padding-left: 35px; }
|
||||
#wpscan-metabox-ignore-vulnerabilities input[type="checkbox"] { margin-left: -35px; }
|
||||
}
|
||||
|
||||
/* Account */
|
||||
|
||||
#wpscan-account-summary ul li span {
|
||||
float: right;
|
||||
text-transform: capitalize;
|
||||
min-width: 30px;
|
||||
text-align: center;
|
||||
border-radius: 3px;
|
||||
padding: 0px 11px 1px 11px;
|
||||
word-spacing: 1px;
|
||||
color: #4e645a;
|
||||
background: #cbe0ec;
|
||||
}
|
||||
|
||||
#wpscan-account-summary ul li {
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
line-height: 23px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
#wpscan-account-summary ul {
|
||||
margin: 10px 0px;
|
||||
}
|
||||
|
||||
#wpscan-account-summary .button {
|
||||
float: right;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
#wpscan-account-summary .inside {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.wpscan-status-green {
|
||||
background: #c3e6c1 !important;
|
||||
color: #026624 !important;
|
||||
}
|
||||
|
||||
.wpscan-status-orange {
|
||||
background: #ffd2a3 !important;
|
||||
color: #d95200 !important;
|
||||
}
|
||||
|
||||
.wpscan-status-red {
|
||||
background: #ffb6b6 !important;
|
||||
color: #c00 !important;
|
||||
}
|
||||
|
||||
/* download report */
|
||||
|
||||
.toplevel_page_wpscan .download-report {
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
/* Extra info */
|
||||
|
||||
.vulnerability {
|
||||
margin-bottom: 12px;
|
||||
float: left;
|
||||
width: 100%;
|
||||
line-height: 1.8;
|
||||
line-height: 25px;
|
||||
}
|
||||
|
||||
.vulnerability a {
|
||||
float: left;
|
||||
max-width: 80%;
|
||||
}
|
||||
|
||||
.vulnerability:last-child {
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.vulnerability-severity {
|
||||
float: left;
|
||||
min-width: 100px;
|
||||
}
|
||||
|
||||
.vulnerability-title .vulnerability-status .vulnerability-link {
|
||||
float: left;
|
||||
}
|
||||
|
||||
.vulnerability-severity span {
|
||||
float: left;
|
||||
text-transform: capitalize;
|
||||
text-align: center;
|
||||
border-radius: 3px;
|
||||
font-size: 11px;
|
||||
line-height: 19px;
|
||||
min-width: 100px;
|
||||
color: #4e645a;
|
||||
background: #c6e1d5;
|
||||
}
|
||||
|
||||
.item-closed {
|
||||
float: left;
|
||||
text-transform: capitalize;
|
||||
min-width: 30px;
|
||||
text-align: center;
|
||||
border-radius: 3px;
|
||||
padding: 0px 8px 1px 8px;
|
||||
line-height: 20px;
|
||||
font-size: 11px;
|
||||
margin-bottom: 3px;
|
||||
margin-top: 10px;
|
||||
background: #e1dfdf !important;
|
||||
}
|
||||
|
||||
.item-version {
|
||||
float: left;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.wpscan-info {
|
||||
background: #c1e3e6 !important;
|
||||
color: #304584 !important;
|
||||
}
|
||||
|
||||
.wpscan-low {
|
||||
background: #c3e6c1 !important;
|
||||
color: #026624 !important;
|
||||
}
|
||||
|
||||
.wpscan-medium {
|
||||
background: #ffd2a3 !important;
|
||||
color: #d95200 !important;
|
||||
}
|
||||
|
||||
.wpscan-high {
|
||||
background: #ffb6b6 !important;
|
||||
color: #c00 !important;
|
||||
}
|
||||
|
||||
.wpscan-critical {
|
||||
background: #e1b8ff !important;
|
||||
color: #66348a !important;
|
||||
}
|
||||
|
||||
.wpscan-ignored {
|
||||
border-radius: 3px;
|
||||
padding: 0px 8px 0px 8px;
|
||||
line-height: 22px;
|
||||
font-size: 12px;
|
||||
float: left;
|
||||
background: #c1e3e6 !important;
|
||||
color: #304584 !important;
|
||||
}
|
||||
|
||||
.security-check-actions .spinner {
|
||||
float: none;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.security-check-actions button {
|
||||
margin-right: 5px !important;
|
||||
margin-bottom: 5px !important;
|
||||
width: 70px;
|
||||
}
|
||||
|
||||
.ui-tooltip {
|
||||
padding: 6px 12px;
|
||||
border-radius: 3px;
|
||||
max-width: 350px;
|
||||
background: #d7dade;
|
||||
color: #2a2c31;
|
||||
}
|
@ -1,19 +0,0 @@
|
||||
jQuery(document).ready(function($) {
|
||||
let link = $('#deactivate-wpscan');
|
||||
let deactivate = $('.wpscan-model .button-deactivate');
|
||||
let close = $('.wpscan-model .button-close');
|
||||
|
||||
deactivate.attr('href', link.attr('href'));
|
||||
|
||||
link.on('click', function (e) {
|
||||
e.preventDefault();
|
||||
|
||||
$('.wpscan-model').show()
|
||||
});
|
||||
|
||||
close.on('click', function (e) {
|
||||
e.preventDefault();
|
||||
|
||||
$('.wpscan-model').hide()
|
||||
});
|
||||
});
|
File diff suppressed because one or more lines are too long
@ -1,141 +0,0 @@
|
||||
// Actions for metabox Summary
|
||||
|
||||
jQuery( document ).ready(
|
||||
function( $ ) {
|
||||
|
||||
let button_check = $( '#wpscan-metabox-summary .check-now button' );
|
||||
let security_check = $( '.security-check-actions .button' );
|
||||
let spinner = $( '#wpscan-metabox-summary .spinner' );
|
||||
let security_check_runnig = false;
|
||||
let security_check_button = [];
|
||||
|
||||
// Checks if a cron job is already running when the page loads
|
||||
if ( wpscan.doing_cron === 'YES' ) {
|
||||
button_check.attr( 'disabled', true );
|
||||
spinner.css( 'visibility', 'visible' );
|
||||
|
||||
check_cron();
|
||||
}
|
||||
|
||||
if ( wpscan.doing_security_cron.length !== 0 ) {
|
||||
check_security_cron();
|
||||
}
|
||||
|
||||
// Starts the cron job
|
||||
function do_check() {
|
||||
button_check.attr( 'disabled', true );
|
||||
spinner.css( 'visibility', 'visible' );
|
||||
|
||||
$.ajax(
|
||||
{
|
||||
url: wpscan.ajaxurl,
|
||||
method: 'POST',
|
||||
data: {
|
||||
action: wpscan.action_check,
|
||||
_ajax_nonce: wpscan.ajax_nonce
|
||||
},
|
||||
success: function( ) {
|
||||
check_cron();
|
||||
},
|
||||
error: function () {
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
// Check every X seconds if cron has finished
|
||||
function check_cron() {
|
||||
|
||||
setTimeout(
|
||||
function() {
|
||||
$.ajax(
|
||||
{
|
||||
url: ajaxurl,
|
||||
method: 'POST',
|
||||
data: {
|
||||
action: wpscan.action_cron,
|
||||
_ajax_nonce: wpscan.ajax_nonce
|
||||
},
|
||||
success: function( data ) {
|
||||
if ( data === 'NO' ) {
|
||||
location.reload();
|
||||
} else {
|
||||
check_cron();
|
||||
}
|
||||
},
|
||||
error: function ( ) {
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
);
|
||||
},
|
||||
1000 * 2
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
function check_security_cron() {
|
||||
security_check_runnig = true;
|
||||
security_check_button = [];
|
||||
setTimeout(
|
||||
function() {
|
||||
$.ajax(
|
||||
{
|
||||
url: ajaxurl,
|
||||
method: 'POST',
|
||||
data: {
|
||||
action: wpscan.action_security_check,
|
||||
_ajax_nonce: wpscan.ajax_nonce
|
||||
},
|
||||
success: function( data ) {
|
||||
if ( data.length !== 0 ) {
|
||||
var ajax_response = $.parseJSON( data );
|
||||
$.each(
|
||||
ajax_response.inline,
|
||||
function ( key, data ) {
|
||||
security_check_button.push( key );
|
||||
}
|
||||
);
|
||||
|
||||
$( '.security-check-actions button[data-action="run"]' ).each(
|
||||
function() {
|
||||
if ( $.inArray( $( this ).data( 'check-id' ), security_check_button ) === -1 && $( this ).attr( 'disabled' ) ) {
|
||||
$( this ).closest( 'tr' ).find( '.check-column' ).html( ajax_response.plugins[$( this ).data( 'check-id' )]['status'] );
|
||||
$( this ).closest( 'tr' ).find( '.vulnerabilities' ).html( ajax_response.plugins[$( this ).data( 'check-id' )]['vulnerabilities'] );
|
||||
$( this ).closest( 'tr' ).find( '.security-check-actions' ).html( ajax_response.plugins[$( this ).data( 'check-id' )]['security-check-actions'] );
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
if ( security_check_button.length !== 0 ) {
|
||||
check_security_cron();
|
||||
} else {
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
},
|
||||
error: function ( ) {
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
);
|
||||
},
|
||||
2000
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
// Button
|
||||
button_check.on( 'click', do_check );
|
||||
if ( ! security_check_runnig ) {
|
||||
security_check.one( 'click', check_security_cron );
|
||||
}
|
||||
|
||||
// close postboxes that should be closed
|
||||
$( '.if-js-closed' ).removeClass( 'if-js-closed' ).addClass( 'closed' );
|
||||
// postboxes setup
|
||||
postboxes.add_postbox_toggles( 'wpscan' );
|
||||
}
|
||||
);
|
@ -1,58 +0,0 @@
|
||||
jQuery( document ).ready(
|
||||
function ($) {
|
||||
|
||||
// Tooltips
|
||||
$( "strong[title]" ).tooltip(
|
||||
{
|
||||
position: {
|
||||
my: "left top",
|
||||
at: "right+5 top-5",
|
||||
collision: "none"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Actions
|
||||
$( '.security-check-actions button' ).on(
|
||||
'click',
|
||||
function () {
|
||||
|
||||
let btn = $( this );
|
||||
let check = btn.data( 'check-id' );
|
||||
let action_id = btn.data( 'action' );
|
||||
let should_confirm = btn.data( 'confirm' );
|
||||
|
||||
if (should_confirm && ! confirm( 'Are you sure?' )) {
|
||||
return;
|
||||
}
|
||||
|
||||
btn.siblings( '.spinner' ).css( 'visibility', 'visible' );
|
||||
|
||||
$.ajax(
|
||||
{
|
||||
url: wpscan.ajaxurl,
|
||||
method: 'POST',
|
||||
data: {
|
||||
action: 'wpscan_check_action',
|
||||
action_id: action_id,
|
||||
check,
|
||||
_ajax_nonce: wpscan.ajax_nonce
|
||||
},
|
||||
success: function (res) {
|
||||
console.log( res );
|
||||
if (res.success && 'dismiss' === action_id) {
|
||||
location.reload();
|
||||
} else if (res.success) {
|
||||
console.log( $( this ) );
|
||||
btn.prop( 'disabled', true ).html( wpscan.running ).siblings( '.spinner' ).css( 'visibility', 'hidden' );
|
||||
} else {
|
||||
alert( 'Something went wrong, please reload the page.' );
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
}
|
||||
);
|
File diff suppressed because one or more lines are too long
Before Width: | Height: | Size: 7.7 KiB |
@ -1 +0,0 @@
|
||||
<svg id="Layer_1_copy" data-name="Layer 1 copy" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 20 20"><defs><style>.cls-1{fill:#a0a5aa;}</style></defs><title>Artboard 2</title><polyline class="cls-1" points="16.67 10 20 8.08 10 2.3 0 8.08 3.33 10 10 6.15 16.67 10"/><path class="cls-1" d="M16.67,10l-4.2,2.42L10,13.85l-.51-.3L8.3,12.87,7.15,14.13a.93.93,0,0,1-.64.27.9.9,0,0,1-.63-.27.88.88,0,0,1,0-1.27L6.81,12,3.33,10,0,11.92,10,17.7l10-5.78Z"/><path class="cls-1" d="M11.36,10A1.37,1.37,0,0,1,10,11.36h0V11h0a1,1,0,0,0,.72-.29A1,1,0,0,0,11,10ZM10,11.72a1.72,1.72,0,0,1-1.21-.5A1.74,1.74,0,0,1,8.29,10,1.71,1.71,0,1,1,10,11.72Zm0-3.94A2.23,2.23,0,0,0,7.77,10a2.17,2.17,0,0,0,.49,1.38c-.14.13-1.86,1.69-2,1.84a.37.37,0,1,0,.53.53c.15-.15,1.71-1.87,1.83-2a2.28,2.28,0,0,0,1.39.49,2.23,2.23,0,1,0,0-4.46Z"/></svg>
|
Before Width: | Height: | Size: 836 B |
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -1,9 +0,0 @@
|
||||
{
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"WPScan\\": "app/"
|
||||
}
|
||||
},
|
||||
"description": "",
|
||||
"name": "wpscan/wpscan-wordpress-plugin"
|
||||
}
|
@ -1,24 +0,0 @@
|
||||
# This file is for unifying the coding style for different editors and IDEs
|
||||
# editorconfig.org
|
||||
|
||||
# WordPress Coding Standards
|
||||
# https://make.wordpress.org/core/handbook/coding-standards/
|
||||
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_size = 4
|
||||
tab_width = 4
|
||||
indent_style = tab
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
|
||||
[*.txt]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.{md,json,yml}]
|
||||
trim_trailing_whitespace = false
|
||||
indent_style = space
|
||||
indent_size = 2
|
@ -1,45 +0,0 @@
|
||||
# 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.6"
|
||||
- "7.0"
|
||||
- "7.1"
|
||||
- "7.2"
|
||||
- "7.3"
|
||||
|
||||
# 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=5.3 WP_MULTISITE=0
|
||||
- WP_VERSION=5.2 WP_MULTISITE=0
|
||||
- WP_VERSION=5.1 WP_MULTISITE=0
|
||||
- WP_VERSION=5.3 WP_MULTISITE=1
|
||||
- WP_VERSION=5.2 WP_MULTISITE=1
|
||||
- WP_VERSION=5.1 WP_MULTISITE=1
|
||||
|
||||
# WordPress 5.3 requires PHP 5.6. Exclude WP 5.3 + PHP 5.3
|
||||
jobs:
|
||||
exclude:
|
||||
- php: "5.3"
|
||||
env: WP_VERSION=5.3 WP_MULTISITE=0
|
||||
- php: "5.3"
|
||||
env: WP_VERSION=5.3 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.3" ]] && [[ "$WP_VERSION" == "5.3" ]] && [[ "$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)
|
@ -1,57 +0,0 @@
|
||||
module.exports = function( grunt ) {
|
||||
'use strict';
|
||||
|
||||
grunt.initConfig({
|
||||
// Check textdomain errors.
|
||||
checktextdomain: {
|
||||
options:{
|
||||
text_domain: 'action-scheduler',
|
||||
keywords: [
|
||||
'__:1,2d',
|
||||
'_e:1,2d',
|
||||
'_x:1,2c,3d',
|
||||
'esc_html__:1,2d',
|
||||
'esc_html_e:1,2d',
|
||||
'esc_html_x:1,2c,3d',
|
||||
'esc_attr__:1,2d',
|
||||
'esc_attr_e:1,2d',
|
||||
'esc_attr_x:1,2c,3d',
|
||||
'_ex:1,2c,3d',
|
||||
'_n:1,2,4d',
|
||||
'_nx:1,2,4c,5d',
|
||||
'_n_noop:1,2,3d',
|
||||
'_nx_noop:1,2,3c,4d'
|
||||
]
|
||||
},
|
||||
files: {
|
||||
src: [
|
||||
'**/*.php',
|
||||
'!node_modules/**',
|
||||
'!tests/**',
|
||||
'!vendor/**',
|
||||
'!tmp/**'
|
||||
],
|
||||
expand: true
|
||||
}
|
||||
},
|
||||
|
||||
// PHP Code Sniffer.
|
||||
phpcs: {
|
||||
options: {
|
||||
bin: 'vendor/bin/phpcs'
|
||||
},
|
||||
dist: {
|
||||
src: [
|
||||
'**/*.php', // Include all php files.
|
||||
'!deprecated/**',
|
||||
'!node_modules/**',
|
||||
'!vendor/**'
|
||||
]
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Load NPM tasks to be used here.
|
||||
grunt.loadNpmTasks( 'grunt-phpcs' );
|
||||
grunt.loadNpmTasks( 'grunt-checktextdomain' );
|
||||
};
|
@ -1,53 +0,0 @@
|
||||
<?php
|
||||
/*
|
||||
* Plugin Name: Action Scheduler
|
||||
* Plugin URI: https://actionscheduler.org
|
||||
* Description: A robust scheduling library for use in WordPress plugins.
|
||||
* Author: Automattic
|
||||
* Author URI: https://automattic.com/
|
||||
* Version: 3.1.6
|
||||
* License: GPLv3
|
||||
*
|
||||
* Copyright 2019 Automattic, Inc. (https://automattic.com/contact/)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
|
||||
if ( ! function_exists( 'action_scheduler_register_3_dot_1_dot_6' ) ) {
|
||||
|
||||
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_3_dot_1_dot_6', 0, 0 );
|
||||
|
||||
function action_scheduler_register_3_dot_1_dot_6() {
|
||||
$versions = ActionScheduler_Versions::instance();
|
||||
$versions->register( '3.1.6', 'action_scheduler_initialize_3_dot_1_dot_6' );
|
||||
}
|
||||
|
||||
function action_scheduler_initialize_3_dot_1_dot_6() {
|
||||
require_once( 'classes/abstracts/ActionScheduler.php' );
|
||||
ActionScheduler::init( __FILE__ );
|
||||
}
|
||||
|
||||
// Support usage in themes - load this version if no plugin has loaded a version yet.
|
||||
if ( did_action( 'plugins_loaded' ) && ! class_exists( 'ActionScheduler' ) ) {
|
||||
action_scheduler_initialize_3_dot_1_dot_6();
|
||||
do_action( 'action_scheduler_pre_theme_init' );
|
||||
ActionScheduler_Versions::initialize_latest_version();
|
||||
}
|
||||
}
|
@ -1,23 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
|
@ -1,179 +0,0 @@
|
||||
<?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';
|
||||
if ( ! is_null( $schedule ) && ! is_a( $schedule, 'ActionScheduler_CanceledSchedule' ) && ! is_a( $schedule, 'ActionScheduler_NullSchedule' ) ) {
|
||||
$schedule = new ActionScheduler_CanceledSchedule( $schedule->get_date() );
|
||||
}
|
||||
break;
|
||||
default :
|
||||
$action_class = 'ActionScheduler_FinishedAction';
|
||||
break;
|
||||
}
|
||||
|
||||
$action_class = apply_filters( 'action_scheduler_stored_action_class', $action_class, $status, $hook, $args, $schedule, $group );
|
||||
|
||||
$action = new $action_class( $hook, $args, $schedule, $group );
|
||||
|
||||
/**
|
||||
* 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 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueue an action to run one time, as soon as possible (rather a specific scheduled time).
|
||||
*
|
||||
* This method creates a new action with the NULLSchedule. This schedule maps to a MySQL datetime string of
|
||||
* 0000-00-00 00:00:00. This is done to create a psuedo "async action" type that is fully backward compatible.
|
||||
* Existing queries to claim actions claim by date, meaning actions scheduled for 0000-00-00 00:00:00 will
|
||||
* always be claimed prior to actions scheduled for a specific date. This makes sure that any async action is
|
||||
* given priority in queue processing. This has the added advantage of making sure async actions can be
|
||||
* claimed by both the existing WP Cron and WP CLI runners, as well as a new async request runner.
|
||||
*
|
||||
* @param string $hook The hook to trigger when this action runs
|
||||
* @param array $args Args to pass when the hook is triggered
|
||||
* @param string $group A group to put the action in
|
||||
*
|
||||
* @return int The ID of the stored action
|
||||
*/
|
||||
public function async( $hook, $args = array(), $group = '' ) {
|
||||
$schedule = new ActionScheduler_NullSchedule();
|
||||
$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 $when Unix timestamp when the action will run
|
||||
* @param string $group A group to put the action in
|
||||
*
|
||||
* @return int The ID of the stored action
|
||||
*/
|
||||
public function single( $hook, $args = array(), $when = null, $group = '' ) {
|
||||
$date = as_get_datetime_object( $when );
|
||||
$schedule = new ActionScheduler_SimpleSchedule( $date );
|
||||
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
|
||||
return $this->store( $action );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the first instance of an action recurring on a given interval.
|
||||
*
|
||||
* @param string $hook The hook to trigger when this action runs
|
||||
* @param array $args Args to pass when the hook is triggered
|
||||
* @param int $first Unix timestamp for the first run
|
||||
* @param int $interval Seconds between runs
|
||||
* @param string $group A group to put the action in
|
||||
*
|
||||
* @return int The ID of the stored action
|
||||
*/
|
||||
public function recurring( $hook, $args = array(), $first = null, $interval = null, $group = '' ) {
|
||||
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 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the first instance of an action recurring on a Cron schedule.
|
||||
*
|
||||
* @param string $hook The hook to trigger when this action runs
|
||||
* @param array $args Args to pass when the hook is triggered
|
||||
* @param int $base_timestamp The first instance of the action will be scheduled
|
||||
* to run at a time calculated after this timestamp matching the cron
|
||||
* expression. This can be used to delay the first instance of the action.
|
||||
* @param int $schedule A cron definition string
|
||||
* @param string $group A group to put the action in
|
||||
*
|
||||
* @return int The ID of the stored action
|
||||
*/
|
||||
public function cron( $hook, $args = array(), $base_timestamp = null, $schedule = null, $group = '' ) {
|
||||
if ( empty($schedule) ) {
|
||||
return $this->single( $hook, $args, $base_timestamp, $group );
|
||||
}
|
||||
$date = as_get_datetime_object( $base_timestamp );
|
||||
$cron = CronExpression::factory( $schedule );
|
||||
$schedule = new ActionScheduler_CronSchedule( $date, $cron );
|
||||
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
|
||||
return $this->store( $action );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a successive instance of a recurring or cron action.
|
||||
*
|
||||
* Importantly, the action will be rescheduled to run based on the current date/time.
|
||||
* That means when the action is scheduled to run in the past, the next scheduled date
|
||||
* will be pushed forward. For example, if a recurring action set to run every hour
|
||||
* was scheduled to run 5 seconds ago, it will be next scheduled for 1 hour in the
|
||||
* future, which is 1 hour and 5 seconds from when it was last scheduled to run.
|
||||
*
|
||||
* Alternatively, if the action is scheduled to run in the future, and is run early,
|
||||
* likely via manual intervention, then its schedule will change based on the time now.
|
||||
* For example, if a recurring action set to run every day, and is run 12 hours early,
|
||||
* it will run again in 24 hours, not 36 hours.
|
||||
*
|
||||
* This slippage is less of an issue with Cron actions, as the specific run time can
|
||||
* be set for them to run, e.g. 1am each day. In those cases, and entire period would
|
||||
* need to be missed before there was any change is scheduled, e.g. in the case of an
|
||||
* action scheduled for 1am each day, the action would need to run an entire day late.
|
||||
*
|
||||
* @param ActionScheduler_Action $action The existing action.
|
||||
*
|
||||
* @return string The ID of the stored action
|
||||
* @throws InvalidArgumentException If $action is not a recurring action.
|
||||
*/
|
||||
public function repeat( $action ) {
|
||||
$schedule = $action->get_schedule();
|
||||
$next = $schedule->get_next( as_get_datetime_object() );
|
||||
|
||||
if ( is_null( $next ) || ! $schedule->is_recurring() ) {
|
||||
throw new InvalidArgumentException( __( 'Invalid action - must be a recurring action.', 'action-scheduler' ) );
|
||||
}
|
||||
|
||||
$schedule_class = get_class( $schedule );
|
||||
$new_schedule = new $schedule( $next, $schedule->get_recurrence(), $schedule->get_first_date() );
|
||||
$new_action = new ActionScheduler_Action( $action->get_hook(), $action->get_args(), $new_schedule, $action->get_group() );
|
||||
return $this->store( $new_action );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ActionScheduler_Action $action
|
||||
*
|
||||
* @return int The ID of the stored action
|
||||
*/
|
||||
protected function store( ActionScheduler_Action $action ) {
|
||||
$store = ActionScheduler_Store::instance();
|
||||
return $store->save_action( $action );
|
||||
}
|
||||
}
|
@ -1,154 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_AdminView
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {
|
||||
|
||||
private static $admin_view = NULL;
|
||||
|
||||
private static $screen_id = 'tools_page_action-scheduler';
|
||||
|
||||
/** @var ActionScheduler_ListTable */
|
||||
protected $list_table;
|
||||
|
||||
/**
|
||||
* @return ActionScheduler_AdminView
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public static function instance() {
|
||||
|
||||
if ( empty( self::$admin_view ) ) {
|
||||
$class = apply_filters('action_scheduler_admin_view_class', 'ActionScheduler_AdminView');
|
||||
self::$admin_view = new $class();
|
||||
}
|
||||
|
||||
return self::$admin_view;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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_action( 'woocommerce_system_status_report', array( $this, 'system_status_report' ) );
|
||||
add_filter( 'woocommerce_admin_status_tabs', array( $this, 'register_system_status_tab' ) );
|
||||
}
|
||||
|
||||
add_action( 'admin_menu', array( $this, 'register_menu' ) );
|
||||
|
||||
add_action( 'current_screen', array( $this, 'add_help_tabs' ) );
|
||||
}
|
||||
}
|
||||
|
||||
public function system_status_report() {
|
||||
$table = new ActionScheduler_wcSystemStatus( ActionScheduler::store() );
|
||||
$table->render();
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers action-scheduler into WooCommerce > System status.
|
||||
*
|
||||
* @param array $tabs An associative array of tab key => label.
|
||||
* @return array $tabs An associative array of tab key => label, including Action Scheduler's tabs
|
||||
*/
|
||||
public function register_system_status_tab( array $tabs ) {
|
||||
$tabs['action-scheduler'] = __( 'Scheduled Actions', 'action-scheduler' );
|
||||
|
||||
return $tabs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Include Action Scheduler's administration under the Tools menu.
|
||||
*
|
||||
* A menu under the Tools menu is important for backward compatibility (as that's
|
||||
* where it started), and also provides more convenient access than the WooCommerce
|
||||
* System Status page, and for sites where WooCommerce isn't active.
|
||||
*/
|
||||
public function register_menu() {
|
||||
$hook_suffix = add_submenu_page(
|
||||
'tools.php',
|
||||
__( 'Scheduled Actions', 'action-scheduler' ),
|
||||
__( 'Scheduled Actions', 'action-scheduler' ),
|
||||
'manage_options',
|
||||
'action-scheduler',
|
||||
array( $this, 'render_admin_ui' )
|
||||
);
|
||||
add_action( 'load-' . $hook_suffix , array( $this, 'process_admin_ui' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Triggers processing of any pending actions.
|
||||
*/
|
||||
public function process_admin_ui() {
|
||||
$this->get_list_table();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the Admin UI
|
||||
*/
|
||||
public function render_admin_ui() {
|
||||
$table = $this->get_list_table();
|
||||
$table->display_page();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the admin UI object and process any requested actions.
|
||||
*
|
||||
* @return ActionScheduler_ListTable
|
||||
*/
|
||||
protected function get_list_table() {
|
||||
if ( null === $this->list_table ) {
|
||||
$this->list_table = new ActionScheduler_ListTable( ActionScheduler::store(), ActionScheduler::logger(), ActionScheduler::runner() );
|
||||
$this->list_table->process_actions();
|
||||
}
|
||||
|
||||
return $this->list_table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide more information about the screen and its data in the help tab.
|
||||
*/
|
||||
public function add_help_tabs() {
|
||||
$screen = get_current_screen();
|
||||
|
||||
if ( ! $screen || self::$screen_id != $screen->id ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$as_version = ActionScheduler_Versions::instance()->latest_version();
|
||||
$screen->add_help_tab(
|
||||
array(
|
||||
'id' => 'action_scheduler_about',
|
||||
'title' => __( 'About', 'action-scheduler' ),
|
||||
'content' =>
|
||||
'<h2>' . sprintf( __( 'About Action Scheduler %s', 'action-scheduler' ), $as_version ) . '</h2>' .
|
||||
'<p>' .
|
||||
__( 'Action Scheduler is a scalable, traceable job queue for background processing large sets of actions. Action Scheduler works by triggering an action hook to run at some time in the future. Scheduled actions can also be scheduled to run on a recurring schedule.', 'action-scheduler' ) .
|
||||
'</p>',
|
||||
)
|
||||
);
|
||||
|
||||
$screen->add_help_tab(
|
||||
array(
|
||||
'id' => 'action_scheduler_columns',
|
||||
'title' => __( 'Columns', 'action-scheduler' ),
|
||||
'content' =>
|
||||
'<h2>' . __( 'Scheduled Action Columns', 'action-scheduler' ) . '</h2>' .
|
||||
'<ul>' .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Hook', 'action-scheduler' ), __( 'Name of the action hook that will be triggered.', 'action-scheduler' ) ) .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Status', 'action-scheduler' ), __( 'Action statuses are Pending, Complete, Canceled, Failed', 'action-scheduler' ) ) .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Arguments', 'action-scheduler' ), __( 'Optional data array passed to the action hook.', 'action-scheduler' ) ) .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Group', 'action-scheduler' ), __( 'Optional action group.', 'action-scheduler' ) ) .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Recurrence', 'action-scheduler' ), __( 'The action\'s schedule frequency.', 'action-scheduler' ) ) .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Scheduled', 'action-scheduler' ), __( 'The date/time the action is/was scheduled to run.', 'action-scheduler' ) ) .
|
||||
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Log', 'action-scheduler' ), __( 'Activity log for the action.', 'action-scheduler' ) ) .
|
||||
'</ul>',
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
@ -1,97 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* ActionScheduler_AsyncRequest_QueueRunner
|
||||
*/
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
/**
|
||||
* ActionScheduler_AsyncRequest_QueueRunner class.
|
||||
*/
|
||||
class ActionScheduler_AsyncRequest_QueueRunner extends WP_Async_Request {
|
||||
|
||||
/**
|
||||
* Data store for querying actions
|
||||
*
|
||||
* @var ActionScheduler_Store
|
||||
* @access protected
|
||||
*/
|
||||
protected $store;
|
||||
|
||||
/**
|
||||
* Prefix for ajax hooks
|
||||
*
|
||||
* @var string
|
||||
* @access protected
|
||||
*/
|
||||
protected $prefix = 'as';
|
||||
|
||||
/**
|
||||
* Action for ajax hooks
|
||||
*
|
||||
* @var string
|
||||
* @access protected
|
||||
*/
|
||||
protected $action = 'async_request_queue_runner';
|
||||
|
||||
/**
|
||||
* Initiate new async request
|
||||
*/
|
||||
public function __construct( ActionScheduler_Store $store ) {
|
||||
parent::__construct();
|
||||
$this->store = $store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle async requests
|
||||
*
|
||||
* Run a queue, and maybe dispatch another async request to run another queue
|
||||
* if there are still pending actions after completing a queue in this request.
|
||||
*/
|
||||
protected function handle() {
|
||||
do_action( 'action_scheduler_run_queue', 'Async Request' ); // run a queue in the same way as WP Cron, but declare the Async Request context
|
||||
|
||||
$sleep_seconds = $this->get_sleep_seconds();
|
||||
|
||||
if ( $sleep_seconds ) {
|
||||
sleep( $sleep_seconds );
|
||||
}
|
||||
|
||||
$this->maybe_dispatch();
|
||||
}
|
||||
|
||||
/**
|
||||
* If the async request runner is needed and allowed to run, dispatch a request.
|
||||
*/
|
||||
public function maybe_dispatch() {
|
||||
if ( ! $this->allow() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->dispatch();
|
||||
ActionScheduler_QueueRunner::instance()->unhook_dispatch_async_request();
|
||||
}
|
||||
|
||||
/**
|
||||
* Only allow async requests when needed.
|
||||
*
|
||||
* Also allow 3rd party code to disable running actions via async requests.
|
||||
*/
|
||||
protected function allow() {
|
||||
|
||||
if ( ! has_action( 'action_scheduler_run_queue' ) || ActionScheduler::runner()->has_maximum_concurrent_batches() || ! $this->store->has_pending_actions_due() ) {
|
||||
$allow = false;
|
||||
} else {
|
||||
$allow = true;
|
||||
}
|
||||
|
||||
return apply_filters( 'action_scheduler_allow_async_request_runner', $allow );
|
||||
}
|
||||
|
||||
/**
|
||||
* Chaining async requests can crash MySQL. A brief sleep call in PHP prevents that.
|
||||
*/
|
||||
protected function get_sleep_seconds() {
|
||||
return apply_filters( 'action_scheduler_async_request_sleep_seconds', 5, $this );
|
||||
}
|
||||
}
|
@ -1,99 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_Compatibility
|
||||
*/
|
||||
class ActionScheduler_Compatibility {
|
||||
|
||||
/**
|
||||
* Converts a shorthand byte value to an integer byte value.
|
||||
*
|
||||
* Wrapper for wp_convert_hr_to_bytes(), moved to load.php in WordPress 4.6 from media.php
|
||||
*
|
||||
* @link https://secure.php.net/manual/en/function.ini-get.php
|
||||
* @link https://secure.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
|
||||
*
|
||||
* @param string $value A (PHP ini) byte value, either shorthand or ordinary.
|
||||
* @return int An integer byte value.
|
||||
*/
|
||||
public static function convert_hr_to_bytes( $value ) {
|
||||
if ( function_exists( 'wp_convert_hr_to_bytes' ) ) {
|
||||
return wp_convert_hr_to_bytes( $value );
|
||||
}
|
||||
|
||||
$value = strtolower( trim( $value ) );
|
||||
$bytes = (int) $value;
|
||||
|
||||
if ( false !== strpos( $value, 'g' ) ) {
|
||||
$bytes *= GB_IN_BYTES;
|
||||
} elseif ( false !== strpos( $value, 'm' ) ) {
|
||||
$bytes *= MB_IN_BYTES;
|
||||
} elseif ( false !== strpos( $value, 'k' ) ) {
|
||||
$bytes *= KB_IN_BYTES;
|
||||
}
|
||||
|
||||
// Deal with large (float) values which run into the maximum integer size.
|
||||
return min( $bytes, PHP_INT_MAX );
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to raise the PHP memory limit for memory intensive processes.
|
||||
*
|
||||
* Only allows raising the existing limit and prevents lowering it.
|
||||
*
|
||||
* Wrapper for wp_raise_memory_limit(), added in WordPress v4.6.0
|
||||
*
|
||||
* @return bool|int|string The limit that was set or false on failure.
|
||||
*/
|
||||
public static function raise_memory_limit() {
|
||||
if ( function_exists( 'wp_raise_memory_limit' ) ) {
|
||||
return wp_raise_memory_limit( 'admin' );
|
||||
}
|
||||
|
||||
$current_limit = @ini_get( 'memory_limit' );
|
||||
$current_limit_int = self::convert_hr_to_bytes( $current_limit );
|
||||
|
||||
if ( -1 === $current_limit_int ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$wp_max_limit = WP_MAX_MEMORY_LIMIT;
|
||||
$wp_max_limit_int = self::convert_hr_to_bytes( $wp_max_limit );
|
||||
$filtered_limit = apply_filters( 'admin_memory_limit', $wp_max_limit );
|
||||
$filtered_limit_int = self::convert_hr_to_bytes( $filtered_limit );
|
||||
|
||||
if ( -1 === $filtered_limit_int || ( $filtered_limit_int > $wp_max_limit_int && $filtered_limit_int > $current_limit_int ) ) {
|
||||
if ( false !== @ini_set( 'memory_limit', $filtered_limit ) ) {
|
||||
return $filtered_limit;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} elseif ( -1 === $wp_max_limit_int || $wp_max_limit_int > $current_limit_int ) {
|
||||
if ( false !== @ini_set( 'memory_limit', $wp_max_limit ) ) {
|
||||
return $wp_max_limit;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to raise the PHP timeout for time intensive processes.
|
||||
*
|
||||
* Only allows raising the existing limit and prevents lowering it. Wrapper for wc_set_time_limit(), when available.
|
||||
*
|
||||
* @param int The time limit in seconds.
|
||||
*/
|
||||
public static function raise_time_limit( $limit = 0 ) {
|
||||
if ( $limit < ini_get( 'max_execution_time' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ( function_exists( 'wc_set_time_limit' ) ) {
|
||||
wc_set_time_limit( $limit );
|
||||
} elseif ( function_exists( 'set_time_limit' ) && false === strpos( ini_get( 'disable_functions' ), 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
|
||||
@set_time_limit( $limit );
|
||||
}
|
||||
}
|
||||
}
|
@ -1,187 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Action_Scheduler\Migration\Controller;
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_DataController
|
||||
*
|
||||
* The main plugin/initialization class for the data stores.
|
||||
*
|
||||
* Responsible for hooking everything up with WordPress.
|
||||
*
|
||||
* @package Action_Scheduler
|
||||
*
|
||||
* @since 3.0.0
|
||||
*/
|
||||
class ActionScheduler_DataController {
|
||||
/** Action data store class name. */
|
||||
const DATASTORE_CLASS = 'ActionScheduler_DBStore';
|
||||
|
||||
/** Logger data store class name. */
|
||||
const LOGGER_CLASS = 'ActionScheduler_DBLogger';
|
||||
|
||||
/** Migration status option name. */
|
||||
const STATUS_FLAG = 'action_scheduler_migration_status';
|
||||
|
||||
/** Migration status option value. */
|
||||
const STATUS_COMPLETE = 'complete';
|
||||
|
||||
/** Migration minimum required PHP version. */
|
||||
const MIN_PHP_VERSION = '5.5';
|
||||
|
||||
/** @var ActionScheduler_DataController */
|
||||
private static $instance;
|
||||
|
||||
/** @var int */
|
||||
private static $sleep_time = 0;
|
||||
|
||||
/** @var int */
|
||||
private static $free_ticks = 50;
|
||||
|
||||
/**
|
||||
* Get a flag indicating whether the migration environment dependencies are met.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function dependencies_met() {
|
||||
$php_support = version_compare( PHP_VERSION, self::MIN_PHP_VERSION, '>=' );
|
||||
return $php_support && apply_filters( 'action_scheduler_migration_dependencies_met', true );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a flag indicating whether the migration is complete.
|
||||
*
|
||||
* @return bool Whether the flag has been set marking the migration as complete
|
||||
*/
|
||||
public static function is_migration_complete() {
|
||||
return get_option( self::STATUS_FLAG ) === self::STATUS_COMPLETE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the migration as complete.
|
||||
*/
|
||||
public static function mark_migration_complete() {
|
||||
update_option( self::STATUS_FLAG, self::STATUS_COMPLETE );
|
||||
}
|
||||
|
||||
/**
|
||||
* Unmark migration when a plugin is de-activated. Will not work in case of silent activation, for example in an update.
|
||||
* We do this to mitigate the bug of lost actions which happens if there was an AS 2.x to AS 3.x migration in the past, but that plugin is now
|
||||
* deactivated and the site was running on AS 2.x again.
|
||||
*/
|
||||
public static function mark_migration_incomplete() {
|
||||
delete_option( self::STATUS_FLAG );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the action store class name.
|
||||
*
|
||||
* @param string $class Classname of the store class.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function set_store_class( $class ) {
|
||||
return self::DATASTORE_CLASS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the action logger class name.
|
||||
*
|
||||
* @param string $class Classname of the logger class.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function set_logger_class( $class ) {
|
||||
return self::LOGGER_CLASS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the sleep time in seconds.
|
||||
*
|
||||
* @param integer $sleep_time The number of seconds to pause before resuming operation.
|
||||
*/
|
||||
public static function set_sleep_time( $sleep_time ) {
|
||||
self::$sleep_time = (int) $sleep_time;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the tick count required for freeing memory.
|
||||
*
|
||||
* @param integer $free_ticks The number of ticks to free memory on.
|
||||
*/
|
||||
public static function set_free_ticks( $free_ticks ) {
|
||||
self::$free_ticks = (int) $free_ticks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Free memory if conditions are met.
|
||||
*
|
||||
* @param int $ticks Current tick count.
|
||||
*/
|
||||
public static function maybe_free_memory( $ticks ) {
|
||||
if ( self::$free_ticks && 0 === $ticks % self::$free_ticks ) {
|
||||
self::free_memory();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduce memory footprint by clearing the database query and object caches.
|
||||
*/
|
||||
public static function free_memory() {
|
||||
if ( 0 < self::$sleep_time ) {
|
||||
/* translators: %d: amount of time */
|
||||
\WP_CLI::warning( sprintf( _n( 'Stopped the insanity for %d second', 'Stopped the insanity for %d seconds', self::$sleep_time, 'action-scheduler' ), self::$sleep_time ) );
|
||||
sleep( self::$sleep_time );
|
||||
}
|
||||
|
||||
\WP_CLI::warning( __( 'Attempting to reduce used memory...', 'action-scheduler' ) );
|
||||
|
||||
/**
|
||||
* @var $wpdb \wpdb
|
||||
* @var $wp_object_cache \WP_Object_Cache
|
||||
*/
|
||||
global $wpdb, $wp_object_cache;
|
||||
|
||||
$wpdb->queries = array();
|
||||
|
||||
if ( ! is_a( $wp_object_cache, 'WP_Object_Cache' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$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
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to table datastores if migration is complete.
|
||||
* Otherwise, proceed with the migration if the dependencies have been met.
|
||||
*/
|
||||
public static function init() {
|
||||
if ( self::is_migration_complete() ) {
|
||||
add_filter( 'action_scheduler_store_class', array( 'ActionScheduler_DataController', 'set_store_class' ), 100 );
|
||||
add_filter( 'action_scheduler_logger_class', array( 'ActionScheduler_DataController', 'set_logger_class' ), 100 );
|
||||
add_action( 'deactivate_plugin', array( 'ActionScheduler_DataController', 'mark_migration_incomplete' ) );
|
||||
} elseif ( self::dependencies_met() ) {
|
||||
Controller::init();
|
||||
}
|
||||
|
||||
add_action( 'action_scheduler/progress_tick', array( 'ActionScheduler_DataController', 'maybe_free_memory' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Singleton factory.
|
||||
*/
|
||||
public static function instance() {
|
||||
if ( ! isset( self::$instance ) ) {
|
||||
self::$instance = new static();
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
}
|
@ -1,76 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* ActionScheduler DateTime class.
|
||||
*
|
||||
* This is a custom extension to DateTime that
|
||||
*/
|
||||
class ActionScheduler_DateTime extends DateTime {
|
||||
|
||||
/**
|
||||
* UTC offset.
|
||||
*
|
||||
* Only used when a timezone is not set. When a timezone string is
|
||||
* used, this will be set to 0.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $utcOffset = 0;
|
||||
|
||||
/**
|
||||
* 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' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the UTC offset.
|
||||
*
|
||||
* This represents a fixed offset instead of a timezone setting.
|
||||
*
|
||||
* @param $offset
|
||||
*/
|
||||
public function setUtcOffset( $offset ) {
|
||||
$this->utcOffset = intval( $offset );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the timezone offset.
|
||||
*
|
||||
* @return int
|
||||
* @link http://php.net/manual/en/datetime.getoffset.php
|
||||
*/
|
||||
public function getOffset() {
|
||||
return $this->utcOffset ? $this->utcOffset : parent::getOffset();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the TimeZone associated with the DateTime
|
||||
*
|
||||
* @param DateTimeZone $timezone
|
||||
*
|
||||
* @return static
|
||||
* @link http://php.net/manual/en/datetime.settimezone.php
|
||||
*/
|
||||
public function setTimezone( $timezone ) {
|
||||
$this->utcOffset = 0;
|
||||
parent::setTimezone( $timezone );
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the timestamp with the WordPress timezone offset added or subtracted.
|
||||
*
|
||||
* @since 3.0.0
|
||||
* @return int
|
||||
*/
|
||||
public function getOffsetTimestamp() {
|
||||
return $this->getTimestamp() + $this->getOffset();
|
||||
}
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* ActionScheduler Exception Interface.
|
||||
*
|
||||
* Facilitates catching Exceptions unique to Action Scheduler.
|
||||
*
|
||||
* @package ActionScheduler
|
||||
* @since %VERSION%
|
||||
*/
|
||||
interface ActionScheduler_Exception {}
|
@ -1,55 +0,0 @@
|
||||
<?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_execution_ignored', 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 );
|
||||
remove_action( 'action_scheduler_after_execute', array( $this, 'untrack_action' ), 0 );
|
||||
remove_action( 'action_scheduler_execution_ignored', array( $this, 'untrack_action' ), 0 );
|
||||
remove_action( 'action_scheduler_failed_execution', array( $this, 'untrack_action' ), 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 );
|
||||
}
|
||||
}
|
||||
}
|
@ -1,47 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* InvalidAction Exception.
|
||||
*
|
||||
* Used for identifying actions that are invalid in some way.
|
||||
*
|
||||
* @package ActionScheduler
|
||||
*/
|
||||
class ActionScheduler_InvalidActionException extends \InvalidArgumentException implements ActionScheduler_Exception {
|
||||
|
||||
/**
|
||||
* Create a new exception when the action's schedule cannot be fetched.
|
||||
*
|
||||
* @param string $action_id The action ID with bad args.
|
||||
* @return static
|
||||
*/
|
||||
public static function from_schedule( $action_id, $schedule ) {
|
||||
$message = sprintf(
|
||||
/* translators: 1: action ID 2: schedule */
|
||||
__( 'Action [%1$s] has an invalid schedule: %2$s', 'action-scheduler' ),
|
||||
$action_id,
|
||||
var_export( $schedule, true )
|
||||
);
|
||||
|
||||
return new static( $message );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new exception when the action's args cannot be decoded to an array.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*
|
||||
* @param string $action_id The action ID with bad args.
|
||||
* @return static
|
||||
*/
|
||||
public static function from_decoding_args( $action_id, $args = array() ) {
|
||||
$message = sprintf(
|
||||
/* translators: 1: action ID 2: arguments */
|
||||
__( 'Action [%1$s] has invalid arguments. It cannot be JSON decoded to an array. $args = %2$s', 'action-scheduler' ),
|
||||
$action_id,
|
||||
var_export( $args, true )
|
||||
);
|
||||
|
||||
return new static( $message );
|
||||
}
|
||||
}
|
@ -1,612 +0,0 @@
|
||||
<?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,
|
||||
/* translators: %s: amount of time */
|
||||
'names' => _n_noop( '%s year', '%s years', 'action-scheduler' ),
|
||||
),
|
||||
array(
|
||||
'seconds' => MONTH_IN_SECONDS,
|
||||
/* translators: %s: amount of time */
|
||||
'names' => _n_noop( '%s month', '%s months', 'action-scheduler' ),
|
||||
),
|
||||
array(
|
||||
'seconds' => WEEK_IN_SECONDS,
|
||||
/* translators: %s: amount of time */
|
||||
'names' => _n_noop( '%s week', '%s weeks', 'action-scheduler' ),
|
||||
),
|
||||
array(
|
||||
'seconds' => DAY_IN_SECONDS,
|
||||
/* translators: %s: amount of time */
|
||||
'names' => _n_noop( '%s day', '%s days', 'action-scheduler' ),
|
||||
),
|
||||
array(
|
||||
'seconds' => HOUR_IN_SECONDS,
|
||||
/* translators: %s: amount of time */
|
||||
'names' => _n_noop( '%s hour', '%s hours', 'action-scheduler' ),
|
||||
),
|
||||
array(
|
||||
'seconds' => MINUTE_IN_SECONDS,
|
||||
/* translators: %s: amount of time */
|
||||
'names' => _n_noop( '%s minute', '%s minutes', 'action-scheduler' ),
|
||||
),
|
||||
array(
|
||||
'seconds' => 1,
|
||||
/* translators: %s: amount of time */
|
||||
'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 ) {
|
||||
$schedule = $action->get_schedule();
|
||||
if ( $schedule->is_recurring() ) {
|
||||
$recurrence = $schedule->get_recurrence();
|
||||
|
||||
if ( is_numeric( $recurrence ) ) {
|
||||
/* translators: %s: time interval */
|
||||
return sprintf( __( 'Every %s', 'action-scheduler' ), self::human_interval( $recurrence ) );
|
||||
} else {
|
||||
return $recurrence;
|
||||
}
|
||||
}
|
||||
|
||||
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 apply_filters( 'action_scheduler_list_table_column_args', '', $row );
|
||||
}
|
||||
|
||||
$row_html = '<ul>';
|
||||
foreach ( $row['args'] as $key => $value ) {
|
||||
$row_html .= sprintf( '<li><code>%s => %s</code></li>', esc_html( var_export( $key, true ) ), esc_html( var_export( $value, true ) ) );
|
||||
}
|
||||
$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 O' ) ), 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_name' ] ) ) {
|
||||
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 is manually executed.
|
||||
* 3. Tables are missing.
|
||||
*/
|
||||
public function display_admin_notices() {
|
||||
global $wpdb;
|
||||
|
||||
if ( ( is_a( $this->store, 'ActionScheduler_HybridStore' ) || is_a( $this->store, 'ActionScheduler_DBStore' ) ) && apply_filters( 'action_scheduler_enable_recreate_data_store', true ) ) {
|
||||
$table_list = array(
|
||||
'actionscheduler_actions',
|
||||
'actionscheduler_logs',
|
||||
'actionscheduler_groups',
|
||||
'actionscheduler_claims',
|
||||
);
|
||||
|
||||
$found_tables = $wpdb->get_col( "SHOW TABLES LIKE '{$wpdb->prefix}actionscheduler%'" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
foreach ( $table_list as $table_name ) {
|
||||
if ( ! in_array( $wpdb->prefix . $table_name, $found_tables ) ) {
|
||||
$this->admin_notices[] = array(
|
||||
'class' => 'error',
|
||||
'message' => __( 'It appears one or more database tables were missing. Attempting to re-create the missing table(s).' , 'action-scheduler' ),
|
||||
);
|
||||
$this->recreate_tables();
|
||||
parent::display_admin_notices();
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ( $this->runner->has_maximum_concurrent_batches() ) {
|
||||
$claim_count = $this->store->get_claim_count();
|
||||
$this->admin_notices[] = array(
|
||||
'class' => 'updated',
|
||||
'message' => sprintf(
|
||||
/* translators: %s: amount of claims */
|
||||
_n(
|
||||
'Maximum simultaneous queues already in progress (%s queue). No additional queues will begin processing until the current queues are complete.',
|
||||
'Maximum simultaneous queues already in progress (%s queues). No additional queues will begin processing until the current queues are complete.',
|
||||
$claim_count,
|
||||
'action-scheduler'
|
||||
),
|
||||
$claim_count
|
||||
),
|
||||
);
|
||||
} elseif ( $this->store->has_pending_actions_due() ) {
|
||||
|
||||
$async_request_lock_expiration = ActionScheduler::lock()->get_expiration( 'async-request-runner' );
|
||||
|
||||
// No lock set or lock expired
|
||||
if ( false === $async_request_lock_expiration || $async_request_lock_expiration < time() ) {
|
||||
$in_progress_url = add_query_arg( 'status', 'in-progress', remove_query_arg( 'status' ) );
|
||||
/* translators: %s: process URL */
|
||||
$async_request_message = sprintf( __( 'A new queue has begun processing. <a href="%s">View actions in-progress »</a>', 'action-scheduler' ), esc_url( $in_progress_url ) );
|
||||
} else {
|
||||
/* translators: %d: seconds */
|
||||
$async_request_message = sprintf( __( 'The next queue will begin processing in approximately %d seconds.', 'action-scheduler' ), $async_request_lock_expiration - time() );
|
||||
}
|
||||
|
||||
$this->admin_notices[] = array(
|
||||
'class' => 'notice notice-info',
|
||||
'message' => $async_request_message,
|
||||
);
|
||||
}
|
||||
|
||||
$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' :
|
||||
/* translators: %s: action HTML */
|
||||
$action_message_html = sprintf( __( 'Successfully executed action: %s', 'action-scheduler' ), $action_hook_html );
|
||||
break;
|
||||
case 'cancel' :
|
||||
/* translators: %s: action HTML */
|
||||
$action_message_html = sprintf( __( 'Successfully canceled action: %s', 'action-scheduler' ), $action_hook_html );
|
||||
break;
|
||||
default :
|
||||
/* translators: %s: action HTML */
|
||||
$action_message_html = sprintf( __( 'Successfully processed change for action: %s', 'action-scheduler' ), $action_hook_html );
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
$class = 'error';
|
||||
/* translators: 1: action HTML 2: action ID 3: error message */
|
||||
$action_message_html = sprintf( __( 'Could not process change for action: "%1$s" (ID: %2$d). Error: %3$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->get_date() ) {
|
||||
return '0000-00-00 00:00:00';
|
||||
}
|
||||
|
||||
$next_timestamp = $schedule->get_date()->getTimestamp();
|
||||
|
||||
$schedule_display_string .= $schedule->get_date()->format( 'Y-m-d H:i:s O' );
|
||||
$schedule_display_string .= '<br/>';
|
||||
|
||||
if ( gmdate( 'U' ) > $next_timestamp ) {
|
||||
/* translators: %s: date interval */
|
||||
$schedule_display_string .= sprintf( __( ' (%s ago)', 'action-scheduler' ), self::human_interval( gmdate( 'U' ) - $next_timestamp ) );
|
||||
} else {
|
||||
/* translators: %s: date interval */
|
||||
$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' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Force the data store schema updates.
|
||||
*/
|
||||
protected function recreate_tables() {
|
||||
if ( is_a( $this->store, 'ActionScheduler_HybridStore' ) ) {
|
||||
$store = $this->store;
|
||||
} else {
|
||||
$store = new ActionScheduler_HybridStore();
|
||||
}
|
||||
add_action( 'action_scheduler/created_table', array( $store, 'set_autoincrement' ), 10, 2 );
|
||||
|
||||
$store_schema = new ActionScheduler_StoreSchema();
|
||||
$logger_schema = new ActionScheduler_LoggerSchema();
|
||||
$store_schema->register_tables( true );
|
||||
$logger_schema->register_tables( true );
|
||||
|
||||
remove_action( 'action_scheduler/created_table', array( $store, 'set_autoincrement' ), 10 );
|
||||
}
|
||||
/**
|
||||
* 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, 'Admin List Table' );
|
||||
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->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;
|
||||
}
|
||||
if ( is_a( $action, 'ActionScheduler_NullAction' ) ) {
|
||||
continue;
|
||||
}
|
||||
$this->items[ $action_id ] = array(
|
||||
'ID' => $action_id,
|
||||
'hook' => $action->get_hook(),
|
||||
'status_name' => $this->store->get_status( $action_id ),
|
||||
'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' );
|
||||
}
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
|
@ -1,11 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_NullLogEntry
|
||||
*/
|
||||
class ActionScheduler_NullLogEntry extends ActionScheduler_LogEntry {
|
||||
public function __construct( $action_id = '', $message = '' ) {
|
||||
// nothing to see here
|
||||
}
|
||||
}
|
||||
|
@ -1,49 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Provide a way to set simple transient locks to block behaviour
|
||||
* for up-to a given duration.
|
||||
*
|
||||
* Class ActionScheduler_OptionLock
|
||||
* @since 3.0.0
|
||||
*/
|
||||
class ActionScheduler_OptionLock extends ActionScheduler_Lock {
|
||||
|
||||
/**
|
||||
* Set a lock using options for a given amount of time (60 seconds by default).
|
||||
*
|
||||
* Using an autoloaded option avoids running database queries or other resource intensive tasks
|
||||
* on frequently triggered hooks, like 'init' or 'shutdown'.
|
||||
*
|
||||
* For example, ActionScheduler_QueueRunner->maybe_dispatch_async_request() uses a lock to avoid
|
||||
* calling ActionScheduler_QueueRunner->has_maximum_concurrent_batches() every time the 'shutdown',
|
||||
* hook is triggered, because that method calls ActionScheduler_QueueRunner->store->get_claim_count()
|
||||
* to find the current number of claims in the database.
|
||||
*
|
||||
* @param string $lock_type A string to identify different lock types.
|
||||
* @bool True if lock value has changed, false if not or if set failed.
|
||||
*/
|
||||
public function set( $lock_type ) {
|
||||
return update_option( $this->get_key( $lock_type ), time() + $this->get_duration( $lock_type ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* If a lock is set, return the timestamp it was set to expiry.
|
||||
*
|
||||
* @param string $lock_type A string to identify different lock types.
|
||||
* @return bool|int False if no lock is set, otherwise the timestamp for when the lock is set to expire.
|
||||
*/
|
||||
public function get_expiration( $lock_type ) {
|
||||
return get_option( $this->get_key( $lock_type ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the key to use for storing the lock in the transient
|
||||
*
|
||||
* @param string $lock_type A string to identify different lock types.
|
||||
* @return string
|
||||
*/
|
||||
protected function get_key( $lock_type ) {
|
||||
return sprintf( 'action_scheduler_lock_%s', $lock_type );
|
||||
}
|
||||
}
|
@ -1,155 +0,0 @@
|
||||
<?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;
|
||||
|
||||
/**
|
||||
* 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 ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unclaim pending actions that have not been run within a given time limit.
|
||||
*
|
||||
* When called by ActionScheduler_Abstract_QueueRunner::run_cleanup(), the time limit passed
|
||||
* as a parameter is 10x the time limit used for queue processing.
|
||||
*
|
||||
* @param int $time_limit The number of seconds to allow a queue to run before unclaiming its pending actions. Default 300 (5 minutes).
|
||||
*/
|
||||
public function reset_timeouts( $time_limit = 300 ) {
|
||||
$timeout = apply_filters( 'action_scheduler_timeout_period', $time_limit );
|
||||
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 );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark actions that have been running for more than a given time limit as failed, based on
|
||||
* the assumption some uncatachable and unloggable fatal error occurred during processing.
|
||||
*
|
||||
* When called by ActionScheduler_Abstract_QueueRunner::run_cleanup(), the time limit passed
|
||||
* as a parameter is 10x the time limit used for queue processing.
|
||||
*
|
||||
* @param int $time_limit The number of seconds to allow an action to run before it is considered to have failed. Default 300 (5 minutes).
|
||||
*/
|
||||
public function mark_failures( $time_limit = 300 ) {
|
||||
$timeout = apply_filters( 'action_scheduler_failure_period', $time_limit );
|
||||
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.
|
||||
*
|
||||
* @param int $time_limit The number of seconds to use as the timeout and failure period. Default 300 (5 minutes).
|
||||
* @author Jeremy Pry
|
||||
*/
|
||||
public function clean( $time_limit = 300 ) {
|
||||
$this->delete_old_actions();
|
||||
$this->reset_timeouts( $time_limit );
|
||||
$this->mark_failures( $time_limit );
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 ) );
|
||||
}
|
||||
}
|
@ -1,197 +0,0 @@
|
||||
<?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_AsyncRequest_QueueRunner */
|
||||
protected $async_request;
|
||||
|
||||
/** @var ActionScheduler_QueueRunner */
|
||||
private static $runner = null;
|
||||
|
||||
/**
|
||||
* @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, ActionScheduler_AsyncRequest_QueueRunner $async_request = null ) {
|
||||
parent::__construct( $store, $monitor, $cleaner );
|
||||
|
||||
if ( is_null( $async_request ) ) {
|
||||
$async_request = new ActionScheduler_AsyncRequest_QueueRunner( $this->store );
|
||||
}
|
||||
|
||||
$this->async_request = $async_request;
|
||||
}
|
||||
|
||||
/**
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function init() {
|
||||
|
||||
add_filter( 'cron_schedules', array( self::instance(), 'add_wp_cron_schedule' ) );
|
||||
|
||||
// Check for and remove any WP Cron hook scheduled by Action Scheduler < 3.0.0, which didn't include the $context param
|
||||
$next_timestamp = wp_next_scheduled( self::WP_CRON_HOOK );
|
||||
if ( $next_timestamp ) {
|
||||
wp_unschedule_event( $next_timestamp, self::WP_CRON_HOOK );
|
||||
}
|
||||
|
||||
$cron_context = array( 'WP Cron' );
|
||||
|
||||
if ( ! wp_next_scheduled( self::WP_CRON_HOOK, $cron_context ) ) {
|
||||
$schedule = apply_filters( 'action_scheduler_run_schedule', self::WP_CRON_SCHEDULE );
|
||||
wp_schedule_event( time(), $schedule, self::WP_CRON_HOOK, $cron_context );
|
||||
}
|
||||
|
||||
add_action( self::WP_CRON_HOOK, array( self::instance(), 'run' ) );
|
||||
$this->hook_dispatch_async_request();
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook check for dispatching an async request.
|
||||
*/
|
||||
public function hook_dispatch_async_request() {
|
||||
add_action( 'shutdown', array( $this, 'maybe_dispatch_async_request' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Unhook check for dispatching an async request.
|
||||
*/
|
||||
public function unhook_dispatch_async_request() {
|
||||
remove_action( 'shutdown', array( $this, 'maybe_dispatch_async_request' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if we should dispatch an async request to process actions.
|
||||
*
|
||||
* This method is attached to 'shutdown', so is called frequently. To avoid slowing down
|
||||
* the site, it mitigates the work performed in each request by:
|
||||
* 1. checking if it's in the admin context and then
|
||||
* 2. haven't run on the 'shutdown' hook within the lock time (60 seconds by default)
|
||||
* 3. haven't exceeded the number of allowed batches.
|
||||
*
|
||||
* The order of these checks is important, because they run from a check on a value:
|
||||
* 1. in memory - is_admin() maps to $GLOBALS or the WP_ADMIN constant
|
||||
* 2. in memory - transients use autoloaded options by default
|
||||
* 3. from a database query - has_maximum_concurrent_batches() run the query
|
||||
* $this->store->get_claim_count() to find the current number of claims in the DB.
|
||||
*
|
||||
* If all of these conditions are met, then we request an async runner check whether it
|
||||
* should dispatch a request to process pending actions.
|
||||
*/
|
||||
public function maybe_dispatch_async_request() {
|
||||
if ( is_admin() && ! ActionScheduler::lock()->is_locked( 'async-request-runner' ) ) {
|
||||
// Only start an async queue at most once every 60 seconds
|
||||
ActionScheduler::lock()->set( 'async-request-runner' );
|
||||
$this->async_request->maybe_dispatch();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process actions in the queue. Attached to self::WP_CRON_HOOK i.e. 'action_scheduler_run_queue'
|
||||
*
|
||||
* The $context param of this method defaults to 'WP Cron', because prior to Action Scheduler 3.0.0
|
||||
* that was the only context in which this method was run, and the self::WP_CRON_HOOK hook had no context
|
||||
* passed along with it. New code calling this method directly, or by triggering the self::WP_CRON_HOOK,
|
||||
* should set a context as the first parameter. For an example of this, refer to the code seen in
|
||||
* @see ActionScheduler_AsyncRequest_QueueRunner::handle()
|
||||
*
|
||||
* @param string $context Optional identifer for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
|
||||
* Generally, this should be capitalised and not localised as it's a proper noun.
|
||||
* @return int The number of actions processed.
|
||||
*/
|
||||
public function run( $context = 'WP Cron' ) {
|
||||
ActionScheduler_Compatibility::raise_memory_limit();
|
||||
ActionScheduler_Compatibility::raise_time_limit( $this->get_time_limit() );
|
||||
do_action( 'action_scheduler_before_process_queue' );
|
||||
$this->run_cleanup();
|
||||
$processed_actions = 0;
|
||||
if ( false === $this->has_maximum_concurrent_batches() ) {
|
||||
$batch_size = apply_filters( 'action_scheduler_queue_runner_batch_size', 25 );
|
||||
do {
|
||||
$processed_actions_in_batch = $this->do_batch( $batch_size, $context );
|
||||
$processed_actions += $processed_actions_in_batch;
|
||||
} while ( $processed_actions_in_batch > 0 && ! $this->batch_limits_exceeded( $processed_actions ) ); // keep going until we run out of actions, time, or memory
|
||||
}
|
||||
|
||||
do_action( 'action_scheduler_after_process_queue' );
|
||||
return $processed_actions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a batch of actions pending in the queue.
|
||||
*
|
||||
* Actions are processed by claiming a set of pending actions then processing each one until either the batch
|
||||
* size is completed, or memory or time limits are reached, defined by @see $this->batch_limits_exceeded().
|
||||
*
|
||||
* @param int $size The maximum number of actions to process in the batch.
|
||||
* @param string $context Optional identifer for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
|
||||
* Generally, this should be capitalised and not localised as it's a proper noun.
|
||||
* @return int The number of actions processed.
|
||||
*/
|
||||
protected function do_batch( $size = 100, $context = '' ) {
|
||||
$claim = $this->store->stake_claim($size);
|
||||
$this->monitor->attach($claim);
|
||||
$processed_actions = 0;
|
||||
|
||||
foreach ( $claim->get_actions() as $action_id ) {
|
||||
// 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, $context );
|
||||
$processed_actions++;
|
||||
|
||||
if ( $this->batch_limits_exceeded( $processed_actions ) ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
$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', 'action-scheduler' ),
|
||||
);
|
||||
|
||||
return $schedules;
|
||||
}
|
||||
}
|
@ -1,62 +0,0 @@
|
||||
<?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());
|
||||
}
|
||||
}
|
||||
|
@ -1,115 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_WPCommentCleaner
|
||||
*
|
||||
* @since 3.0.0
|
||||
*/
|
||||
class ActionScheduler_WPCommentCleaner {
|
||||
|
||||
/**
|
||||
* Post migration hook used to cleanup the WP comment table.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected static $cleanup_hook = 'action_scheduler/cleanup_wp_comment_logs';
|
||||
|
||||
/**
|
||||
* An instance of the ActionScheduler_wpCommentLogger class to interact with the comments table.
|
||||
*
|
||||
* This instance should only be used as an interface. It should not be initialized.
|
||||
*
|
||||
* @var ActionScheduler_wpCommentLogger
|
||||
*/
|
||||
protected static $wp_comment_logger = null;
|
||||
|
||||
/**
|
||||
* The key used to store the cached value of whether there are logs in the WP comment table.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected static $has_logs_option_key = 'as_has_wp_comment_logs';
|
||||
|
||||
/**
|
||||
* Initialize the class and attach callbacks.
|
||||
*/
|
||||
public static function init() {
|
||||
if ( empty( self::$wp_comment_logger ) ) {
|
||||
self::$wp_comment_logger = new ActionScheduler_wpCommentLogger();
|
||||
}
|
||||
|
||||
add_action( self::$cleanup_hook, array( __CLASS__, 'delete_all_action_comments' ) );
|
||||
|
||||
// While there are orphaned logs left in the comments table, we need to attach the callbacks which filter comment counts.
|
||||
add_action( 'pre_get_comments', array( self::$wp_comment_logger, 'filter_comment_queries' ), 10, 1 );
|
||||
add_action( 'wp_count_comments', array( self::$wp_comment_logger, '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( self::$wp_comment_logger, 'filter_comment_feed' ), 10, 2 );
|
||||
|
||||
// Action Scheduler may be displayed as a Tools screen or WooCommerce > Status administration screen
|
||||
add_action( 'load-tools_page_action-scheduler', array( __CLASS__, 'register_admin_notice' ) );
|
||||
add_action( 'load-woocommerce_page_wc-status', array( __CLASS__, 'register_admin_notice' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if there are log entries in the wp comments table.
|
||||
*
|
||||
* Uses the flag set on migration completion set by @see self::maybe_schedule_cleanup().
|
||||
*
|
||||
* @return boolean Whether there are scheduled action comments in the comments table.
|
||||
*/
|
||||
public static function has_logs() {
|
||||
return 'yes' === get_option( self::$has_logs_option_key );
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules the WP Post comment table cleanup to run in 6 months if it's not already scheduled.
|
||||
* Attached to the migration complete hook 'action_scheduler/migration_complete'.
|
||||
*/
|
||||
public static function maybe_schedule_cleanup() {
|
||||
if ( (bool) get_comments( array( 'type' => ActionScheduler_wpCommentLogger::TYPE, 'number' => 1, 'fields' => 'ids' ) ) ) {
|
||||
update_option( self::$has_logs_option_key, 'yes' );
|
||||
|
||||
if ( ! as_next_scheduled_action( self::$cleanup_hook ) ) {
|
||||
as_schedule_single_action( gmdate( 'U' ) + ( 6 * MONTH_IN_SECONDS ), self::$cleanup_hook );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete all action comments from the WP Comments table.
|
||||
*/
|
||||
public static function delete_all_action_comments() {
|
||||
global $wpdb;
|
||||
$wpdb->delete( $wpdb->comments, array( 'comment_type' => ActionScheduler_wpCommentLogger::TYPE, 'comment_agent' => ActionScheduler_wpCommentLogger::AGENT ) );
|
||||
delete_option( self::$has_logs_option_key );
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers admin notices about the orphaned action logs.
|
||||
*/
|
||||
public static function register_admin_notice() {
|
||||
add_action( 'admin_notices', array( __CLASS__, 'print_admin_notice' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints details about the orphaned action logs and includes information on where to learn more.
|
||||
*/
|
||||
public static function print_admin_notice() {
|
||||
$next_cleanup_message = '';
|
||||
$next_scheduled_cleanup_hook = as_next_scheduled_action( self::$cleanup_hook );
|
||||
|
||||
if ( $next_scheduled_cleanup_hook ) {
|
||||
/* translators: %s: date interval */
|
||||
$next_cleanup_message = sprintf( __( 'This data will be deleted in %s.', 'action-scheduler' ), human_time_diff( gmdate( 'U' ), $next_scheduled_cleanup_hook ) );
|
||||
}
|
||||
|
||||
$notice = sprintf(
|
||||
/* translators: 1: next cleanup message 2: github issue URL */
|
||||
__( 'Action Scheduler has migrated data to custom tables; however, orphaned log entries exist in the WordPress Comments table. %1$s <a href="%2$s">Learn more »</a>', 'action-scheduler' ),
|
||||
$next_cleanup_message,
|
||||
'https://github.com/woocommerce/action-scheduler/issues/368'
|
||||
);
|
||||
|
||||
echo '<div class="notice notice-warning"><p>' . wp_kses_post( $notice ) . '</p></div>';
|
||||
}
|
||||
}
|
@ -1,157 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_wcSystemStatus
|
||||
*/
|
||||
class ActionScheduler_wcSystemStatus {
|
||||
|
||||
/**
|
||||
* The active data stores
|
||||
*
|
||||
* @var ActionScheduler_Store
|
||||
*/
|
||||
protected $store;
|
||||
|
||||
function __construct( $store ) {
|
||||
$this->store = $store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display action data, including number of actions grouped by status and the oldest & newest action in each status.
|
||||
*
|
||||
* Helpful to identify issues, like a clogged queue.
|
||||
*/
|
||||
public function render() {
|
||||
$action_counts = $this->store->action_counts();
|
||||
$status_labels = $this->store->get_status_labels();
|
||||
$oldest_and_newest = $this->get_oldest_and_newest( array_keys( $status_labels ) );
|
||||
|
||||
$this->get_template( $status_labels, $action_counts, $oldest_and_newest );
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 DateTime
|
||||
*/
|
||||
protected function get_action_status_date( $status, $date_type = 'oldest' ) {
|
||||
|
||||
$order = 'oldest' === $date_type ? 'ASC' : 'DESC';
|
||||
|
||||
$action = $this->store->query_actions( array(
|
||||
'claimed' => false,
|
||||
'status' => $status,
|
||||
'per_page' => 1,
|
||||
'order' => $order,
|
||||
) );
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get oldest or newest scheduled date for a given status.
|
||||
*
|
||||
* @param array $status_labels Set of statuses to find oldest & newest action for.
|
||||
* @param array $action_counts Number of actions grouped by status.
|
||||
* @param array $oldest_and_newest Date of the oldest and newest action with each status.
|
||||
*/
|
||||
protected function get_template( $status_labels, $action_counts, $oldest_and_newest ) {
|
||||
$as_version = ActionScheduler_Versions::instance()->latest_version();
|
||||
$as_datastore = get_class( ActionScheduler_Store::instance() );
|
||||
?>
|
||||
|
||||
<table class="wc_status_table widefat" cellspacing="0">
|
||||
<thead>
|
||||
<tr>
|
||||
<th colspan="5" data-export-label="Action Scheduler"><h2><?php esc_html_e( 'Action Scheduler', 'action-scheduler' ); ?><?php echo wc_help_tip( esc_html__( 'This section shows details of Action Scheduler.', 'action-scheduler' ) ); ?></h2></th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2" data-export-label="Version"><?php esc_html_e( 'Version:', 'action-scheduler' ); ?></td>
|
||||
<td colspan="3"><?php echo esc_html( $as_version ); ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2" data-export-label="Data store"><?php esc_html_e( 'Data store:', 'action-scheduler' ); ?></td>
|
||||
<td colspan="3"><?php echo esc_html( $as_datastore ); ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><strong><?php esc_html_e( 'Action Status', 'action-scheduler' ); ?></strong></td>
|
||||
<td class="help"> </td>
|
||||
<td><strong><?php esc_html_e( 'Count', 'action-scheduler' ); ?></strong></td>
|
||||
<td><strong><?php esc_html_e( 'Oldest Scheduled Date', 'action-scheduler' ); ?></strong></td>
|
||||
<td><strong><?php esc_html_e( 'Newest Scheduled Date', 'action-scheduler' ); ?></strong></td>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php
|
||||
foreach ( $action_counts as $status => $count ) {
|
||||
// WC uses the 3rd column for export, so we need to display more data in that (hidden when viewed as part of the table) and add an empty 2nd column.
|
||||
printf(
|
||||
'<tr><td>%1$s</td><td> </td><td>%2$s<span style="display: none;">, Oldest: %3$s, Newest: %4$s</span></td><td>%3$s</td><td>%4$s</td></tr>',
|
||||
esc_html( $status_labels[ $status ] ),
|
||||
number_format_i18n( $count ),
|
||||
$oldest_and_newest[ $status ]['oldest'],
|
||||
$oldest_and_newest[ $status ]['newest']
|
||||
);
|
||||
}
|
||||
?>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<?php
|
||||
}
|
||||
|
||||
/**
|
||||
* is triggered when invoking inaccessible methods in an object context.
|
||||
*
|
||||
* @param string $name
|
||||
* @param array $arguments
|
||||
*
|
||||
* @return mixed
|
||||
* @link https://php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
|
||||
*/
|
||||
public function __call( $name, $arguments ) {
|
||||
switch ( $name ) {
|
||||
case 'print':
|
||||
_deprecated_function( __CLASS__ . '::print()', '2.2.4', __CLASS__ . '::render()' );
|
||||
return call_user_func_array( array( $this, 'render' ), $arguments );
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
@ -1,197 +0,0 @@
|
||||
<?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 {
|
||||
|
||||
/** @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 ) ) {
|
||||
/* 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.
|
||||
*
|
||||
* @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.
|
||||
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.
|
||||
*
|
||||
* @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' ), 10, 2 );
|
||||
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 = new ProgressBar(
|
||||
/* translators: %d: amount of actions */
|
||||
sprintf( _n( 'Running %d action', 'Running %d actions', $count, 'action-scheduler' ), number_format_i18n( $count ) ),
|
||||
$count
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process actions in the queue.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*
|
||||
* @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() ) ) ) {
|
||||
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.
|
||||
*
|
||||
* @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 int $action_id
|
||||
* @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.
|
||||
*
|
||||
* @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: 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();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,158 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Commands for Action Scheduler.
|
||||
*/
|
||||
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.
|
||||
*
|
||||
* [--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', '' );
|
||||
$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 = $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 )
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
@ -1,148 +0,0 @@
|
||||
<?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 {
|
||||
|
||||
/** @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', [ $this, 'migrate' ], [
|
||||
'shortdesc' => 'Migrates actions to the DB tables store',
|
||||
'synopsis' => [
|
||||
[
|
||||
'type' => 'assoc',
|
||||
'name' => 'batch-size',
|
||||
'optional' => true,
|
||||
'default' => 100,
|
||||
'description' => 'The number of actions to process in each batch',
|
||||
],
|
||||
[
|
||||
'type' => 'assoc',
|
||||
'name' => 'free-memory-on',
|
||||
'optional' => true,
|
||||
'default' => 50,
|
||||
'description' => 'The number of actions to process between freeing memory. 0 disables freeing memory',
|
||||
],
|
||||
[
|
||||
'type' => 'assoc',
|
||||
'name' => 'pause',
|
||||
'optional' => true,
|
||||
'default' => 0,
|
||||
'description' => 'The number of seconds to pause when freeing memory',
|
||||
],
|
||||
[
|
||||
'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, [
|
||||
'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 ) );
|
||||
}, 10, 1 );
|
||||
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 ) );
|
||||
}, 10, 1 );
|
||||
add_action( 'action_scheduler/migrate_action_failed', function ( $action_id ) {
|
||||
WP_CLI::warning( sprintf( 'Failed migrating action with ID %d', $action_id ) );
|
||||
}, 10, 1 );
|
||||
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 ) );
|
||||
}, 10, 1 );
|
||||
add_action( 'action_scheduler/migration_batch_complete', function ( $batch ) {
|
||||
WP_CLI::log( sprintf( 'Completed migration of %d actions', count( $batch ) ) );
|
||||
}, 10, 1 );
|
||||
}
|
||||
}
|
@ -1,119 +0,0 @@
|
||||
<?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 {
|
||||
|
||||
/** @var integer */
|
||||
protected $total_ticks;
|
||||
|
||||
/** @var integer */
|
||||
protected $count;
|
||||
|
||||
/** @var integer */
|
||||
protected $interval;
|
||||
|
||||
/** @var string */
|
||||
protected $message;
|
||||
|
||||
/** @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 );
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
);
|
||||
}
|
||||
}
|
@ -1,304 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Action_Scheduler\WP_CLI\Migration_Command;
|
||||
use Action_Scheduler\Migration\Controller;
|
||||
|
||||
/**
|
||||
* Class ActionScheduler
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
abstract class ActionScheduler {
|
||||
private static $plugin_file = '';
|
||||
/** @var ActionScheduler_ActionFactory */
|
||||
private static $factory = NULL;
|
||||
/** @var bool */
|
||||
private static $data_store_initialized = false;
|
||||
|
||||
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 lock() {
|
||||
return ActionScheduler_Lock::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;
|
||||
$classes_dir = self::plugin_path( 'classes' . $d );
|
||||
$separator = strrpos( $class, '\\' );
|
||||
if ( false !== $separator ) {
|
||||
if ( 0 !== strpos( $class, 'Action_Scheduler' ) ) {
|
||||
return;
|
||||
}
|
||||
$class = substr( $class, $separator + 1 );
|
||||
}
|
||||
|
||||
if ( 'Deprecated' === substr( $class, -10 ) ) {
|
||||
$dir = self::plugin_path( 'deprecated' . $d );
|
||||
} elseif ( self::is_class_abstract( $class ) ) {
|
||||
$dir = $classes_dir . 'abstracts' . $d;
|
||||
} elseif ( self::is_class_migration( $class ) ) {
|
||||
$dir = $classes_dir . 'migration' . $d;
|
||||
} elseif ( 'Schedule' === substr( $class, -8 ) ) {
|
||||
$dir = $classes_dir . 'schedules' . $d;
|
||||
} elseif ( 'Action' === substr( $class, -6 ) ) {
|
||||
$dir = $classes_dir . 'actions' . $d;
|
||||
} elseif ( 'Schema' === substr( $class, -6 ) ) {
|
||||
$dir = $classes_dir . 'schema' . $d;
|
||||
} elseif ( strpos( $class, 'ActionScheduler' ) === 0 ) {
|
||||
$segments = explode( '_', $class );
|
||||
$type = isset( $segments[ 1 ] ) ? $segments[ 1 ] : '';
|
||||
|
||||
switch ( $type ) {
|
||||
case 'WPCLI':
|
||||
$dir = $classes_dir . 'WP_CLI' . $d;
|
||||
break;
|
||||
case 'DBLogger':
|
||||
case 'DBStore':
|
||||
case 'HybridStore':
|
||||
case 'wpPostStore':
|
||||
case 'wpCommentLogger':
|
||||
$dir = $classes_dir . 'data-stores' . $d;
|
||||
break;
|
||||
default:
|
||||
$dir = $classes_dir;
|
||||
break;
|
||||
}
|
||||
} elseif ( self::is_class_cli( $class ) ) {
|
||||
$dir = $classes_dir . 'WP_CLI' . $d;
|
||||
} elseif ( strpos( $class, 'CronExpression' ) === 0 ) {
|
||||
$dir = self::plugin_path( 'lib' . $d . 'cron-expression' . $d );
|
||||
} elseif ( strpos( $class, 'WP_Async_Request' ) === 0 ) {
|
||||
$dir = self::plugin_path( 'lib' . $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' ) );
|
||||
|
||||
/**
|
||||
* Fires in the early stages of Action Scheduler init hook.
|
||||
*/
|
||||
do_action( 'action_scheduler_pre_init' );
|
||||
|
||||
require_once( self::plugin_path( 'functions.php' ) );
|
||||
ActionScheduler_DataController::init();
|
||||
|
||||
$store = self::store();
|
||||
$logger = self::logger();
|
||||
$runner = self::runner();
|
||||
$admin_view = self::admin_view();
|
||||
|
||||
// Ensure initialization on plugin activation.
|
||||
if ( ! did_action( 'init' ) ) {
|
||||
add_action( 'init', array( $admin_view, 'init' ), 0, 0 ); // run before $store::init()
|
||||
add_action( 'init', array( $store, 'init' ), 1, 0 );
|
||||
add_action( 'init', array( $logger, 'init' ), 1, 0 );
|
||||
add_action( 'init', array( $runner, 'init' ), 1, 0 );
|
||||
} else {
|
||||
$admin_view->init();
|
||||
$store->init();
|
||||
$logger->init();
|
||||
$runner->init();
|
||||
}
|
||||
|
||||
if ( apply_filters( 'action_scheduler_load_deprecated_functions', true ) ) {
|
||||
require_once( self::plugin_path( 'deprecated/functions.php' ) );
|
||||
}
|
||||
|
||||
if ( defined( 'WP_CLI' ) && WP_CLI ) {
|
||||
WP_CLI::add_command( 'action-scheduler', 'ActionScheduler_WPCLI_Scheduler_command' );
|
||||
if ( ! ActionScheduler_DataController::is_migration_complete() && Controller::instance()->allow_migration() ) {
|
||||
$command = new Migration_Command();
|
||||
$command->register();
|
||||
}
|
||||
}
|
||||
|
||||
self::$data_store_initialized = true;
|
||||
|
||||
/**
|
||||
* Handle WP comment cleanup after migration.
|
||||
*/
|
||||
if ( is_a( $logger, 'ActionScheduler_DBLogger' ) && ActionScheduler_DataController::is_migration_complete() && ActionScheduler_WPCommentCleaner::has_logs() ) {
|
||||
ActionScheduler_WPCommentCleaner::init();
|
||||
}
|
||||
|
||||
add_action( 'action_scheduler/migration_complete', 'ActionScheduler_WPCommentCleaner::maybe_schedule_cleanup' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the AS data store has been initialized.
|
||||
*
|
||||
* @param string $function_name The name of the function being called. Optional. Default `null`.
|
||||
* @return bool
|
||||
*/
|
||||
public static function is_initialized( $function_name = null ) {
|
||||
if ( ! self::$data_store_initialized && ! empty( $function_name ) ) {
|
||||
$message = sprintf( __( '%s() was called before the Action Scheduler data store was initialized', 'action-scheduler' ), esc_attr( $function_name ) );
|
||||
error_log( $message, E_WARNING );
|
||||
}
|
||||
|
||||
return self::$data_store_initialized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the class is one of our abstract classes.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @param string $class The class name.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected static function is_class_abstract( $class ) {
|
||||
static $abstracts = array(
|
||||
'ActionScheduler' => true,
|
||||
'ActionScheduler_Abstract_ListTable' => true,
|
||||
'ActionScheduler_Abstract_QueueRunner' => true,
|
||||
'ActionScheduler_Abstract_Schedule' => true,
|
||||
'ActionScheduler_Abstract_RecurringSchedule' => true,
|
||||
'ActionScheduler_Lock' => true,
|
||||
'ActionScheduler_Logger' => true,
|
||||
'ActionScheduler_Abstract_Schema' => true,
|
||||
'ActionScheduler_Store' => true,
|
||||
'ActionScheduler_TimezoneHelper' => true,
|
||||
);
|
||||
|
||||
return isset( $abstracts[ $class ] ) && $abstracts[ $class ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the class is one of our migration classes.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @param string $class The class name.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected static function is_class_migration( $class ) {
|
||||
static $migration_segments = array(
|
||||
'ActionMigrator' => true,
|
||||
'BatchFetcher' => true,
|
||||
'DBStoreMigrator' => true,
|
||||
'DryRun' => true,
|
||||
'LogMigrator' => true,
|
||||
'Config' => true,
|
||||
'Controller' => true,
|
||||
'Runner' => true,
|
||||
'Scheduler' => true,
|
||||
);
|
||||
|
||||
$segments = explode( '_', $class );
|
||||
$segment = isset( $segments[ 1 ] ) ? $segments[ 1 ] : $class;
|
||||
|
||||
return isset( $migration_segments[ $segment ] ) && $migration_segments[ $segment ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the class is one of our WP CLI classes.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @param string $class The class name.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected static function is_class_cli( $class ) {
|
||||
static $cli_segments = array(
|
||||
'QueueRunner' => true,
|
||||
'Command' => true,
|
||||
'ProgressBar' => true,
|
||||
);
|
||||
|
||||
$segments = explode( '_', $class );
|
||||
$segment = isset( $segments[ 1 ] ) ? $segments[ 1 ] : $class;
|
||||
|
||||
return isset( $cli_segments[ $segment ] ) && $cli_segments[ $segment ];
|
||||
}
|
||||
|
||||
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 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Issue deprecated warning if an Action Scheduler function is called in the shutdown hook.
|
||||
*
|
||||
* @param string $function_name The name of the function being called.
|
||||
* @deprecated 3.1.6.
|
||||
*/
|
||||
public static function check_shutdown_hook( $function_name ) {
|
||||
_deprecated_function( __FUNCTION__, '3.1.6' );
|
||||
}
|
||||
}
|
@ -1,674 +0,0 @@
|
||||
<?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 to get options from WP_List_Table::get_items_per_page.
|
||||
*/
|
||||
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).
|
||||
*
|
||||
* @deprecated 3.0.0
|
||||
*/
|
||||
protected function translate( $text, $context = '' ) {
|
||||
return $text;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 ] = $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.
|
||||
* validated already by process_bulk_action()
|
||||
*/
|
||||
protected function bulk_delete( array $ids, $ids_sql ) {
|
||||
$store = ActionScheduler::store();
|
||||
foreach ( $ids as $action_id ) {
|
||||
$store->delete( $action_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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" />' ),
|
||||
$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 = sanitize_text_field( $_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[] = $wpdb->prepare('`' . $column . '` like "%%s%"', $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( $label )
|
||||
. '</option>';
|
||||
}
|
||||
|
||||
echo '</select>';
|
||||
}
|
||||
|
||||
submit_button( esc_html__( 'Filter', 'action-scheduler' ), '', '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() ) {
|
||||
/* translators: %s: search query */
|
||||
echo '<span class="subtitle">' . esc_attr( sprintf( __( 'Search results for "%s"', 'action-scheduler' ), $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_filter_url = remove_query_arg( array( 'paged', 's' ), $status_filter_url );
|
||||
$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 || 'ID' === $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>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Process any pending actions.
|
||||
*/
|
||||
public function process_actions() {
|
||||
$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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 esc_html__( 'Search', 'action-scheduler' );
|
||||
}
|
||||
}
|
@ -1,240 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Abstract class with common Queue Cleaner functionality.
|
||||
*/
|
||||
abstract class ActionScheduler_Abstract_QueueRunner extends ActionScheduler_Abstract_QueueRunner_Deprecated {
|
||||
|
||||
/** @var ActionScheduler_QueueCleaner */
|
||||
protected $cleaner;
|
||||
|
||||
/** @var ActionScheduler_FatalErrorMonitor */
|
||||
protected $monitor;
|
||||
|
||||
/** @var ActionScheduler_Store */
|
||||
protected $store;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* 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->created_time = microtime( true );
|
||||
|
||||
$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.
|
||||
* @param string $context Optional identifer for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
|
||||
* Generally, this should be capitalised and not localised as it's a proper noun.
|
||||
*/
|
||||
public function process_action( $action_id, $context = '' ) {
|
||||
try {
|
||||
$valid_action = false;
|
||||
do_action( 'action_scheduler_before_execute', $action_id, $context );
|
||||
|
||||
if ( ActionScheduler_Store::STATUS_PENDING !== $this->store->get_status( $action_id ) ) {
|
||||
do_action( 'action_scheduler_execution_ignored', $action_id, $context );
|
||||
return;
|
||||
}
|
||||
|
||||
$valid_action = true;
|
||||
do_action( 'action_scheduler_begin_execute', $action_id, $context );
|
||||
|
||||
$action = $this->store->fetch_action( $action_id );
|
||||
$this->store->log_execution( $action_id );
|
||||
$action->execute();
|
||||
do_action( 'action_scheduler_after_execute', $action_id, $action, $context );
|
||||
$this->store->mark_complete( $action_id );
|
||||
} catch ( Exception $e ) {
|
||||
if ( $valid_action ) {
|
||||
$this->store->mark_failure( $action_id );
|
||||
do_action( 'action_scheduler_failed_execution', $action_id, $e, $context );
|
||||
} else {
|
||||
do_action( 'action_scheduler_failed_validation', $action_id, $e, $context );
|
||||
}
|
||||
}
|
||||
|
||||
if ( isset( $action ) && is_a( $action, 'ActionScheduler_Action' ) && $action->get_schedule()->is_recurring() ) {
|
||||
$this->schedule_next_instance( $action, $action_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule the next instance of the action if necessary.
|
||||
*
|
||||
* @param ActionScheduler_Action $action
|
||||
* @param int $action_id
|
||||
*/
|
||||
protected function schedule_next_instance( ActionScheduler_Action $action, $action_id ) {
|
||||
try {
|
||||
ActionScheduler::factory()->repeat( $action );
|
||||
} catch ( Exception $e ) {
|
||||
do_action( 'action_scheduler_failed_to_schedule_next_instance', $action_id, $e, $action );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the queue cleaner.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*/
|
||||
protected function run_cleanup() {
|
||||
$this->cleaner->clean( 10 * $this->get_time_limit() );
|
||||
}
|
||||
|
||||
/**
|
||||
* 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', 1 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the number of allowed concurrent batches is met or exceeded.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function has_maximum_concurrent_batches() {
|
||||
return $this->store->get_claim_count() >= $this->get_allowed_concurrent_batches();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the maximum number of seconds a batch can run for.
|
||||
*
|
||||
* @return int The number of seconds.
|
||||
*/
|
||||
protected function get_time_limit() {
|
||||
|
||||
$time_limit = 30;
|
||||
|
||||
// Apply deprecated filter from deprecated get_maximum_execution_time() method
|
||||
if ( has_filter( 'action_scheduler_maximum_execution_time' ) ) {
|
||||
_deprecated_function( 'action_scheduler_maximum_execution_time', '2.1.1', 'action_scheduler_queue_runner_time_limit' );
|
||||
$time_limit = apply_filters( 'action_scheduler_maximum_execution_time', $time_limit );
|
||||
}
|
||||
|
||||
return absint( apply_filters( 'action_scheduler_queue_runner_time_limit', $time_limit ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of seconds the process has been running.
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the host's max execution time is (likely) to be exceeded if processing more actions.
|
||||
*
|
||||
* @param int $processed_actions The number of actions processed so far - used to determine the likelihood of exceeding the time limit if processing another action
|
||||
* @return bool
|
||||
*/
|
||||
protected function time_likely_to_be_exceeded( $processed_actions ) {
|
||||
|
||||
$execution_time = $this->get_execution_time();
|
||||
$max_execution_time = $this->get_time_limit();
|
||||
$time_per_action = $execution_time / $processed_actions;
|
||||
$estimated_time = $execution_time + ( $time_per_action * 3 );
|
||||
$likely_to_be_exceeded = $estimated_time > $max_execution_time;
|
||||
|
||||
return apply_filters( 'action_scheduler_maximum_execution_time_likely_to_be_exceeded', $likely_to_be_exceeded, $this, $processed_actions, $execution_time, $max_execution_time );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get memory limit
|
||||
*
|
||||
* Based on WP_Background_Process::get_memory_limit()
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
protected function get_memory_limit() {
|
||||
if ( function_exists( 'ini_get' ) ) {
|
||||
$memory_limit = ini_get( 'memory_limit' );
|
||||
} else {
|
||||
$memory_limit = '128M'; // Sensible default, and minimum required by WooCommerce
|
||||
}
|
||||
|
||||
if ( ! $memory_limit || -1 === $memory_limit || '-1' === $memory_limit ) {
|
||||
// Unlimited, set to 32GB.
|
||||
$memory_limit = '32G';
|
||||
}
|
||||
|
||||
return ActionScheduler_Compatibility::convert_hr_to_bytes( $memory_limit );
|
||||
}
|
||||
|
||||
/**
|
||||
* Memory exceeded
|
||||
*
|
||||
* Ensures the batch process never exceeds 90% of the maximum WordPress memory.
|
||||
*
|
||||
* Based on WP_Background_Process::memory_exceeded()
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function memory_exceeded() {
|
||||
|
||||
$memory_limit = $this->get_memory_limit() * 0.90;
|
||||
$current_memory = memory_get_usage( true );
|
||||
$memory_exceeded = $current_memory >= $memory_limit;
|
||||
|
||||
return apply_filters( 'action_scheduler_memory_exceeded', $memory_exceeded, $this );
|
||||
}
|
||||
|
||||
/**
|
||||
* See if the batch limits have been exceeded, which is when memory usage is almost at
|
||||
* the maximum limit, or the time to process more actions will exceed the max time limit.
|
||||
*
|
||||
* Based on WC_Background_Process::batch_limits_exceeded()
|
||||
*
|
||||
* @param int $processed_actions The number of actions processed so far - used to determine the likelihood of exceeding the time limit if processing another action
|
||||
* @return bool
|
||||
*/
|
||||
protected function batch_limits_exceeded( $processed_actions ) {
|
||||
return $this->memory_exceeded() || $this->time_likely_to_be_exceeded( $processed_actions );
|
||||
}
|
||||
|
||||
/**
|
||||
* Process actions in the queue.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
* @param string $context Optional identifer for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
|
||||
* Generally, this should be capitalised and not localised as it's a proper noun.
|
||||
* @return int The number of actions processed.
|
||||
*/
|
||||
abstract public function run( $context = '' );
|
||||
}
|
@ -1,102 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_Abstract_RecurringSchedule
|
||||
*/
|
||||
abstract class ActionScheduler_Abstract_RecurringSchedule extends ActionScheduler_Abstract_Schedule {
|
||||
|
||||
/**
|
||||
* The date & time the first instance of this schedule was setup to run (which may not be this instance).
|
||||
*
|
||||
* Schedule objects are attached to an action object. Each schedule stores the run date for that
|
||||
* object as the start date - @see $this->start - and logic to calculate the next run date after
|
||||
* that - @see $this->calculate_next(). The $first_date property also keeps a record of when the very
|
||||
* first instance of this chain of schedules ran.
|
||||
*
|
||||
* @var DateTime
|
||||
*/
|
||||
private $first_date = NULL;
|
||||
|
||||
/**
|
||||
* Timestamp equivalent of @see $this->first_date
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $first_timestamp = NULL;
|
||||
|
||||
/**
|
||||
* The recurrance between each time an action is run using this schedule.
|
||||
* Used to calculate the start date & time. Can be a number of seconds, in the
|
||||
* case of ActionScheduler_IntervalSchedule, or a cron expression, as in the
|
||||
* case of ActionScheduler_CronSchedule. Or something else.
|
||||
*
|
||||
* @var mixed
|
||||
*/
|
||||
protected $recurrence;
|
||||
|
||||
/**
|
||||
* @param DateTime $date The date & time to run the action.
|
||||
* @param mixed $recurrence The data used to determine the schedule's recurrance.
|
||||
* @param DateTime|null $first (Optional) The date & time the first instance of this interval schedule ran. Default null, meaning this is the first instance.
|
||||
*/
|
||||
public function __construct( DateTime $date, $recurrence, DateTime $first = null ) {
|
||||
parent::__construct( $date );
|
||||
$this->first_date = empty( $first ) ? $date : $first;
|
||||
$this->recurrence = $recurrence;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function is_recurring() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the date & time of the first schedule in this recurring series.
|
||||
*
|
||||
* @return DateTime|null
|
||||
*/
|
||||
public function get_first_date() {
|
||||
return clone $this->first_date;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function get_recurrence() {
|
||||
return $this->recurrence;
|
||||
}
|
||||
|
||||
/**
|
||||
* For PHP 5.2 compat, since DateTime objects can't be serialized
|
||||
* @return array
|
||||
*/
|
||||
public function __sleep() {
|
||||
$sleep_params = parent::__sleep();
|
||||
$this->first_timestamp = $this->first_date->getTimestamp();
|
||||
return array_merge( $sleep_params, array(
|
||||
'first_timestamp',
|
||||
'recurrence'
|
||||
) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Unserialize recurring schedules serialized/stored prior to AS 3.0.0
|
||||
*
|
||||
* Prior to Action Scheduler 3.0.0, schedules used different property names to refer
|
||||
* to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
|
||||
* was the same as ActionScheduler_SimpleSchedule::timestamp. This was addressed in
|
||||
* Action Scheduler 3.0.0, where properties and property names were aligned for better
|
||||
* inheritance. To maintain backward compatibility with scheduled serialized and stored
|
||||
* prior to 3.0, we need to correctly map the old property names.
|
||||
*/
|
||||
public function __wakeup() {
|
||||
parent::__wakeup();
|
||||
if ( $this->first_timestamp > 0 ) {
|
||||
$this->first_date = as_get_datetime_object( $this->first_timestamp );
|
||||
} else {
|
||||
$this->first_date = $this->get_date();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,83 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_Abstract_Schedule
|
||||
*/
|
||||
abstract class ActionScheduler_Abstract_Schedule extends ActionScheduler_Schedule_Deprecated {
|
||||
|
||||
/**
|
||||
* The date & time the schedule is set to run.
|
||||
*
|
||||
* @var DateTime
|
||||
*/
|
||||
private $scheduled_date = NULL;
|
||||
|
||||
/**
|
||||
* Timestamp equivalent of @see $this->scheduled_date
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $scheduled_timestamp = NULL;
|
||||
|
||||
/**
|
||||
* @param DateTime $date The date & time to run the action.
|
||||
*/
|
||||
public function __construct( DateTime $date ) {
|
||||
$this->scheduled_date = $date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a schedule should recur.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
abstract public function is_recurring();
|
||||
|
||||
/**
|
||||
* Calculate when the next instance of this schedule would run based on a given date & time.
|
||||
*
|
||||
* @param DateTime $after
|
||||
* @return DateTime
|
||||
*/
|
||||
abstract protected function calculate_next( DateTime $after );
|
||||
|
||||
/**
|
||||
* Get the next date & time when this schedule should run after a given date & time.
|
||||
*
|
||||
* @param DateTime $after
|
||||
* @return DateTime|null
|
||||
*/
|
||||
public function get_next( DateTime $after ) {
|
||||
$after = clone $after;
|
||||
if ( $after > $this->scheduled_date ) {
|
||||
$after = $this->calculate_next( $after );
|
||||
return $after;
|
||||
}
|
||||
return clone $this->scheduled_date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the date & time the schedule is set to run.
|
||||
*
|
||||
* @return DateTime|null
|
||||
*/
|
||||
public function get_date() {
|
||||
return $this->scheduled_date;
|
||||
}
|
||||
|
||||
/**
|
||||
* For PHP 5.2 compat, since DateTime objects can't be serialized
|
||||
* @return array
|
||||
*/
|
||||
public function __sleep() {
|
||||
$this->scheduled_timestamp = $this->scheduled_date->getTimestamp();
|
||||
return array(
|
||||
'scheduled_timestamp',
|
||||
);
|
||||
}
|
||||
|
||||
public function __wakeup() {
|
||||
$this->scheduled_date = as_get_datetime_object( $this->scheduled_timestamp );
|
||||
unset( $this->scheduled_timestamp );
|
||||
}
|
||||
}
|
@ -1,135 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_Abstract_Schema
|
||||
*
|
||||
* @package Action_Scheduler
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*
|
||||
* Utility class for creating/updating custom tables
|
||||
*/
|
||||
abstract class ActionScheduler_Abstract_Schema {
|
||||
|
||||
/**
|
||||
* @var int Increment this value in derived class to trigger a schema update.
|
||||
*/
|
||||
protected $schema_version = 1;
|
||||
|
||||
/**
|
||||
* @var array Names of tables that will be registered by this class.
|
||||
*/
|
||||
protected $tables = [];
|
||||
|
||||
/**
|
||||
* Register tables with WordPress, and create them if needed.
|
||||
*
|
||||
* @param bool $force_update Optional. Default false. Use true to always run the schema update.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function register_tables( $force_update = false ) {
|
||||
global $wpdb;
|
||||
|
||||
// make WP aware of our tables
|
||||
foreach ( $this->tables as $table ) {
|
||||
$wpdb->tables[] = $table;
|
||||
$name = $this->get_full_table_name( $table );
|
||||
$wpdb->$table = $name;
|
||||
}
|
||||
|
||||
// create the tables
|
||||
if ( $this->schema_update_required() || $force_update ) {
|
||||
foreach ( $this->tables as $table ) {
|
||||
$this->update_table( $table );
|
||||
}
|
||||
$this->mark_schema_update_complete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $table The name of the table
|
||||
*
|
||||
* @return string The CREATE TABLE statement, suitable for passing to dbDelta
|
||||
*/
|
||||
abstract protected function get_table_definition( $table );
|
||||
|
||||
/**
|
||||
* Determine if the database schema is out of date
|
||||
* by comparing the integer found in $this->schema_version
|
||||
* with the option set in the WordPress options table
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function schema_update_required() {
|
||||
$option_name = 'schema-' . static::class;
|
||||
$version_found_in_db = get_option( $option_name, 0 );
|
||||
|
||||
// Check for schema option stored by the Action Scheduler Custom Tables plugin in case site has migrated from that plugin with an older schema
|
||||
if ( 0 === $version_found_in_db ) {
|
||||
|
||||
$plugin_option_name = 'schema-';
|
||||
|
||||
switch ( static::class ) {
|
||||
case 'ActionScheduler_StoreSchema' :
|
||||
$plugin_option_name .= 'Action_Scheduler\Custom_Tables\DB_Store_Table_Maker';
|
||||
break;
|
||||
case 'ActionScheduler_LoggerSchema' :
|
||||
$plugin_option_name .= 'Action_Scheduler\Custom_Tables\DB_Logger_Table_Maker';
|
||||
break;
|
||||
}
|
||||
|
||||
$version_found_in_db = get_option( $plugin_option_name, 0 );
|
||||
|
||||
delete_option( $plugin_option_name );
|
||||
}
|
||||
|
||||
return version_compare( $version_found_in_db, $this->schema_version, '<' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the option in WordPress to indicate that
|
||||
* our schema is now up to date
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function mark_schema_update_complete() {
|
||||
$option_name = 'schema-' . static::class;
|
||||
|
||||
// work around race conditions and ensure that our option updates
|
||||
$value_to_save = (string) $this->schema_version . '.0.' . time();
|
||||
|
||||
update_option( $option_name, $value_to_save );
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the schema for the given table
|
||||
*
|
||||
* @param string $table The name of the table to update
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function update_table( $table ) {
|
||||
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
|
||||
$definition = $this->get_table_definition( $table );
|
||||
if ( $definition ) {
|
||||
$updated = dbDelta( $definition );
|
||||
foreach ( $updated as $updated_table => $update_description ) {
|
||||
if ( strpos( $update_description, 'Created table' ) === 0 ) {
|
||||
do_action( 'action_scheduler/created_table', $updated_table, $table );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $table
|
||||
*
|
||||
* @return string The full name of the table, including the
|
||||
* table prefix for the current blog
|
||||
*/
|
||||
protected function get_full_table_name( $table ) {
|
||||
return $GLOBALS[ 'wpdb' ]->prefix . $table;
|
||||
}
|
||||
}
|
@ -1,62 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Abstract class for setting a basic lock to throttle some action.
|
||||
*
|
||||
* Class ActionScheduler_Lock
|
||||
*/
|
||||
abstract class ActionScheduler_Lock {
|
||||
|
||||
/** @var ActionScheduler_Lock */
|
||||
private static $locker = NULL;
|
||||
|
||||
/** @var int */
|
||||
protected static $lock_duration = MINUTE_IN_SECONDS;
|
||||
|
||||
/**
|
||||
* Check if a lock is set for a given lock type.
|
||||
*
|
||||
* @param string $lock_type A string to identify different lock types.
|
||||
* @return bool
|
||||
*/
|
||||
public function is_locked( $lock_type ) {
|
||||
return ( $this->get_expiration( $lock_type ) >= time() );
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a lock.
|
||||
*
|
||||
* @param string $lock_type A string to identify different lock types.
|
||||
* @return bool
|
||||
*/
|
||||
abstract public function set( $lock_type );
|
||||
|
||||
/**
|
||||
* If a lock is set, return the timestamp it was set to expiry.
|
||||
*
|
||||
* @param string $lock_type A string to identify different lock types.
|
||||
* @return bool|int False if no lock is set, otherwise the timestamp for when the lock is set to expire.
|
||||
*/
|
||||
abstract public function get_expiration( $lock_type );
|
||||
|
||||
/**
|
||||
* Get the amount of time to set for a given lock. 60 seconds by default.
|
||||
*
|
||||
* @param string $lock_type A string to identify different lock types.
|
||||
* @return int
|
||||
*/
|
||||
protected function get_duration( $lock_type ) {
|
||||
return apply_filters( 'action_scheduler_lock_duration', self::$lock_duration, $lock_type );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ActionScheduler_Lock
|
||||
*/
|
||||
public static function instance() {
|
||||
if ( empty( self::$locker ) ) {
|
||||
$class = apply_filters( 'action_scheduler_lock_class', 'ActionScheduler_OptionLock' );
|
||||
self::$locker = new $class();
|
||||
}
|
||||
return self::$locker;
|
||||
}
|
||||
}
|
@ -1,176 +0,0 @@
|
||||
<?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 );
|
||||
|
||||
|
||||
/**
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function init() {
|
||||
$this->hook_stored_action();
|
||||
add_action( 'action_scheduler_canceled_action', array( $this, 'log_canceled_action' ), 10, 1 );
|
||||
add_action( 'action_scheduler_begin_execute', array( $this, 'log_started_action' ), 10, 2 );
|
||||
add_action( 'action_scheduler_after_execute', array( $this, 'log_completed_action' ), 10, 3 );
|
||||
add_action( 'action_scheduler_failed_execution', array( $this, 'log_failed_action' ), 10, 3 );
|
||||
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( 'action_scheduler_execution_ignored', array( $this, 'log_ignored_action' ), 10, 2 );
|
||||
add_action( 'action_scheduler_failed_fetch_action', array( $this, 'log_failed_fetch_action' ), 10, 2 );
|
||||
add_action( 'action_scheduler_failed_to_schedule_next_instance', array( $this, 'log_failed_schedule_next_instance' ), 10, 2 );
|
||||
add_action( 'action_scheduler_bulk_cancel_actions', array( $this, 'bulk_log_cancel_actions' ), 10, 1 );
|
||||
}
|
||||
|
||||
public function hook_stored_action() {
|
||||
add_action( 'action_scheduler_stored_action', array( $this, 'log_stored_action' ) );
|
||||
}
|
||||
|
||||
public function unhook_stored_action() {
|
||||
remove_action( 'action_scheduler_stored_action', array( $this, 'log_stored_action' ) );
|
||||
}
|
||||
|
||||
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, $context = '' ) {
|
||||
if ( ! empty( $context ) ) {
|
||||
/* translators: %s: context */
|
||||
$message = sprintf( __( 'action started via %s', 'action-scheduler' ), $context );
|
||||
} else {
|
||||
$message = __( 'action started', 'action-scheduler' );
|
||||
}
|
||||
$this->log( $action_id, $message );
|
||||
}
|
||||
|
||||
public function log_completed_action( $action_id, $action = NULL, $context = '' ) {
|
||||
if ( ! empty( $context ) ) {
|
||||
/* translators: %s: context */
|
||||
$message = sprintf( __( 'action complete via %s', 'action-scheduler' ), $context );
|
||||
} else {
|
||||
$message = __( 'action complete', 'action-scheduler' );
|
||||
}
|
||||
$this->log( $action_id, $message );
|
||||
}
|
||||
|
||||
public function log_failed_action( $action_id, Exception $exception, $context = '' ) {
|
||||
if ( ! empty( $context ) ) {
|
||||
/* translators: 1: context 2: exception message */
|
||||
$message = sprintf( __( 'action failed via %1$s: %2$s', 'action-scheduler' ), $context, $exception->getMessage() );
|
||||
} else {
|
||||
/* translators: %s: exception message */
|
||||
$message = sprintf( __( 'action failed: %s', 'action-scheduler' ), $exception->getMessage() );
|
||||
}
|
||||
$this->log( $action_id, $message );
|
||||
}
|
||||
|
||||
public function log_timed_out_action( $action_id, $timeout ) {
|
||||
/* translators: %s: amount of time */
|
||||
$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 ) ) {
|
||||
/* translators: 1: error message 2: filename 3: line */
|
||||
$this->log( $action_id, sprintf( __( 'unexpected shutdown: PHP Fatal error %1$s in %2$s on line %3$s', 'action-scheduler' ), $error['message'], $error['file'], $error['line'] ) );
|
||||
}
|
||||
}
|
||||
|
||||
public function log_reset_action( $action_id ) {
|
||||
$this->log( $action_id, __( 'action reset', 'action-scheduler' ) );
|
||||
}
|
||||
|
||||
public function log_ignored_action( $action_id, $context = '' ) {
|
||||
if ( ! empty( $context ) ) {
|
||||
/* translators: %s: context */
|
||||
$message = sprintf( __( 'action ignored via %s', 'action-scheduler' ), $context );
|
||||
} else {
|
||||
$message = __( 'action ignored', 'action-scheduler' );
|
||||
}
|
||||
$this->log( $action_id, $message );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $action_id
|
||||
* @param Exception|NULL $exception The exception which occured when fetching the action. NULL by default for backward compatibility.
|
||||
*
|
||||
* @return ActionScheduler_LogEntry[]
|
||||
*/
|
||||
public function log_failed_fetch_action( $action_id, Exception $exception = NULL ) {
|
||||
|
||||
if ( ! is_null( $exception ) ) {
|
||||
/* translators: %s: exception message */
|
||||
$log_message = sprintf( __( 'There was a failure fetching this action: %s', 'action-scheduler' ), $exception->getMessage() );
|
||||
} else {
|
||||
$log_message = __( 'There was a failure fetching this action', 'action-scheduler' );
|
||||
}
|
||||
|
||||
$this->log( $action_id, $log_message );
|
||||
}
|
||||
|
||||
public function log_failed_schedule_next_instance( $action_id, Exception $exception ) {
|
||||
/* translators: %s: exception message */
|
||||
$this->log( $action_id, sprintf( __( 'There was a failure scheduling the next instance of this action: %s', 'action-scheduler' ), $exception->getMessage() ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk add cancel action log entries.
|
||||
*
|
||||
* Implemented here for backward compatibility. Should be implemented in parent loggers
|
||||
* for more performant bulk logging.
|
||||
*
|
||||
* @param array $action_ids List of action ID.
|
||||
*/
|
||||
public function bulk_log_cancel_actions( $action_ids ) {
|
||||
if ( empty( $action_ids ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ( $action_ids as $action_id ) {
|
||||
$this->log_canceled_action( $action_id );
|
||||
}
|
||||
}
|
||||
}
|
@ -1,345 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_Store
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
abstract class ActionScheduler_Store extends ActionScheduler_Store_Deprecated {
|
||||
const STATUS_COMPLETE = 'complete';
|
||||
const STATUS_PENDING = 'pending';
|
||||
const STATUS_RUNNING = 'in-progress';
|
||||
const STATUS_FAILED = 'failed';
|
||||
const STATUS_CANCELED = 'canceled';
|
||||
const DEFAULT_CLASS = 'ActionScheduler_wpPostStore';
|
||||
|
||||
/** @var ActionScheduler_Store */
|
||||
private static $store = NULL;
|
||||
|
||||
/** @var int */
|
||||
protected static $max_args_length = 191;
|
||||
|
||||
/**
|
||||
* @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 int 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 Hook name/slug.
|
||||
* @param array $params Hook arguments.
|
||||
* @return string ID of the next action matching the criteria.
|
||||
*/
|
||||
abstract public function find_action( $hook, $params = array() );
|
||||
|
||||
/**
|
||||
* @param array $query Query parameters.
|
||||
* @param string $query_type Whether to select or count the results. Default, select.
|
||||
*
|
||||
* @return array|int The IDs of or count of actions matching the query.
|
||||
*/
|
||||
abstract public function query_actions( $query = array(), $query_type = 'select' );
|
||||
|
||||
/**
|
||||
* 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()->get_date() : $scheduled_date;
|
||||
if ( ! $next ) {
|
||||
return '0000-00-00 00:00:00';
|
||||
}
|
||||
$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()->get_date() : $scheduled_date;
|
||||
if ( ! $next ) {
|
||||
return '0000-00-00 00:00:00';
|
||||
}
|
||||
|
||||
ActionScheduler_TimezoneHelper::set_local_timezone( $next );
|
||||
return $next->format( 'Y-m-d H:i:s' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that we could decode action arguments.
|
||||
*
|
||||
* @param mixed $args The decoded arguments.
|
||||
* @param int $action_id The action ID.
|
||||
*
|
||||
* @throws ActionScheduler_InvalidActionException When the decoded arguments are invalid.
|
||||
*/
|
||||
protected function validate_args( $args, $action_id ) {
|
||||
// Ensure we have an array of args.
|
||||
if ( ! is_array( $args ) ) {
|
||||
throw ActionScheduler_InvalidActionException::from_decoding_args( $action_id );
|
||||
}
|
||||
|
||||
// Validate JSON decoding if possible.
|
||||
if ( function_exists( 'json_last_error' ) && JSON_ERROR_NONE !== json_last_error() ) {
|
||||
throw ActionScheduler_InvalidActionException::from_decoding_args( $action_id, $args );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a ActionScheduler_Schedule object.
|
||||
*
|
||||
* @param mixed $schedule The unserialized ActionScheduler_Schedule object.
|
||||
* @param int $action_id The action ID.
|
||||
*
|
||||
* @throws ActionScheduler_InvalidActionException When the schedule is invalid.
|
||||
*/
|
||||
protected function validate_schedule( $schedule, $action_id ) {
|
||||
if ( empty( $schedule ) || ! is_a( $schedule, 'ActionScheduler_Schedule' ) ) {
|
||||
throw ActionScheduler_InvalidActionException::from_schedule( $action_id, $schedule );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* InnoDB indexes have a maximum size of 767 bytes by default, which is only 191 characters with utf8mb4.
|
||||
*
|
||||
* Previously, AS wasn't concerned about args length, as we used the (unindex) post_content column. However,
|
||||
* with custom tables, we use an indexed VARCHAR column instead.
|
||||
*
|
||||
* @param ActionScheduler_Action $action Action to be validated.
|
||||
* @throws InvalidArgumentException When json encoded args is too long.
|
||||
*/
|
||||
protected function validate_action( ActionScheduler_Action $action ) {
|
||||
if ( strlen( json_encode( $action->get_args() ) ) > static::$max_args_length ) {
|
||||
throw new InvalidArgumentException( sprintf( __( 'ActionScheduler_Action::$args too long. To ensure the args column can be indexed, action args should not be more than %d characters when encoded as JSON.', 'action-scheduler' ), static::$max_args_length ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel pending actions by hook.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @param string $hook Hook name.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function cancel_actions_by_hook( $hook ) {
|
||||
$action_ids = true;
|
||||
while ( ! empty( $action_ids ) ) {
|
||||
$action_ids = $this->query_actions(
|
||||
array(
|
||||
'hook' => $hook,
|
||||
'status' => self::STATUS_PENDING,
|
||||
'per_page' => 1000,
|
||||
)
|
||||
);
|
||||
|
||||
$this->bulk_cancel_actions( $action_ids );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel pending actions by group.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @param string $group Group slug.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function cancel_actions_by_group( $group ) {
|
||||
$action_ids = true;
|
||||
while ( ! empty( $action_ids ) ) {
|
||||
$action_ids = $this->query_actions(
|
||||
array(
|
||||
'group' => $group,
|
||||
'status' => self::STATUS_PENDING,
|
||||
'per_page' => 1000,
|
||||
)
|
||||
);
|
||||
|
||||
$this->bulk_cancel_actions( $action_ids );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel a set of action IDs.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @param array $action_ids List of action IDs.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function bulk_cancel_actions( $action_ids ) {
|
||||
foreach ( $action_ids as $action_id ) {
|
||||
$this->cancel_action( $action_id );
|
||||
}
|
||||
|
||||
do_action( 'action_scheduler_bulk_cancel_actions', $action_ids );
|
||||
}
|
||||
|
||||
/**
|
||||
* @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' ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there are any pending scheduled actions due to run.
|
||||
*
|
||||
* @param ActionScheduler_Action $action
|
||||
* @param DateTime $scheduled_date (optional)
|
||||
* @return string
|
||||
*/
|
||||
public function has_pending_actions_due() {
|
||||
$pending_actions = $this->query_actions( array(
|
||||
'date' => as_get_datetime_object(),
|
||||
'status' => ActionScheduler_Store::STATUS_PENDING,
|
||||
) );
|
||||
|
||||
return ! empty( $pending_actions );
|
||||
}
|
||||
|
||||
/**
|
||||
* Callable initialization function optionally overridden in derived classes.
|
||||
*/
|
||||
public function init() {}
|
||||
|
||||
/**
|
||||
* Callable function to mark an action as migrated optionally overridden in derived classes.
|
||||
*/
|
||||
public function mark_migrated( $action_id ) {}
|
||||
|
||||
/**
|
||||
* @return ActionScheduler_Store
|
||||
*/
|
||||
public static function instance() {
|
||||
if ( empty( self::$store ) ) {
|
||||
$class = apply_filters( 'action_scheduler_store_class', self::DEFAULT_CLASS );
|
||||
self::$store = new $class();
|
||||
}
|
||||
return self::$store;
|
||||
}
|
||||
}
|
@ -1,152 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_TimezoneHelper
|
||||
*/
|
||||
abstract class ActionScheduler_TimezoneHelper {
|
||||
private static $local_timezone = NULL;
|
||||
|
||||
/**
|
||||
* Set a DateTime's timezone to the WordPress site's timezone, or a UTC offset
|
||||
* if no timezone string is available.
|
||||
*
|
||||
* @since 2.1.0
|
||||
*
|
||||
* @param DateTime $date
|
||||
* @return ActionScheduler_DateTime
|
||||
*/
|
||||
public static function set_local_timezone( DateTime $date ) {
|
||||
|
||||
// Accept a DateTime for easier backward compatibility, even though we require methods on ActionScheduler_DateTime
|
||||
if ( ! is_a( $date, 'ActionScheduler_DateTime' ) ) {
|
||||
$date = as_get_datetime_object( $date->format( 'U' ) );
|
||||
}
|
||||
|
||||
if ( get_option( 'timezone_string' ) ) {
|
||||
$date->setTimezone( new DateTimeZone( self::get_local_timezone_string() ) );
|
||||
} else {
|
||||
$date->setUtcOffset( self::get_local_timezone_offset() );
|
||||
}
|
||||
|
||||
return $date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to retrieve the timezone string for a site until a WP core method exists
|
||||
* (see https://core.trac.wordpress.org/ticket/24730).
|
||||
*
|
||||
* Adapted from wc_timezone_string() and https://secure.php.net/manual/en/function.timezone-name-from-abbr.php#89155.
|
||||
*
|
||||
* If no timezone string is set, and its not possible to match the UTC offset set for the site to a timezone
|
||||
* string, then an empty string will be returned, and the UTC offset should be used to set a DateTime's
|
||||
* timezone.
|
||||
*
|
||||
* @since 2.1.0
|
||||
* @return string PHP timezone string for the site or empty if no timezone string is available.
|
||||
*/
|
||||
protected static function get_local_timezone_string( $reset = false ) {
|
||||
// If site timezone string exists, return it.
|
||||
$timezone = get_option( 'timezone_string' );
|
||||
if ( $timezone ) {
|
||||
return $timezone;
|
||||
}
|
||||
|
||||
// Get UTC offset, if it isn't set then return UTC.
|
||||
$utc_offset = intval( get_option( 'gmt_offset', 0 ) );
|
||||
if ( 0 === $utc_offset ) {
|
||||
return 'UTC';
|
||||
}
|
||||
|
||||
// Adjust UTC offset from hours to seconds.
|
||||
$utc_offset *= 3600;
|
||||
|
||||
// Attempt to guess the timezone string from the UTC offset.
|
||||
$timezone = timezone_name_from_abbr( '', $utc_offset );
|
||||
if ( $timezone ) {
|
||||
return $timezone;
|
||||
}
|
||||
|
||||
// Last try, guess timezone string manually.
|
||||
foreach ( timezone_abbreviations_list() as $abbr ) {
|
||||
foreach ( $abbr as $city ) {
|
||||
if ( (bool) date( 'I' ) === (bool) $city['dst'] && $city['timezone_id'] && intval( $city['offset'] ) === $utc_offset ) {
|
||||
return $city['timezone_id'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No timezone string
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get timezone offset in seconds.
|
||||
*
|
||||
* @since 2.1.0
|
||||
* @return float
|
||||
*/
|
||||
protected static function get_local_timezone_offset() {
|
||||
$timezone = get_option( 'timezone_string' );
|
||||
|
||||
if ( $timezone ) {
|
||||
$timezone_object = new DateTimeZone( $timezone );
|
||||
return $timezone_object->getOffset( new DateTime( 'now' ) );
|
||||
} else {
|
||||
return floatval( get_option( 'gmt_offset', 0 ) ) * HOUR_IN_SECONDS;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated 2.1.0
|
||||
*/
|
||||
public static function get_local_timezone( $reset = FALSE ) {
|
||||
_deprecated_function( __FUNCTION__, '2.1.0', 'ActionScheduler_TimezoneHelper::set_local_timezone()' );
|
||||
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, 1 );
|
||||
|
||||
// If there's no timezone string, try again with no DST.
|
||||
if ( false === $tzstring ) {
|
||||
$tzstring = timezone_name_from_abbr( '', $gmt_offset, 0 );
|
||||
}
|
||||
|
||||
// Try mapping to the first abbreviation we can find.
|
||||
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 ) {
|
||||
// If there's no valid timezone ID, keep looking.
|
||||
if ( null === $city['timezone_id'] ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$tzstring = $city['timezone_id'];
|
||||
break 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we still have no valid string, then fall back to UTC.
|
||||
if ( false === $tzstring ) {
|
||||
$tzstring = 'UTC';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self::$local_timezone = new DateTimeZone($tzstring);
|
||||
}
|
||||
return self::$local_timezone;
|
||||
}
|
||||
}
|
@ -1,75 +0,0 @@
|
||||
<?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(), array_values( $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;
|
||||
}
|
||||
}
|
@ -1,23 +0,0 @@
|
||||
<?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 );
|
||||
if ( is_null( $schedule ) ) {
|
||||
$this->set_schedule( new ActionScheduler_NullSchedule() );
|
||||
}
|
||||
}
|
||||
}
|
@ -1,16 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_FinishedAction
|
||||
*/
|
||||
class ActionScheduler_FinishedAction extends ActionScheduler_Action {
|
||||
|
||||
public function execute() {
|
||||
// don't execute
|
||||
}
|
||||
|
||||
public function is_finished() {
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
@ -1,16 +0,0 @@
|
||||
<?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
|
||||
}
|
||||
}
|
||||
|
@ -1,146 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_DBLogger
|
||||
*
|
||||
* Action logs data table data store.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*/
|
||||
class ActionScheduler_DBLogger extends ActionScheduler_Logger {
|
||||
|
||||
/**
|
||||
* Add a record to an action log.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
* @param string $message Message to be saved in the log entry.
|
||||
* @param DateTime $date Timestamp of the log entry.
|
||||
*
|
||||
* @return int 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;
|
||||
}
|
||||
|
||||
$date_gmt = $date->format( 'Y-m-d H:i:s' );
|
||||
ActionScheduler_TimezoneHelper::set_local_timezone( $date );
|
||||
$date_local = $date->format( 'Y-m-d H:i:s' );
|
||||
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$wpdb->insert( $wpdb->actionscheduler_logs, [
|
||||
'action_id' => $action_id,
|
||||
'message' => $message,
|
||||
'log_date_gmt' => $date_gmt,
|
||||
'log_date_local' => $date_local,
|
||||
], [ '%d', '%s', '%s', '%s' ] );
|
||||
|
||||
return $wpdb->insert_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve an action log entry.
|
||||
*
|
||||
* @param int $entry_id Log entry ID.
|
||||
*
|
||||
* @return ActionScheduler_LogEntry
|
||||
*/
|
||||
public function get_entry( $entry_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$entry = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_logs} WHERE log_id=%d", $entry_id ) );
|
||||
|
||||
return $this->create_entry_from_db_record( $entry );
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an action log entry from a database record.
|
||||
*
|
||||
* @param object $record Log entry database record object.
|
||||
*
|
||||
* @return ActionScheduler_LogEntry
|
||||
*/
|
||||
private function create_entry_from_db_record( $record ) {
|
||||
if ( empty( $record ) ) {
|
||||
return new ActionScheduler_NullLogEntry();
|
||||
}
|
||||
|
||||
$date = as_get_datetime_object( $record->log_date_gmt );
|
||||
|
||||
return new ActionScheduler_LogEntry( $record->action_id, $record->message, $date );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the an action's log entries from the database.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*
|
||||
* @return ActionScheduler_LogEntry[]
|
||||
*/
|
||||
public function get_logs( $action_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
|
||||
$records = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_logs} WHERE action_id=%d", $action_id ) );
|
||||
|
||||
return array_map( [ $this, 'create_entry_from_db_record' ], $records );
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the data store.
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function init() {
|
||||
|
||||
$table_maker = new ActionScheduler_LoggerSchema();
|
||||
$table_maker->register_tables();
|
||||
|
||||
parent::init();
|
||||
|
||||
add_action( 'action_scheduler_deleted_action', [ $this, 'clear_deleted_action_logs' ], 10, 1 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the action logs for an action.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function clear_deleted_action_logs( $action_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$wpdb->delete( $wpdb->actionscheduler_logs, [ 'action_id' => $action_id, ], [ '%d' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk add cancel action log entries.
|
||||
*
|
||||
* @param array $action_ids List of action ID.
|
||||
*/
|
||||
public function bulk_log_cancel_actions( $action_ids ) {
|
||||
if ( empty( $action_ids ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$date = as_get_datetime_object();
|
||||
$date_gmt = $date->format( 'Y-m-d H:i:s' );
|
||||
ActionScheduler_TimezoneHelper::set_local_timezone( $date );
|
||||
$date_local = $date->format( 'Y-m-d H:i:s' );
|
||||
$message = __( 'action canceled', 'action-scheduler' );
|
||||
$format = '(%d, ' . $wpdb->prepare( '%s, %s, %s', $message, $date_gmt, $date_local ) . ')';
|
||||
$sql_query = "INSERT {$wpdb->actionscheduler_logs} (action_id, message, log_date_gmt, log_date_local) VALUES ";
|
||||
$value_rows = [];
|
||||
|
||||
foreach ( $action_ids as $action_id ) {
|
||||
$value_rows[] = $wpdb->prepare( $format, $action_id );
|
||||
}
|
||||
$sql_query .= implode( ',', $value_rows );
|
||||
|
||||
$wpdb->query( $sql_query );
|
||||
}
|
||||
}
|
@ -1,870 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_DBStore
|
||||
*
|
||||
* Action data table data store.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*/
|
||||
class ActionScheduler_DBStore extends ActionScheduler_Store {
|
||||
|
||||
/**
|
||||
* Used to share information about the before_date property of claims internally.
|
||||
*
|
||||
* This is used in preference to passing the same information as a method param
|
||||
* for backwards-compatibility reasons.
|
||||
*
|
||||
* @var DateTime|null
|
||||
*/
|
||||
private $claim_before_date = null;
|
||||
|
||||
/** @var int */
|
||||
protected static $max_args_length = 8000;
|
||||
|
||||
/** @var int */
|
||||
protected static $max_index_length = 191;
|
||||
|
||||
/**
|
||||
* Initialize the data store
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function init() {
|
||||
$table_maker = new ActionScheduler_StoreSchema();
|
||||
$table_maker->register_tables();
|
||||
}
|
||||
|
||||
/**
|
||||
* Save an action.
|
||||
*
|
||||
* @param ActionScheduler_Action $action Action object.
|
||||
* @param DateTime $date Optional schedule date. Default null.
|
||||
*
|
||||
* @return int Action ID.
|
||||
*/
|
||||
public function save_action( ActionScheduler_Action $action, \DateTime $date = null ) {
|
||||
try {
|
||||
|
||||
$this->validate_action( $action );
|
||||
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$data = [
|
||||
'hook' => $action->get_hook(),
|
||||
'status' => ( $action->is_finished() ? self::STATUS_COMPLETE : self::STATUS_PENDING ),
|
||||
'scheduled_date_gmt' => $this->get_scheduled_date_string( $action, $date ),
|
||||
'scheduled_date_local' => $this->get_scheduled_date_string_local( $action, $date ),
|
||||
'schedule' => serialize( $action->get_schedule() ),
|
||||
'group_id' => $this->get_group_id( $action->get_group() ),
|
||||
];
|
||||
$args = wp_json_encode( $action->get_args() );
|
||||
if ( strlen( $args ) <= static::$max_index_length ) {
|
||||
$data['args'] = $args;
|
||||
} else {
|
||||
$data['args'] = $this->hash_args( $args );
|
||||
$data['extended_args'] = $args;
|
||||
}
|
||||
|
||||
$table_name = ! empty( $wpdb->actionscheduler_actions ) ? $wpdb->actionscheduler_actions : $wpdb->prefix . 'actionscheduler_actions';
|
||||
$wpdb->insert( $table_name, $data );
|
||||
$action_id = $wpdb->insert_id;
|
||||
|
||||
if ( is_wp_error( $action_id ) ) {
|
||||
throw new RuntimeException( $action_id->get_error_message() );
|
||||
}
|
||||
elseif ( empty( $action_id ) ) {
|
||||
throw new RuntimeException( $wpdb->last_error ? $wpdb->last_error : __( 'Database error.', 'action-scheduler' ) );
|
||||
}
|
||||
|
||||
do_action( 'action_scheduler_stored_action', $action_id );
|
||||
|
||||
return $action_id;
|
||||
} catch ( \Exception $e ) {
|
||||
/* translators: %s: error message */
|
||||
throw new \RuntimeException( sprintf( __( 'Error saving action: %s', 'action-scheduler' ), $e->getMessage() ), 0 );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a hash from json_encoded $args using MD5 as this isn't for security.
|
||||
*
|
||||
* @param string $args JSON encoded action args.
|
||||
* @return string
|
||||
*/
|
||||
protected function hash_args( $args ) {
|
||||
return md5( $args );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get action args query param value from action args.
|
||||
*
|
||||
* @param array $args Action args.
|
||||
* @return string
|
||||
*/
|
||||
protected function get_args_for_query( $args ) {
|
||||
$encoded = wp_json_encode( $args );
|
||||
if ( strlen( $encoded ) <= static::$max_index_length ) {
|
||||
return $encoded;
|
||||
}
|
||||
return $this->hash_args( $encoded );
|
||||
}
|
||||
/**
|
||||
* Get a group's ID based on its name/slug.
|
||||
*
|
||||
* @param string $slug The string name of a group.
|
||||
* @param bool $create_if_not_exists Whether to create the group if it does not already exist. Default, true - create the group.
|
||||
*
|
||||
* @return int The group's ID, if it exists or is created, or 0 if it does not exist and is not created.
|
||||
*/
|
||||
protected function get_group_id( $slug, $create_if_not_exists = true ) {
|
||||
if ( empty( $slug ) ) {
|
||||
return 0;
|
||||
}
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$group_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT group_id FROM {$wpdb->actionscheduler_groups} WHERE slug=%s", $slug ) );
|
||||
if ( empty( $group_id ) && $create_if_not_exists ) {
|
||||
$group_id = $this->create_group( $slug );
|
||||
}
|
||||
|
||||
return $group_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an action group.
|
||||
*
|
||||
* @param string $slug Group slug.
|
||||
*
|
||||
* @return int Group ID.
|
||||
*/
|
||||
protected function create_group( $slug ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$wpdb->insert( $wpdb->actionscheduler_groups, [ 'slug' => $slug ] );
|
||||
|
||||
return (int) $wpdb->insert_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve an action.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*
|
||||
* @return ActionScheduler_Action
|
||||
*/
|
||||
public function fetch_action( $action_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$data = $wpdb->get_row( $wpdb->prepare(
|
||||
"SELECT a.*, g.slug AS `group` FROM {$wpdb->actionscheduler_actions} a LEFT JOIN {$wpdb->actionscheduler_groups} g ON a.group_id=g.group_id WHERE a.action_id=%d",
|
||||
$action_id
|
||||
) );
|
||||
|
||||
if ( empty( $data ) ) {
|
||||
return $this->get_null_action();
|
||||
}
|
||||
|
||||
if ( ! empty( $data->extended_args ) ) {
|
||||
$data->args = $data->extended_args;
|
||||
unset( $data->extended_args );
|
||||
}
|
||||
|
||||
try {
|
||||
$action = $this->make_action_from_db_record( $data );
|
||||
} catch ( ActionScheduler_InvalidActionException $exception ) {
|
||||
do_action( 'action_scheduler_failed_fetch_action', $action_id, $exception );
|
||||
return $this->get_null_action();
|
||||
}
|
||||
|
||||
return $action;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a null action.
|
||||
*
|
||||
* @return ActionScheduler_NullAction
|
||||
*/
|
||||
protected function get_null_action() {
|
||||
return new ActionScheduler_NullAction();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an action from a database record.
|
||||
*
|
||||
* @param object $data Action database record.
|
||||
*
|
||||
* @return ActionScheduler_Action|ActionScheduler_CanceledAction|ActionScheduler_FinishedAction
|
||||
*/
|
||||
protected function make_action_from_db_record( $data ) {
|
||||
|
||||
$hook = $data->hook;
|
||||
$args = json_decode( $data->args, true );
|
||||
$schedule = unserialize( $data->schedule );
|
||||
|
||||
$this->validate_args( $args, $data->action_id );
|
||||
$this->validate_schedule( $schedule, $data->action_id );
|
||||
|
||||
if ( empty( $schedule ) ) {
|
||||
$schedule = new ActionScheduler_NullSchedule();
|
||||
}
|
||||
$group = $data->group ? $data->group : '';
|
||||
|
||||
return ActionScheduler::factory()->get_stored_action( $data->status, $data->hook, $args, $schedule, $group );
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an action.
|
||||
*
|
||||
* @param string $hook Action hook.
|
||||
* @param array $params Parameters of the action to find.
|
||||
*
|
||||
* @return string|null ID of the next action matching the criteria or NULL if not found.
|
||||
*/
|
||||
public function find_action( $hook, $params = [] ) {
|
||||
$params = wp_parse_args( $params, [
|
||||
'args' => null,
|
||||
'status' => self::STATUS_PENDING,
|
||||
'group' => '',
|
||||
] );
|
||||
|
||||
/** @var wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$query = "SELECT a.action_id FROM {$wpdb->actionscheduler_actions} a";
|
||||
$args = [];
|
||||
if ( ! empty( $params[ 'group' ] ) ) {
|
||||
$query .= " INNER JOIN {$wpdb->actionscheduler_groups} g ON g.group_id=a.group_id AND g.slug=%s";
|
||||
$args[] = $params[ 'group' ];
|
||||
}
|
||||
$query .= " WHERE a.hook=%s";
|
||||
$args[] = $hook;
|
||||
if ( ! is_null( $params[ 'args' ] ) ) {
|
||||
$query .= " AND a.args=%s";
|
||||
$args[] = $this->get_args_for_query( $params[ 'args' ] );
|
||||
}
|
||||
|
||||
$order = 'ASC';
|
||||
if ( ! empty( $params[ 'status' ] ) ) {
|
||||
$query .= " AND a.status=%s";
|
||||
$args[] = $params[ 'status' ];
|
||||
|
||||
if ( self::STATUS_PENDING == $params[ 'status' ] ) {
|
||||
$order = 'ASC'; // Find the next action that matches.
|
||||
} else {
|
||||
$order = 'DESC'; // Find the most recent action that matches.
|
||||
}
|
||||
}
|
||||
|
||||
$query .= " ORDER BY scheduled_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.
|
||||
*
|
||||
* @return string SQL statement 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 value for select or count parameter. Cannot query actions.', 'action-scheduler' ) );
|
||||
}
|
||||
|
||||
$query = wp_parse_args( $query, [
|
||||
'hook' => '',
|
||||
'args' => null,
|
||||
'date' => null,
|
||||
'date_compare' => '<=',
|
||||
'modified' => null,
|
||||
'modified_compare' => '<=',
|
||||
'group' => '',
|
||||
'status' => '',
|
||||
'claimed' => null,
|
||||
'per_page' => 5,
|
||||
'offset' => 0,
|
||||
'orderby' => 'date',
|
||||
'order' => 'ASC',
|
||||
] );
|
||||
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$sql = ( 'count' === $select_or_count ) ? 'SELECT count(a.action_id)' : 'SELECT a.action_id';
|
||||
$sql .= " FROM {$wpdb->actionscheduler_actions} a";
|
||||
$sql_params = [];
|
||||
|
||||
if ( ! empty( $query[ 'group' ] ) || 'group' === $query[ 'orderby' ] ) {
|
||||
$sql .= " LEFT JOIN {$wpdb->actionscheduler_groups} g ON g.group_id=a.group_id";
|
||||
}
|
||||
|
||||
$sql .= " WHERE 1=1";
|
||||
|
||||
if ( ! empty( $query[ 'group' ] ) ) {
|
||||
$sql .= " AND g.slug=%s";
|
||||
$sql_params[] = $query[ 'group' ];
|
||||
}
|
||||
|
||||
if ( $query[ 'hook' ] ) {
|
||||
$sql .= " AND a.hook=%s";
|
||||
$sql_params[] = $query[ 'hook' ];
|
||||
}
|
||||
if ( ! is_null( $query[ 'args' ] ) ) {
|
||||
$sql .= " AND a.args=%s";
|
||||
$sql_params[] = $this->get_args_for_query( $query[ 'args' ] );
|
||||
}
|
||||
|
||||
if ( $query[ 'status' ] ) {
|
||||
$sql .= " AND a.status=%s";
|
||||
$sql_params[] = $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 a.scheduled_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 a.last_attempt_gmt $comparator %s";
|
||||
$sql_params[] = $date_string;
|
||||
}
|
||||
|
||||
if ( $query[ 'claimed' ] === true ) {
|
||||
$sql .= " AND a.claim_id != 0";
|
||||
} elseif ( $query[ 'claimed' ] === false ) {
|
||||
$sql .= " AND a.claim_id = 0";
|
||||
} elseif ( ! is_null( $query[ 'claimed' ] ) ) {
|
||||
$sql .= " AND a.claim_id = %d";
|
||||
$sql_params[] = $query[ 'claimed' ];
|
||||
}
|
||||
|
||||
if ( ! empty( $query['search'] ) ) {
|
||||
$sql .= " AND (a.hook LIKE %s OR (a.extended_args IS NULL AND a.args LIKE %s) OR a.extended_args LIKE %s";
|
||||
for( $i = 0; $i < 3; $i++ ) {
|
||||
$sql_params[] = sprintf( '%%%s%%', $query['search'] );
|
||||
}
|
||||
|
||||
$search_claim_id = (int) $query['search'];
|
||||
if ( $search_claim_id ) {
|
||||
$sql .= ' OR a.claim_id = %d';
|
||||
$sql_params[] = $search_claim_id;
|
||||
}
|
||||
|
||||
$sql .= ')';
|
||||
}
|
||||
|
||||
if ( 'select' === $select_or_count ) {
|
||||
if ( strtoupper( $query[ 'order' ] ) == 'ASC' ) {
|
||||
$order = 'ASC';
|
||||
} else {
|
||||
$order = 'DESC';
|
||||
}
|
||||
switch ( $query['orderby'] ) {
|
||||
case 'hook':
|
||||
$sql .= " ORDER BY a.hook $order";
|
||||
break;
|
||||
case 'group':
|
||||
$sql .= " ORDER BY g.slug $order";
|
||||
break;
|
||||
case 'modified':
|
||||
$sql .= " ORDER BY a.last_attempt_gmt $order";
|
||||
break;
|
||||
case 'none':
|
||||
break;
|
||||
case 'date':
|
||||
default:
|
||||
$sql .= " ORDER BY a.scheduled_date_gmt $order";
|
||||
break;
|
||||
}
|
||||
|
||||
if ( $query[ 'per_page' ] > 0 ) {
|
||||
$sql .= " LIMIT %d, %d";
|
||||
$sql_params[] = $query[ 'offset' ];
|
||||
$sql_params[] = $query[ 'per_page' ];
|
||||
}
|
||||
}
|
||||
|
||||
if ( ! empty( $sql_params ) ) {
|
||||
$sql = $wpdb->prepare( $sql, $sql_params );
|
||||
}
|
||||
|
||||
return $sql;
|
||||
}
|
||||
|
||||
/**
|
||||
* Query for action count of list of action IDs.
|
||||
*
|
||||
* @param array $query Query parameters.
|
||||
* @param string $query_type Whether to select or count the results. Default, select.
|
||||
*
|
||||
* @return null|string|array The IDs of actions matching the query
|
||||
*/
|
||||
public function query_actions( $query = [], $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 Set of 'status' => int $count pairs for statuses with 1 or more actions of that status.
|
||||
*/
|
||||
public function action_counts() {
|
||||
global $wpdb;
|
||||
|
||||
$sql = "SELECT a.status, count(a.status) as 'count'";
|
||||
$sql .= " FROM {$wpdb->actionscheduler_actions} a";
|
||||
$sql .= " GROUP BY a.status";
|
||||
|
||||
$actions_count_by_status = array();
|
||||
$action_stati_and_labels = $this->get_status_labels();
|
||||
|
||||
foreach ( $wpdb->get_results( $sql ) as $action_data ) {
|
||||
// Ignore any actions with invalid status
|
||||
if ( array_key_exists( $action_data->status, $action_stati_and_labels ) ) {
|
||||
$actions_count_by_status[ $action_data->status ] = $action_data->count;
|
||||
}
|
||||
}
|
||||
|
||||
return $actions_count_by_status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel an action.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function cancel_action( $action_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
|
||||
$updated = $wpdb->update(
|
||||
$wpdb->actionscheduler_actions,
|
||||
[ 'status' => self::STATUS_CANCELED ],
|
||||
[ 'action_id' => $action_id ],
|
||||
[ '%s' ],
|
||||
[ '%d' ]
|
||||
);
|
||||
if ( empty( $updated ) ) {
|
||||
/* translators: %s: action ID */
|
||||
throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s', 'action-scheduler' ), $action_id ) );
|
||||
}
|
||||
do_action( 'action_scheduler_canceled_action', $action_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel pending actions by hook.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @param string $hook Hook name.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function cancel_actions_by_hook( $hook ) {
|
||||
$this->bulk_cancel_actions( [ 'hook' => $hook ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel pending actions by group.
|
||||
*
|
||||
* @param string $group Group slug.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function cancel_actions_by_group( $group ) {
|
||||
$this->bulk_cancel_actions( [ 'group' => $group ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Bulk cancel actions.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @param array $query_args Query parameters.
|
||||
*/
|
||||
protected function bulk_cancel_actions( $query_args ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
|
||||
if ( ! is_array( $query_args ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't cancel actions that are already canceled.
|
||||
if ( isset( $query_args['status'] ) && $query_args['status'] == self::STATUS_CANCELED ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$action_ids = true;
|
||||
$query_args = wp_parse_args(
|
||||
$query_args,
|
||||
[
|
||||
'per_page' => 1000,
|
||||
'status' => self::STATUS_PENDING,
|
||||
]
|
||||
);
|
||||
|
||||
while ( $action_ids ) {
|
||||
$action_ids = $this->query_actions( $query_args );
|
||||
if ( empty( $action_ids ) ) {
|
||||
break;
|
||||
}
|
||||
|
||||
$format = array_fill( 0, count( $action_ids ), '%d' );
|
||||
$query_in = '(' . implode( ',', $format ) . ')';
|
||||
$parameters = $action_ids;
|
||||
array_unshift( $parameters, self::STATUS_CANCELED );
|
||||
|
||||
$wpdb->query(
|
||||
$wpdb->prepare( // wpcs: PreparedSQLPlaceholders replacement count ok.
|
||||
"UPDATE {$wpdb->actionscheduler_actions} SET status = %s WHERE action_id IN {$query_in}",
|
||||
$parameters
|
||||
)
|
||||
);
|
||||
|
||||
do_action( 'action_scheduler_bulk_cancel_actions', $action_ids );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an action.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function delete_action( $action_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$deleted = $wpdb->delete( $wpdb->actionscheduler_actions, [ 'action_id' => $action_id ], [ '%d' ] );
|
||||
if ( empty( $deleted ) ) {
|
||||
throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s', 'action-scheduler' ), $action_id ) );
|
||||
}
|
||||
do_action( 'action_scheduler_deleted_action', $action_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the schedule date for an action.
|
||||
*
|
||||
* @param string $action_id Action ID.
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @return \DateTime The local date the action is scheduled to run, or the date that it ran.
|
||||
*/
|
||||
public function get_date( $action_id ) {
|
||||
$date = $this->get_date_gmt( $action_id );
|
||||
ActionScheduler_TimezoneHelper::set_local_timezone( $date );
|
||||
return $date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the GMT schedule date for an action.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @return \DateTime The GMT date the action is scheduled to run, or the date that it ran.
|
||||
*/
|
||||
protected function get_date_gmt( $action_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$record = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_actions} WHERE action_id=%d", $action_id ) );
|
||||
if ( empty( $record ) ) {
|
||||
throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s', 'action-scheduler' ), $action_id ) );
|
||||
}
|
||||
if ( $record->status == self::STATUS_PENDING ) {
|
||||
return as_get_datetime_object( $record->scheduled_date_gmt );
|
||||
} else {
|
||||
return as_get_datetime_object( $record->last_attempt_gmt );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stake a claim on actions.
|
||||
*
|
||||
* @param int $max_actions Maximum number of action to include in claim.
|
||||
* @param \DateTime $before_date Jobs must be schedule before this date. Defaults to now.
|
||||
*
|
||||
* @return ActionScheduler_ActionClaim
|
||||
*/
|
||||
public function stake_claim( $max_actions = 10, \DateTime $before_date = null, $hooks = array(), $group = '' ) {
|
||||
$claim_id = $this->generate_claim_id();
|
||||
|
||||
$this->claim_before_date = $before_date;
|
||||
$this->claim_actions( $claim_id, $max_actions, $before_date, $hooks, $group );
|
||||
$action_ids = $this->find_actions_by_claim_id( $claim_id );
|
||||
$this->claim_before_date = null;
|
||||
|
||||
return new ActionScheduler_ActionClaim( $claim_id, $action_ids );
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a new action claim.
|
||||
*
|
||||
* @return int Claim ID.
|
||||
*/
|
||||
protected function generate_claim_id() {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$now = as_get_datetime_object();
|
||||
$wpdb->insert( $wpdb->actionscheduler_claims, [ 'date_created_gmt' => $now->format( 'Y-m-d H:i:s' ) ] );
|
||||
|
||||
return $wpdb->insert_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark actions claimed.
|
||||
*
|
||||
* @param string $claim_id Claim Id.
|
||||
* @param int $limit Number of action to include in claim.
|
||||
* @param \DateTime $before_date Should use UTC timezone.
|
||||
*
|
||||
* @return int The number of actions that were claimed.
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
protected function claim_actions( $claim_id, $limit, \DateTime $before_date = null, $hooks = array(), $group = '' ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
|
||||
$now = as_get_datetime_object();
|
||||
$date = is_null( $before_date ) ? $now : clone $before_date;
|
||||
|
||||
// can't use $wpdb->update() because of the <= condition
|
||||
$update = "UPDATE {$wpdb->actionscheduler_actions} SET claim_id=%d, last_attempt_gmt=%s, last_attempt_local=%s";
|
||||
$params = array(
|
||||
$claim_id,
|
||||
$now->format( 'Y-m-d H:i:s' ),
|
||||
current_time( 'mysql' ),
|
||||
);
|
||||
|
||||
$where = "WHERE claim_id = 0 AND scheduled_date_gmt <= %s AND status=%s";
|
||||
$params[] = $date->format( 'Y-m-d H:i:s' );
|
||||
$params[] = self::STATUS_PENDING;
|
||||
|
||||
if ( ! empty( $hooks ) ) {
|
||||
$placeholders = array_fill( 0, count( $hooks ), '%s' );
|
||||
$where .= ' AND hook IN (' . join( ', ', $placeholders ) . ')';
|
||||
$params = array_merge( $params, array_values( $hooks ) );
|
||||
}
|
||||
|
||||
if ( ! empty( $group ) ) {
|
||||
|
||||
$group_id = $this->get_group_id( $group, false );
|
||||
|
||||
// throw exception if no matching group found, this matches ActionScheduler_wpPostStore's behaviour
|
||||
if ( empty( $group_id ) ) {
|
||||
/* translators: %s: group name */
|
||||
throw new InvalidArgumentException( sprintf( __( 'The group "%s" does not exist.', 'action-scheduler' ), $group ) );
|
||||
}
|
||||
|
||||
$where .= ' AND group_id = %d';
|
||||
$params[] = $group_id;
|
||||
}
|
||||
|
||||
$order = "ORDER BY attempts ASC, scheduled_date_gmt ASC, action_id ASC LIMIT %d";
|
||||
$params[] = $limit;
|
||||
|
||||
$sql = $wpdb->prepare( "{$update} {$where} {$order}", $params );
|
||||
|
||||
$rows_affected = $wpdb->query( $sql );
|
||||
if ( $rows_affected === false ) {
|
||||
throw new \RuntimeException( __( 'Unable to claim actions. Database error.', 'action-scheduler' ) );
|
||||
}
|
||||
|
||||
return (int) $rows_affected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of active claims.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function get_claim_count() {
|
||||
global $wpdb;
|
||||
|
||||
$sql = "SELECT COUNT(DISTINCT claim_id) FROM {$wpdb->actionscheduler_actions} WHERE claim_id != 0 AND status IN ( %s, %s)";
|
||||
$sql = $wpdb->prepare( $sql, [ self::STATUS_PENDING, self::STATUS_RUNNING ] );
|
||||
|
||||
return (int) $wpdb->get_var( $sql );
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an action's claim ID, as stored in the claim_id column.
|
||||
*
|
||||
* @param string $action_id Action ID.
|
||||
* @return mixed
|
||||
*/
|
||||
public function get_claim_id( $action_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
|
||||
$sql = "SELECT claim_id FROM {$wpdb->actionscheduler_actions} WHERE action_id=%d";
|
||||
$sql = $wpdb->prepare( $sql, $action_id );
|
||||
|
||||
return (int) $wpdb->get_var( $sql );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the action IDs of action in a claim.
|
||||
*
|
||||
* @return int[]
|
||||
*/
|
||||
public function find_actions_by_claim_id( $claim_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
|
||||
$action_ids = array();
|
||||
$before_date = isset( $this->claim_before_date ) ? $this->claim_before_date : as_get_datetime_object();
|
||||
$cut_off = $before_date->format( 'Y-m-d H:i:s' );
|
||||
|
||||
$sql = $wpdb->prepare(
|
||||
"SELECT action_id, scheduled_date_gmt FROM {$wpdb->actionscheduler_actions} WHERE claim_id = %d",
|
||||
$claim_id
|
||||
);
|
||||
|
||||
// Verify that the scheduled date for each action is within the expected bounds (in some unusual
|
||||
// cases, we cannot depend on MySQL to honor all of the WHERE conditions we specify).
|
||||
foreach ( $wpdb->get_results( $sql ) as $claimed_action ) {
|
||||
if ( $claimed_action->scheduled_date_gmt <= $cut_off ) {
|
||||
$action_ids[] = absint( $claimed_action->action_id );
|
||||
}
|
||||
}
|
||||
|
||||
return $action_ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Release actions from a claim and delete the claim.
|
||||
*
|
||||
* @param ActionScheduler_ActionClaim $claim Claim object.
|
||||
*/
|
||||
public function release_claim( ActionScheduler_ActionClaim $claim ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$wpdb->update( $wpdb->actionscheduler_actions, [ 'claim_id' => 0 ], [ 'claim_id' => $claim->get_id() ], [ '%d' ], [ '%d' ] );
|
||||
$wpdb->delete( $wpdb->actionscheduler_claims, [ 'claim_id' => $claim->get_id() ], [ '%d' ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the claim from an action.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function unclaim_action( $action_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$wpdb->update(
|
||||
$wpdb->actionscheduler_actions,
|
||||
[ 'claim_id' => 0 ],
|
||||
[ 'action_id' => $action_id ],
|
||||
[ '%s' ],
|
||||
[ '%d' ]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark an action as failed.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function mark_failure( $action_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$updated = $wpdb->update(
|
||||
$wpdb->actionscheduler_actions,
|
||||
[ 'status' => self::STATUS_FAILED ],
|
||||
[ 'action_id' => $action_id ],
|
||||
[ '%s' ],
|
||||
[ '%d' ]
|
||||
);
|
||||
if ( empty( $updated ) ) {
|
||||
throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s', 'action-scheduler' ), $action_id ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add execution message to action log.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function log_execution( $action_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
|
||||
$sql = "UPDATE {$wpdb->actionscheduler_actions} SET attempts = attempts+1, status=%s, last_attempt_gmt = %s, last_attempt_local = %s WHERE action_id = %d";
|
||||
$sql = $wpdb->prepare( $sql, self::STATUS_RUNNING, current_time( 'mysql', true ), current_time( 'mysql' ), $action_id );
|
||||
$wpdb->query( $sql );
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark an action as complete.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function mark_complete( $action_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$updated = $wpdb->update(
|
||||
$wpdb->actionscheduler_actions,
|
||||
[
|
||||
'status' => self::STATUS_COMPLETE,
|
||||
'last_attempt_gmt' => current_time( 'mysql', true ),
|
||||
'last_attempt_local' => current_time( 'mysql' ),
|
||||
],
|
||||
[ 'action_id' => $action_id ],
|
||||
[ '%s' ],
|
||||
[ '%d' ]
|
||||
);
|
||||
if ( empty( $updated ) ) {
|
||||
throw new \InvalidArgumentException( sprintf( __( 'Unidentified action %s', 'action-scheduler' ), $action_id ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an action's status.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_status( $action_id ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$sql = "SELECT status FROM {$wpdb->actionscheduler_actions} WHERE action_id=%d";
|
||||
$sql = $wpdb->prepare( $sql, $action_id );
|
||||
$status = $wpdb->get_var( $sql );
|
||||
|
||||
if ( $status === null ) {
|
||||
throw new \InvalidArgumentException( __( 'Invalid action ID. No status found.', 'action-scheduler' ) );
|
||||
} elseif ( empty( $status ) ) {
|
||||
throw new \RuntimeException( __( 'Unknown status found for action.', 'action-scheduler' ) );
|
||||
} else {
|
||||
return $status;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,426 +0,0 @@
|
||||
<?php
|
||||
|
||||
use ActionScheduler_Store as Store;
|
||||
use Action_Scheduler\Migration\Runner;
|
||||
use Action_Scheduler\Migration\Config;
|
||||
use Action_Scheduler\Migration\Controller;
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_HybridStore
|
||||
*
|
||||
* A wrapper around multiple stores that fetches data from both.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*/
|
||||
class ActionScheduler_HybridStore extends Store {
|
||||
const DEMARKATION_OPTION = 'action_scheduler_hybrid_store_demarkation';
|
||||
|
||||
private $primary_store;
|
||||
private $secondary_store;
|
||||
private $migration_runner;
|
||||
|
||||
/**
|
||||
* @var int The dividing line between IDs of actions created
|
||||
* by the primary and secondary stores.
|
||||
*
|
||||
* Methods that accept an action ID will compare the ID against
|
||||
* this to determine which store will contain that ID. In almost
|
||||
* all cases, the ID should come from the primary store, but if
|
||||
* client code is bypassing the API functions and fetching IDs
|
||||
* from elsewhere, then there is a chance that an unmigrated ID
|
||||
* might be requested.
|
||||
*/
|
||||
private $demarkation_id = 0;
|
||||
|
||||
/**
|
||||
* ActionScheduler_HybridStore constructor.
|
||||
*
|
||||
* @param Config $config Migration config object.
|
||||
*/
|
||||
public function __construct( Config $config = null ) {
|
||||
$this->demarkation_id = (int) get_option( self::DEMARKATION_OPTION, 0 );
|
||||
if ( empty( $config ) ) {
|
||||
$config = Controller::instance()->get_migration_config_object();
|
||||
}
|
||||
$this->primary_store = $config->get_destination_store();
|
||||
$this->secondary_store = $config->get_source_store();
|
||||
$this->migration_runner = new Runner( $config );
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the table data store tables.
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function init() {
|
||||
add_action( 'action_scheduler/created_table', [ $this, 'set_autoincrement' ], 10, 2 );
|
||||
$this->primary_store->init();
|
||||
$this->secondary_store->init();
|
||||
remove_action( 'action_scheduler/created_table', [ $this, 'set_autoincrement' ], 10 );
|
||||
}
|
||||
|
||||
/**
|
||||
* When the actions table is created, set its autoincrement
|
||||
* value to be one higher than the posts table to ensure that
|
||||
* there are no ID collisions.
|
||||
*
|
||||
* @param string $table_name
|
||||
* @param string $table_suffix
|
||||
*
|
||||
* @return void
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function set_autoincrement( $table_name, $table_suffix ) {
|
||||
if ( ActionScheduler_StoreSchema::ACTIONS_TABLE === $table_suffix ) {
|
||||
if ( empty( $this->demarkation_id ) ) {
|
||||
$this->demarkation_id = $this->set_demarkation_id();
|
||||
}
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
/**
|
||||
* A default date of '0000-00-00 00:00:00' is invalid in MySQL 5.7 when configured with
|
||||
* sql_mode including both STRICT_TRANS_TABLES and NO_ZERO_DATE.
|
||||
*/
|
||||
$default_date = new DateTime( 'tomorrow' );
|
||||
$null_action = new ActionScheduler_NullAction();
|
||||
$date_gmt = $this->get_scheduled_date_string( $null_action, $default_date );
|
||||
$date_local = $this->get_scheduled_date_string_local( $null_action, $default_date );
|
||||
|
||||
$row_count = $wpdb->insert(
|
||||
$wpdb->{ActionScheduler_StoreSchema::ACTIONS_TABLE},
|
||||
[
|
||||
'action_id' => $this->demarkation_id,
|
||||
'hook' => '',
|
||||
'status' => '',
|
||||
'scheduled_date_gmt' => $date_gmt,
|
||||
'scheduled_date_local' => $date_local,
|
||||
'last_attempt_gmt' => $date_gmt,
|
||||
'last_attempt_local' => $date_local,
|
||||
]
|
||||
);
|
||||
if ( $row_count > 0 ) {
|
||||
$wpdb->delete(
|
||||
$wpdb->{ActionScheduler_StoreSchema::ACTIONS_TABLE},
|
||||
[ 'action_id' => $this->demarkation_id ]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store the demarkation id in WP options.
|
||||
*
|
||||
* @param int $id The ID to set as the demarkation point between the two stores
|
||||
* Leave null to use the next ID from the WP posts table.
|
||||
*
|
||||
* @return int The new ID.
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
private function set_demarkation_id( $id = null ) {
|
||||
if ( empty( $id ) ) {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
$id = (int) $wpdb->get_var( "SELECT MAX(ID) FROM $wpdb->posts" );
|
||||
$id ++;
|
||||
}
|
||||
update_option( self::DEMARKATION_OPTION, $id );
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the first matching action from the secondary store.
|
||||
* If it exists, migrate it to the primary store immediately.
|
||||
* After it migrates, the secondary store will logically contain
|
||||
* the next matching action, so return the result thence.
|
||||
*
|
||||
* @param string $hook
|
||||
* @param array $params
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function find_action( $hook, $params = [] ) {
|
||||
$found_unmigrated_action = $this->secondary_store->find_action( $hook, $params );
|
||||
if ( ! empty( $found_unmigrated_action ) ) {
|
||||
$this->migrate( [ $found_unmigrated_action ] );
|
||||
}
|
||||
|
||||
return $this->primary_store->find_action( $hook, $params );
|
||||
}
|
||||
|
||||
/**
|
||||
* Find actions matching the query in the secondary source first.
|
||||
* If any are found, migrate them immediately. Then the secondary
|
||||
* store will contain the canonical results.
|
||||
*
|
||||
* @param array $query
|
||||
* @param string $query_type Whether to select or count the results. Default, select.
|
||||
*
|
||||
* @return int[]
|
||||
*/
|
||||
public function query_actions( $query = [], $query_type = 'select' ) {
|
||||
$found_unmigrated_actions = $this->secondary_store->query_actions( $query, 'select' );
|
||||
if ( ! empty( $found_unmigrated_actions ) ) {
|
||||
$this->migrate( $found_unmigrated_actions );
|
||||
}
|
||||
|
||||
return $this->primary_store->query_actions( $query, $query_type );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a count of all actions in the store, grouped by status
|
||||
*
|
||||
* @return array Set of 'status' => int $count pairs for statuses with 1 or more actions of that status.
|
||||
*/
|
||||
public function action_counts() {
|
||||
$unmigrated_actions_count = $this->secondary_store->action_counts();
|
||||
$migrated_actions_count = $this->primary_store->action_counts();
|
||||
$actions_count_by_status = array();
|
||||
|
||||
foreach ( $this->get_status_labels() as $status_key => $status_label ) {
|
||||
|
||||
$count = 0;
|
||||
|
||||
if ( isset( $unmigrated_actions_count[ $status_key ] ) ) {
|
||||
$count += $unmigrated_actions_count[ $status_key ];
|
||||
}
|
||||
|
||||
if ( isset( $migrated_actions_count[ $status_key ] ) ) {
|
||||
$count += $migrated_actions_count[ $status_key ];
|
||||
}
|
||||
|
||||
$actions_count_by_status[ $status_key ] = $count;
|
||||
}
|
||||
|
||||
$actions_count_by_status = array_filter( $actions_count_by_status );
|
||||
|
||||
return $actions_count_by_status;
|
||||
}
|
||||
|
||||
/**
|
||||
* If any actions would have been claimed by the secondary store,
|
||||
* migrate them immediately, then ask the primary store for the
|
||||
* canonical claim.
|
||||
*
|
||||
* @param int $max_actions
|
||||
* @param DateTime|null $before_date
|
||||
*
|
||||
* @return ActionScheduler_ActionClaim
|
||||
*/
|
||||
public function stake_claim( $max_actions = 10, DateTime $before_date = null, $hooks = array(), $group = '' ) {
|
||||
$claim = $this->secondary_store->stake_claim( $max_actions, $before_date, $hooks, $group );
|
||||
|
||||
$claimed_actions = $claim->get_actions();
|
||||
if ( ! empty( $claimed_actions ) ) {
|
||||
$this->migrate( $claimed_actions );
|
||||
}
|
||||
|
||||
$this->secondary_store->release_claim( $claim );
|
||||
|
||||
return $this->primary_store->stake_claim( $max_actions, $before_date, $hooks, $group );
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate a list of actions to the table data store.
|
||||
*
|
||||
* @param array $action_ids List of action IDs.
|
||||
*/
|
||||
private function migrate( $action_ids ) {
|
||||
$this->migration_runner->migrate_actions( $action_ids );
|
||||
}
|
||||
|
||||
/**
|
||||
* Save an action to the primary store.
|
||||
*
|
||||
* @param ActionScheduler_Action $action Action object to be saved.
|
||||
* @param DateTime $date Optional. Schedule date. Default null.
|
||||
*
|
||||
* @return int The action ID
|
||||
*/
|
||||
public function save_action( ActionScheduler_Action $action, DateTime $date = null ) {
|
||||
return $this->primary_store->save_action( $action, $date );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve an existing action whether migrated or not.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function fetch_action( $action_id ) {
|
||||
$store = $this->get_store_from_action_id( $action_id, true );
|
||||
if ( $store ) {
|
||||
return $store->fetch_action( $action_id );
|
||||
} else {
|
||||
return new ActionScheduler_NullAction();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel an existing action whether migrated or not.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function cancel_action( $action_id ) {
|
||||
$store = $this->get_store_from_action_id( $action_id );
|
||||
if ( $store ) {
|
||||
$store->cancel_action( $action_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an existing action whether migrated or not.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function delete_action( $action_id ) {
|
||||
$store = $this->get_store_from_action_id( $action_id );
|
||||
if ( $store ) {
|
||||
$store->delete_action( $action_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the schedule date an existing action whether migrated or not.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function get_date( $action_id ) {
|
||||
$store = $this->get_store_from_action_id( $action_id );
|
||||
if ( $store ) {
|
||||
return $store->get_date( $action_id );
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark an existing action as failed whether migrated or not.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function mark_failure( $action_id ) {
|
||||
$store = $this->get_store_from_action_id( $action_id );
|
||||
if ( $store ) {
|
||||
$store->mark_failure( $action_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Log the execution of an existing action whether migrated or not.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function log_execution( $action_id ) {
|
||||
$store = $this->get_store_from_action_id( $action_id );
|
||||
if ( $store ) {
|
||||
$store->log_execution( $action_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark an existing action complete whether migrated or not.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function mark_complete( $action_id ) {
|
||||
$store = $this->get_store_from_action_id( $action_id );
|
||||
if ( $store ) {
|
||||
$store->mark_complete( $action_id );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an existing action status whether migrated or not.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function get_status( $action_id ) {
|
||||
$store = $this->get_store_from_action_id( $action_id );
|
||||
if ( $store ) {
|
||||
return $store->get_status( $action_id );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return which store an action is stored in.
|
||||
*
|
||||
* @param int $action_id ID of the action.
|
||||
* @param bool $primary_first Optional flag indicating search the primary store first.
|
||||
* @return ActionScheduler_Store
|
||||
*/
|
||||
protected function get_store_from_action_id( $action_id, $primary_first = false ) {
|
||||
if ( $primary_first ) {
|
||||
$stores = [
|
||||
$this->primary_store,
|
||||
$this->secondary_store,
|
||||
];
|
||||
} elseif ( $action_id < $this->demarkation_id ) {
|
||||
$stores = [
|
||||
$this->secondary_store,
|
||||
$this->primary_store,
|
||||
];
|
||||
} else {
|
||||
$stores = [
|
||||
$this->primary_store,
|
||||
];
|
||||
}
|
||||
|
||||
foreach ( $stores as $store ) {
|
||||
$action = $store->fetch_action( $action_id );
|
||||
if ( ! is_a( $action, 'ActionScheduler_NullAction' ) ) {
|
||||
return $store;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/* * * * * * * * * * * * * * * * * * * * * * * * * * *
|
||||
* All claim-related functions should operate solely
|
||||
* on the primary store.
|
||||
* * * * * * * * * * * * * * * * * * * * * * * * * * */
|
||||
|
||||
/**
|
||||
* Get the claim count from the table data store.
|
||||
*/
|
||||
public function get_claim_count() {
|
||||
return $this->primary_store->get_claim_count();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the claim ID for an action from the table data store.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function get_claim_id( $action_id ) {
|
||||
return $this->primary_store->get_claim_id( $action_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* Release a claim in the table data store.
|
||||
*
|
||||
* @param ActionScheduler_ActionClaim $claim Claim object.
|
||||
*/
|
||||
public function release_claim( ActionScheduler_ActionClaim $claim ) {
|
||||
$this->primary_store->release_claim( $claim );
|
||||
}
|
||||
|
||||
/**
|
||||
* Release claims on an action in the table data store.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function unclaim_action( $action_id ) {
|
||||
$this->primary_store->unclaim_action( $action_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a list of action IDs by claim.
|
||||
*
|
||||
* @param int $claim_id Claim ID.
|
||||
*/
|
||||
public function find_actions_by_claim_id( $claim_id ) {
|
||||
return $this->primary_store->find_actions_by_claim_id( $claim_id );
|
||||
}
|
||||
}
|
@ -1,240 +0,0 @@
|
||||
<?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 = as_get_datetime_object( 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');
|
||||
ActionScheduler_TimezoneHelper::set_local_timezone( $date );
|
||||
$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 );
|
||||
ActionScheduler_TimezoneHelper::set_local_timezone( $date );
|
||||
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 );
|
||||
|
||||
parent::init();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
@ -1,885 +0,0 @@
|
||||
<?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';
|
||||
const DEPENDENCIES_MET = 'as-post-store-dependencies-met';
|
||||
|
||||
/**
|
||||
* Used to share information about the before_date property of claims internally.
|
||||
*
|
||||
* This is used in preference to passing the same information as a method param
|
||||
* for backwards-compatibility reasons.
|
||||
*
|
||||
* @var DateTime|null
|
||||
*/
|
||||
private $claim_before_date = null;
|
||||
|
||||
/** @var DateTimeZone */
|
||||
protected $local_timezone = NULL;
|
||||
|
||||
public function save_action( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ){
|
||||
try {
|
||||
$this->validate_action( $action );
|
||||
$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 );
|
||||
add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 );
|
||||
|
||||
$has_kses = false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' );
|
||||
|
||||
if ( $has_kses ) {
|
||||
// Prevent KSES from corrupting JSON in post_content.
|
||||
kses_remove_filters();
|
||||
}
|
||||
|
||||
$post_id = wp_insert_post($post_array);
|
||||
|
||||
if ( $has_kses ) {
|
||||
kses_init_filters();
|
||||
}
|
||||
|
||||
remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10 );
|
||||
remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a (probably unique) post name for scheduled actions in a more performant manner than wp_unique_post_slug().
|
||||
*
|
||||
* When an action's post status is transitioned to something other than 'draft', 'pending' or 'auto-draft, like 'publish'
|
||||
* or 'failed' or 'trash', WordPress will find a unique slug (stored in post_name column) using the wp_unique_post_slug()
|
||||
* function. This is done to ensure URL uniqueness. The approach taken by wp_unique_post_slug() is to iterate over existing
|
||||
* post_name values that match, and append a number 1 greater than the largest. This makes sense when manually creating a
|
||||
* post from the Edit Post screen. It becomes a bottleneck when automatically processing thousands of actions, with a
|
||||
* database containing thousands of related post_name values.
|
||||
*
|
||||
* WordPress 5.1 introduces the 'pre_wp_unique_post_slug' filter for plugins to address this issue.
|
||||
*
|
||||
* We can short-circuit WordPress's wp_unique_post_slug() approach using the 'pre_wp_unique_post_slug' filter. This
|
||||
* method is available to be used as a callback on that filter. It provides a more scalable approach to generating a
|
||||
* post_name/slug that is probably unique. Because Action Scheduler never actually uses the post_name field, or an
|
||||
* action's slug, being probably unique is good enough.
|
||||
*
|
||||
* For more backstory on this issue, see:
|
||||
* - https://github.com/woocommerce/action-scheduler/issues/44 and
|
||||
* - https://core.trac.wordpress.org/ticket/21112
|
||||
*
|
||||
* @param string $override_slug Short-circuit return value.
|
||||
* @param string $slug The desired slug (post_name).
|
||||
* @param int $post_ID Post ID.
|
||||
* @param string $post_status The post status.
|
||||
* @param string $post_type Post type.
|
||||
* @return string
|
||||
*/
|
||||
public function set_unique_post_slug( $override_slug, $slug, $post_ID, $post_status, $post_type ) {
|
||||
if ( self::POST_TYPE == $post_type ) {
|
||||
$override_slug = uniqid( self::POST_TYPE . '-', true ) . '-' . wp_generate_password( 32, false );
|
||||
}
|
||||
return $override_slug;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
try {
|
||||
$action = $this->make_action_from_post( $post );
|
||||
} catch ( ActionScheduler_InvalidActionException $exception ) {
|
||||
do_action( 'action_scheduler_failed_fetch_action', $post->ID, $exception );
|
||||
return $this->get_null_action();
|
||||
}
|
||||
|
||||
return $action;
|
||||
}
|
||||
|
||||
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 );
|
||||
$this->validate_args( $args, $post->ID );
|
||||
|
||||
$schedule = get_post_meta( $post->ID, self::SCHEDULE_META_KEY, true );
|
||||
$this->validate_schedule( $schedule, $post->ID );
|
||||
|
||||
$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 .= " LEFT JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID";
|
||||
$sql .= " LEFT JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id";
|
||||
$sql .= " LEFT JOIN {$wpdb->terms} t ON tt.term_id=t.term_id";
|
||||
} elseif ( ! empty( $query['group'] ) ) {
|
||||
$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";
|
||||
$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 );
|
||||
add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 );
|
||||
wp_trash_post( $action_id );
|
||||
remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 );
|
||||
}
|
||||
|
||||
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 ActionScheduler_DateTime The date the action is schedule to run, or the date that it ran.
|
||||
*/
|
||||
public function get_date( $action_id ) {
|
||||
$next = $this->get_date_gmt( $action_id );
|
||||
return ActionScheduler_TimezoneHelper::set_local_timezone( $next );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $action_id
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
* @return ActionScheduler_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 = '' ) {
|
||||
$this->claim_before_date = $before_date;
|
||||
$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 );
|
||||
$this->claim_before_date = null;
|
||||
|
||||
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_gmt',
|
||||
'before' => $date->format( 'Y-m-d H:i' ),
|
||||
'inclusive' => true,
|
||||
),
|
||||
'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, post_date_gmt FROM {$wpdb->posts} WHERE post_type = %s AND post_password = %s";
|
||||
$sql = $wpdb->prepare( $sql, array( self::POST_TYPE, $claim_id ) );
|
||||
|
||||
$action_ids = array();
|
||||
$before_date = isset( $this->claim_before_date ) ? $this->claim_before_date : as_get_datetime_object();
|
||||
$cut_off = $before_date->format( 'Y-m-d H:i:s' );
|
||||
|
||||
// Verify that the scheduled date for each action is within the expected bounds (in some unusual
|
||||
// cases, we cannot depend on MySQL to honor all of the WHERE conditions we specify).
|
||||
foreach ( $wpdb->get_results( $sql ) as $claimed_action ) {
|
||||
if ( $claimed_action->post_date_gmt <= $cut_off ) {
|
||||
$action_ids[] = absint( $claimed_action->ID );
|
||||
}
|
||||
}
|
||||
|
||||
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 ) {
|
||||
/* translators: %s: claim ID */
|
||||
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 ) {
|
||||
/* translators: %s: action ID */
|
||||
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 ) {
|
||||
/* translators: %s: action ID */
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Record that an action was completed.
|
||||
*
|
||||
* @param int $action_id ID of the completed action.
|
||||
* @throws InvalidArgumentException|RuntimeException
|
||||
*/
|
||||
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 );
|
||||
add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 );
|
||||
$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 );
|
||||
remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 );
|
||||
if ( is_wp_error( $result ) ) {
|
||||
throw new RuntimeException( $result->get_error_message() );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark action as migrated when there is an error deleting the action.
|
||||
*
|
||||
* @param int $action_id Action ID.
|
||||
*/
|
||||
public function mark_migrated( $action_id ) {
|
||||
wp_update_post(
|
||||
array(
|
||||
'ID' => $action_id,
|
||||
'post_status' => 'migrated'
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the post store can be migrated.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function migration_dependencies_met( $setting ) {
|
||||
global $wpdb;
|
||||
|
||||
$dependencies_met = get_transient( self::DEPENDENCIES_MET );
|
||||
if ( empty( $dependencies_met ) ) {
|
||||
$maximum_args_length = apply_filters( 'action_scheduler_maximum_args_length', 191 );
|
||||
$found_action = $wpdb->get_var(
|
||||
$wpdb->prepare(
|
||||
"SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND CHAR_LENGTH(post_content) > %d LIMIT 1",
|
||||
$maximum_args_length,
|
||||
self::POST_TYPE
|
||||
)
|
||||
);
|
||||
$dependencies_met = $found_action ? 'no' : 'yes';
|
||||
set_transient( self::DEPENDENCIES_MET, $dependencies_met, DAY_IN_SECONDS );
|
||||
}
|
||||
|
||||
return 'yes' == $dependencies_met ? $setting : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* InnoDB indexes have a maximum size of 767 bytes by default, which is only 191 characters with utf8mb4.
|
||||
*
|
||||
* Previously, AS wasn't concerned about args length, as we used the (unindex) post_content column. However,
|
||||
* as we prepare to move to custom tables, and can use an indexed VARCHAR column instead, we want to warn
|
||||
* developers of this impending requirement.
|
||||
*
|
||||
* @param ActionScheduler_Action $action
|
||||
*/
|
||||
protected function validate_action( ActionScheduler_Action $action ) {
|
||||
try {
|
||||
parent::validate_action( $action );
|
||||
} catch ( Exception $e ) {
|
||||
$message = sprintf( __( '%s Support for strings longer than this will be removed in a future version.', 'action-scheduler' ), $e->getMessage() );
|
||||
_doing_it_wrong( 'ActionScheduler_Action::$args', $message, '2.1.0' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
public function init() {
|
||||
add_filter( 'action_scheduler_migration_dependencies_met', array( $this, 'migration_dependencies_met' ) );
|
||||
|
||||
$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();
|
||||
}
|
||||
}
|
@ -1,58 +0,0 @@
|
||||
<?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', 'action-scheduler' ),
|
||||
/* translators: %s: count */
|
||||
'label_count' => _n_noop( 'Failed <span class="count">(%s)</span>', 'Failed <span class="count">(%s)</span>', 'action-scheduler' ),
|
||||
);
|
||||
|
||||
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', 'action-scheduler' ),
|
||||
/* translators: %s: count */
|
||||
'label_count' => _n_noop( 'In-Progress <span class="count">(%s)</span>', 'In-Progress <span class="count">(%s)</span>', 'action-scheduler' ),
|
||||
);
|
||||
|
||||
return apply_filters( 'action_scheduler_post_status_running_labels', $labels );
|
||||
}
|
||||
}
|
@ -1,50 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
|
@ -1,26 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
|
@ -1,109 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Action_Scheduler\Migration;
|
||||
|
||||
/**
|
||||
* Class ActionMigrator
|
||||
*
|
||||
* @package Action_Scheduler\Migration
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class ActionMigrator {
|
||||
/** var ActionScheduler_Store */
|
||||
private $source;
|
||||
|
||||
/** var ActionScheduler_Store */
|
||||
private $destination;
|
||||
|
||||
/** var LogMigrator */
|
||||
private $log_migrator;
|
||||
|
||||
/**
|
||||
* ActionMigrator constructor.
|
||||
*
|
||||
* @param ActionScheduler_Store $source_store Source store object.
|
||||
* @param ActionScheduler_Store $destination_store Destination store object.
|
||||
* @param LogMigrator $log_migrator Log migrator object.
|
||||
*/
|
||||
public function __construct( \ActionScheduler_Store $source_store, \ActionScheduler_Store $destination_store, LogMigrator $log_migrator ) {
|
||||
$this->source = $source_store;
|
||||
$this->destination = $destination_store;
|
||||
$this->log_migrator = $log_migrator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate an action.
|
||||
*
|
||||
* @param int $source_action_id Action ID.
|
||||
*
|
||||
* @return int 0|new action ID
|
||||
*/
|
||||
public function migrate( $source_action_id ) {
|
||||
try {
|
||||
$action = $this->source->fetch_action( $source_action_id );
|
||||
$status = $this->source->get_status( $source_action_id );
|
||||
} catch ( \Exception $e ) {
|
||||
$action = null;
|
||||
$status = '';
|
||||
}
|
||||
|
||||
if ( is_null( $action ) || empty( $status ) || ! $action->get_schedule()->get_date() ) {
|
||||
// null action or empty status means the fetch operation failed or the action didn't exist
|
||||
// null schedule means it's missing vital data
|
||||
// delete it and move on
|
||||
try {
|
||||
$this->source->delete_action( $source_action_id );
|
||||
} catch ( \Exception $e ) {
|
||||
// nothing to do, it didn't exist in the first place
|
||||
}
|
||||
do_action( 'action_scheduler/no_action_to_migrate', $source_action_id, $this->source, $this->destination );
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
// Make sure the last attempt date is set correctly for completed and failed actions
|
||||
$last_attempt_date = ( $status !== \ActionScheduler_Store::STATUS_PENDING ) ? $this->source->get_date( $source_action_id ) : null;
|
||||
|
||||
$destination_action_id = $this->destination->save_action( $action, null, $last_attempt_date );
|
||||
} catch ( \Exception $e ) {
|
||||
do_action( 'action_scheduler/migrate_action_failed', $source_action_id, $this->source, $this->destination );
|
||||
|
||||
return 0; // could not save the action in the new store
|
||||
}
|
||||
|
||||
try {
|
||||
switch ( $status ) {
|
||||
case \ActionScheduler_Store::STATUS_FAILED :
|
||||
$this->destination->mark_failure( $destination_action_id );
|
||||
break;
|
||||
case \ActionScheduler_Store::STATUS_CANCELED :
|
||||
$this->destination->cancel_action( $destination_action_id );
|
||||
break;
|
||||
}
|
||||
|
||||
$this->log_migrator->migrate( $source_action_id, $destination_action_id );
|
||||
$this->source->delete_action( $source_action_id );
|
||||
|
||||
$test_action = $this->source->fetch_action( $source_action_id );
|
||||
if ( ! is_a( $test_action, 'ActionScheduler_NullAction' ) ) {
|
||||
throw new \RuntimeException( sprintf( __( 'Unable to remove source migrated action %s', 'action-scheduler' ), $source_action_id ) );
|
||||
}
|
||||
do_action( 'action_scheduler/migrated_action', $source_action_id, $destination_action_id, $this->source, $this->destination );
|
||||
|
||||
return $destination_action_id;
|
||||
} catch ( \Exception $e ) {
|
||||
// could not delete from the old store
|
||||
$this->source->mark_migrated( $source_action_id );
|
||||
do_action( 'action_scheduler/migrate_action_incomplete', $source_action_id, $destination_action_id, $this->source, $this->destination );
|
||||
do_action( 'action_scheduler/migrated_action', $source_action_id, $destination_action_id, $this->source, $this->destination );
|
||||
|
||||
return $destination_action_id;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,47 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_DBStoreMigrator
|
||||
*
|
||||
* A class for direct saving of actions to the table data store during migration.
|
||||
*
|
||||
* @since 3.0.0
|
||||
*/
|
||||
class ActionScheduler_DBStoreMigrator extends ActionScheduler_DBStore {
|
||||
|
||||
/**
|
||||
* Save an action with optional last attempt date.
|
||||
*
|
||||
* Normally, saving an action sets its attempted date to 0000-00-00 00:00:00 because when an action is first saved,
|
||||
* it can't have been attempted yet, but migrated completed actions will have an attempted date, so we need to save
|
||||
* that when first saving the action.
|
||||
*
|
||||
* @param ActionScheduler_Action $action
|
||||
* @param \DateTime $scheduled_date Optional date of the first instance to store.
|
||||
* @param \DateTime $last_attempt_date Optional date the action was last attempted.
|
||||
*
|
||||
* @return string The action ID
|
||||
* @throws \RuntimeException When the action is not saved.
|
||||
*/
|
||||
public function save_action( ActionScheduler_Action $action, \DateTime $scheduled_date = null, \DateTime $last_attempt_date = null ){
|
||||
try {
|
||||
/** @var \wpdb $wpdb */
|
||||
global $wpdb;
|
||||
|
||||
$action_id = parent::save_action( $action, $scheduled_date );
|
||||
|
||||
if ( null !== $last_attempt_date ) {
|
||||
$data = [
|
||||
'last_attempt_gmt' => $this->get_scheduled_date_string( $action, $last_attempt_date ),
|
||||
'last_attempt_local' => $this->get_scheduled_date_string_local( $action, $last_attempt_date ),
|
||||
];
|
||||
|
||||
$wpdb->update( $wpdb->actionscheduler_actions, $data, array( 'action_id' => $action_id ), array( '%s', '%s' ), array( '%d' ) );
|
||||
}
|
||||
|
||||
return $action_id;
|
||||
} catch ( \Exception $e ) {
|
||||
throw new \RuntimeException( sprintf( __( 'Error saving action: %s', 'action-scheduler' ), $e->getMessage() ), 0 );
|
||||
}
|
||||
}
|
||||
}
|
@ -1,86 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Action_Scheduler\Migration;
|
||||
|
||||
|
||||
use ActionScheduler_Store as Store;
|
||||
|
||||
/**
|
||||
* Class BatchFetcher
|
||||
*
|
||||
* @package Action_Scheduler\Migration
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class BatchFetcher {
|
||||
/** var ActionScheduler_Store */
|
||||
private $store;
|
||||
|
||||
/**
|
||||
* BatchFetcher constructor.
|
||||
*
|
||||
* @param ActionScheduler_Store $source_store Source store object.
|
||||
*/
|
||||
public function __construct( Store $source_store ) {
|
||||
$this->store = $source_store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a list of actions.
|
||||
*
|
||||
* @param int $count The number of actions to retrieve
|
||||
*
|
||||
* @return int[] A list of action IDs
|
||||
*/
|
||||
public function fetch( $count = 10 ) {
|
||||
foreach ( $this->get_query_strategies( $count ) as $query ) {
|
||||
$action_ids = $this->store->query_actions( $query );
|
||||
if ( ! empty( $action_ids ) ) {
|
||||
return $action_ids;
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a list of prioritized of action search parameters.
|
||||
*
|
||||
* @param int $count Number of actions to find.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function get_query_strategies( $count ) {
|
||||
$now = as_get_datetime_object();
|
||||
$args = [
|
||||
'date' => $now,
|
||||
'per_page' => $count,
|
||||
'offset' => 0,
|
||||
'orderby' => 'date',
|
||||
'order' => 'ASC',
|
||||
];
|
||||
|
||||
$priorities = [
|
||||
Store::STATUS_PENDING,
|
||||
Store::STATUS_FAILED,
|
||||
Store::STATUS_CANCELED,
|
||||
Store::STATUS_COMPLETE,
|
||||
Store::STATUS_RUNNING,
|
||||
'', // any other unanticipated status
|
||||
];
|
||||
|
||||
foreach ( $priorities as $status ) {
|
||||
yield wp_parse_args( [
|
||||
'status' => $status,
|
||||
'date_compare' => '<=',
|
||||
], $args );
|
||||
yield wp_parse_args( [
|
||||
'status' => $status,
|
||||
'date_compare' => '>=',
|
||||
], $args );
|
||||
}
|
||||
}
|
||||
}
|
@ -1,168 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Action_Scheduler\Migration;
|
||||
|
||||
use Action_Scheduler\WP_CLI\ProgressBar;
|
||||
use ActionScheduler_Logger as Logger;
|
||||
use ActionScheduler_Store as Store;
|
||||
|
||||
/**
|
||||
* Class Config
|
||||
*
|
||||
* @package Action_Scheduler\Migration
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* A config builder for the ActionScheduler\Migration\Runner class
|
||||
*/
|
||||
class Config {
|
||||
/** @var ActionScheduler_Store */
|
||||
private $source_store;
|
||||
|
||||
/** @var ActionScheduler_Logger */
|
||||
private $source_logger;
|
||||
|
||||
/** @var ActionScheduler_Store */
|
||||
private $destination_store;
|
||||
|
||||
/** @var ActionScheduler_Logger */
|
||||
private $destination_logger;
|
||||
|
||||
/** @var Progress bar */
|
||||
private $progress_bar;
|
||||
|
||||
/** @var bool */
|
||||
private $dry_run = false;
|
||||
|
||||
/**
|
||||
* Config constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the configured source store.
|
||||
*
|
||||
* @return ActionScheduler_Store
|
||||
*/
|
||||
public function get_source_store() {
|
||||
if ( empty( $this->source_store ) ) {
|
||||
throw new \RuntimeException( __( 'Source store must be configured before running a migration', 'action-scheduler' ) );
|
||||
}
|
||||
|
||||
return $this->source_store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the configured source store.
|
||||
*
|
||||
* @param ActionScheduler_Store $store Source store object.
|
||||
*/
|
||||
public function set_source_store( Store $store ) {
|
||||
$this->source_store = $store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the configured source loger.
|
||||
*
|
||||
* @return ActionScheduler_Logger
|
||||
*/
|
||||
public function get_source_logger() {
|
||||
if ( empty( $this->source_logger ) ) {
|
||||
throw new \RuntimeException( __( 'Source logger must be configured before running a migration', 'action-scheduler' ) );
|
||||
}
|
||||
|
||||
return $this->source_logger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the configured source logger.
|
||||
*
|
||||
* @param ActionScheduler_Logger $logger
|
||||
*/
|
||||
public function set_source_logger( Logger $logger ) {
|
||||
$this->source_logger = $logger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the configured destination store.
|
||||
*
|
||||
* @return ActionScheduler_Store
|
||||
*/
|
||||
public function get_destination_store() {
|
||||
if ( empty( $this->destination_store ) ) {
|
||||
throw new \RuntimeException( __( 'Destination store must be configured before running a migration', 'action-scheduler' ) );
|
||||
}
|
||||
|
||||
return $this->destination_store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the configured destination store.
|
||||
*
|
||||
* @param ActionScheduler_Store $store
|
||||
*/
|
||||
public function set_destination_store( Store $store ) {
|
||||
$this->destination_store = $store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the configured destination logger.
|
||||
*
|
||||
* @return ActionScheduler_Logger
|
||||
*/
|
||||
public function get_destination_logger() {
|
||||
if ( empty( $this->destination_logger ) ) {
|
||||
throw new \RuntimeException( __( 'Destination logger must be configured before running a migration', 'action-scheduler' ) );
|
||||
}
|
||||
|
||||
return $this->destination_logger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the configured destination logger.
|
||||
*
|
||||
* @param ActionScheduler_Logger $logger
|
||||
*/
|
||||
public function set_destination_logger( Logger $logger ) {
|
||||
$this->destination_logger = $logger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get flag indicating whether it's a dry run.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function get_dry_run() {
|
||||
return $this->dry_run;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set flag indicating whether it's a dry run.
|
||||
*
|
||||
* @param bool $dry_run
|
||||
*/
|
||||
public function set_dry_run( $dry_run ) {
|
||||
$this->dry_run = (bool) $dry_run;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get progress bar object.
|
||||
*
|
||||
* @return ActionScheduler\WPCLI\ProgressBar
|
||||
*/
|
||||
public function get_progress_bar() {
|
||||
return $this->progress_bar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set progress bar object.
|
||||
*
|
||||
* @param ActionScheduler\WPCLI\ProgressBar $progress_bar
|
||||
*/
|
||||
public function set_progress_bar( ProgressBar $progress_bar ) {
|
||||
$this->progress_bar = $progress_bar;
|
||||
}
|
||||
}
|
@ -1,206 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Action_Scheduler\Migration;
|
||||
|
||||
use Action_Scheduler\WP_CLI\Migration_Command;
|
||||
use Action_Scheduler\WP_CLI\ProgressBar;
|
||||
|
||||
/**
|
||||
* Class Controller
|
||||
*
|
||||
* The main plugin/initialization class for migration to custom tables.
|
||||
*
|
||||
* @package Action_Scheduler\Migration
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class Controller {
|
||||
private static $instance;
|
||||
|
||||
/** @var Action_Scheduler\Migration\Scheduler */
|
||||
private $migration_scheduler;
|
||||
|
||||
/** @var string */
|
||||
private $store_classname;
|
||||
|
||||
/** @var string */
|
||||
private $logger_classname;
|
||||
|
||||
/** @var bool */
|
||||
private $migrate_custom_store;
|
||||
|
||||
/**
|
||||
* Controller constructor.
|
||||
*
|
||||
* @param Scheduler $migration_scheduler Migration scheduler object.
|
||||
*/
|
||||
protected function __construct( Scheduler $migration_scheduler ) {
|
||||
$this->migration_scheduler = $migration_scheduler;
|
||||
$this->store_classname = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the action store class name.
|
||||
*
|
||||
* @param string $class Classname of the store class.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_store_class( $class ) {
|
||||
if ( \ActionScheduler_DataController::is_migration_complete() ) {
|
||||
return \ActionScheduler_DataController::DATASTORE_CLASS;
|
||||
} elseif ( \ActionScheduler_Store::DEFAULT_CLASS !== $class ) {
|
||||
$this->store_classname = $class;
|
||||
return $class;
|
||||
} else {
|
||||
return 'ActionScheduler_HybridStore';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the action logger class name.
|
||||
*
|
||||
* @param string $class Classname of the logger class.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function get_logger_class( $class ) {
|
||||
\ActionScheduler_Store::instance();
|
||||
|
||||
if ( $this->has_custom_datastore() ) {
|
||||
$this->logger_classname = $class;
|
||||
return $class;
|
||||
} else {
|
||||
return \ActionScheduler_DataController::LOGGER_CLASS;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get flag indicating whether a custom datastore is in use.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function has_custom_datastore() {
|
||||
return (bool) $this->store_classname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up the background migration process
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function schedule_migration() {
|
||||
if ( \ActionScheduler_DataController::is_migration_complete() || $this->migration_scheduler->is_migration_scheduled() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->migration_scheduler->schedule_migration();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the default migration config object
|
||||
*
|
||||
* @return ActionScheduler\Migration\Config
|
||||
*/
|
||||
public function get_migration_config_object() {
|
||||
static $config = null;
|
||||
|
||||
if ( ! $config ) {
|
||||
$source_store = $this->store_classname ? new $this->store_classname() : new \ActionScheduler_wpPostStore();
|
||||
$source_logger = $this->logger_classname ? new $this->logger_classname() : new \ActionScheduler_wpCommentLogger();
|
||||
|
||||
$config = new Config();
|
||||
$config->set_source_store( $source_store );
|
||||
$config->set_source_logger( $source_logger );
|
||||
$config->set_destination_store( new \ActionScheduler_DBStoreMigrator() );
|
||||
$config->set_destination_logger( new \ActionScheduler_DBLogger() );
|
||||
|
||||
if ( defined( 'WP_CLI' ) && WP_CLI ) {
|
||||
$config->set_progress_bar( new ProgressBar( '', 0 ) );
|
||||
}
|
||||
}
|
||||
|
||||
return apply_filters( 'action_scheduler/migration_config', $config );
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook dashboard migration notice.
|
||||
*/
|
||||
public function hook_admin_notices() {
|
||||
if ( ! $this->allow_migration() || \ActionScheduler_DataController::is_migration_complete() ) {
|
||||
return;
|
||||
}
|
||||
add_action( 'admin_notices', array( $this, 'display_migration_notice' ), 10, 0 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a dashboard notice that migration is in progress.
|
||||
*/
|
||||
public function display_migration_notice() {
|
||||
printf( '<div class="notice notice-warning"><p>%s</p></div>', __( 'Action Scheduler migration in progress. The list of scheduled actions may be incomplete.', 'action-scheduler' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add store classes. Hook migration.
|
||||
*/
|
||||
private function hook() {
|
||||
add_filter( 'action_scheduler_store_class', array( $this, 'get_store_class' ), 100, 1 );
|
||||
add_filter( 'action_scheduler_logger_class', array( $this, 'get_logger_class' ), 100, 1 );
|
||||
add_action( 'init', array( $this, 'maybe_hook_migration' ) );
|
||||
add_action( 'wp_loaded', array( $this, 'schedule_migration' ) );
|
||||
|
||||
// Action Scheduler may be displayed as a Tools screen or WooCommerce > Status administration screen
|
||||
add_action( 'load-tools_page_action-scheduler', array( $this, 'hook_admin_notices' ), 10, 0 );
|
||||
add_action( 'load-woocommerce_page_wc-status', array( $this, 'hook_admin_notices' ), 10, 0 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Possibly hook the migration scheduler action.
|
||||
*
|
||||
* @author Jeremy Pry
|
||||
*/
|
||||
public function maybe_hook_migration() {
|
||||
if ( ! $this->allow_migration() || \ActionScheduler_DataController::is_migration_complete() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->migration_scheduler->hook();
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow datastores to enable migration to AS tables.
|
||||
*/
|
||||
public function allow_migration() {
|
||||
if ( ! \ActionScheduler_DataController::dependencies_met() ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( null === $this->migrate_custom_store ) {
|
||||
$this->migrate_custom_store = apply_filters( 'action_scheduler_migrate_data_store', false );
|
||||
}
|
||||
|
||||
return ( ! $this->has_custom_datastore() ) || $this->migrate_custom_store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Proceed with the migration if the dependencies have been met.
|
||||
*/
|
||||
public static function init() {
|
||||
if ( \ActionScheduler_DataController::dependencies_met() ) {
|
||||
self::instance()->hook();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Singleton factory.
|
||||
*/
|
||||
public static function instance() {
|
||||
if ( ! isset( self::$instance ) ) {
|
||||
self::$instance = new static( new Scheduler() );
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Action_Scheduler\Migration;
|
||||
|
||||
/**
|
||||
* Class DryRun_ActionMigrator
|
||||
*
|
||||
* @package Action_Scheduler\Migration
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class DryRun_ActionMigrator extends ActionMigrator {
|
||||
/**
|
||||
* Simulate migrating an action.
|
||||
*
|
||||
* @param int $source_action_id Action ID.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function migrate( $source_action_id ) {
|
||||
do_action( 'action_scheduler/migrate_action_dry_run', $source_action_id );
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
@ -1,23 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Action_Scheduler\Migration;
|
||||
|
||||
/**
|
||||
* Class DryRun_LogMigrator
|
||||
*
|
||||
* @package Action_Scheduler\Migration
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class DryRun_LogMigrator extends LogMigrator {
|
||||
/**
|
||||
* Simulate migrating an action log.
|
||||
*
|
||||
* @param int $source_action_id Source logger object.
|
||||
* @param int $destination_action_id Destination logger object.
|
||||
*/
|
||||
public function migrate( $source_action_id, $destination_action_id ) {
|
||||
// no-op
|
||||
}
|
||||
}
|
@ -1,49 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Action_Scheduler\Migration;
|
||||
|
||||
use ActionScheduler_Logger;
|
||||
|
||||
/**
|
||||
* Class LogMigrator
|
||||
*
|
||||
* @package Action_Scheduler\Migration
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class LogMigrator {
|
||||
/** @var ActionScheduler_Logger */
|
||||
private $source;
|
||||
|
||||
/** @var ActionScheduler_Logger */
|
||||
private $destination;
|
||||
|
||||
/**
|
||||
* ActionMigrator constructor.
|
||||
*
|
||||
* @param ActionScheduler_Logger $source_logger Source logger object.
|
||||
* @param ActionScheduler_Logger $destination_Logger Destination logger object.
|
||||
*/
|
||||
public function __construct( ActionScheduler_Logger $source_logger, ActionScheduler_Logger $destination_Logger ) {
|
||||
$this->source = $source_logger;
|
||||
$this->destination = $destination_Logger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate an action log.
|
||||
*
|
||||
* @param int $source_action_id Source logger object.
|
||||
* @param int $destination_action_id Destination logger object.
|
||||
*/
|
||||
public function migrate( $source_action_id, $destination_action_id ) {
|
||||
$logs = $this->source->get_logs( $source_action_id );
|
||||
foreach ( $logs as $log ) {
|
||||
if ( $log->get_action_id() == $source_action_id ) {
|
||||
$this->destination->log( $destination_action_id, $log->get_message(), $log->get_date() );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,136 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Action_Scheduler\Migration;
|
||||
|
||||
/**
|
||||
* Class Runner
|
||||
*
|
||||
* @package Action_Scheduler\Migration
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class Runner {
|
||||
/** @var ActionScheduler_Store */
|
||||
private $source_store;
|
||||
|
||||
/** @var ActionScheduler_Store */
|
||||
private $destination_store;
|
||||
|
||||
/** @var ActionScheduler_Logger */
|
||||
private $source_logger;
|
||||
|
||||
/** @var ActionScheduler_Logger */
|
||||
private $destination_logger;
|
||||
|
||||
/** @var BatchFetcher */
|
||||
private $batch_fetcher;
|
||||
|
||||
/** @var ActionMigrator */
|
||||
private $action_migrator;
|
||||
|
||||
/** @var LogMigrator */
|
||||
private $log_migrator;
|
||||
|
||||
/** @var ProgressBar */
|
||||
private $progress_bar;
|
||||
|
||||
/**
|
||||
* Runner constructor.
|
||||
*
|
||||
* @param Config $config Migration configuration object.
|
||||
*/
|
||||
public function __construct( Config $config ) {
|
||||
$this->source_store = $config->get_source_store();
|
||||
$this->destination_store = $config->get_destination_store();
|
||||
$this->source_logger = $config->get_source_logger();
|
||||
$this->destination_logger = $config->get_destination_logger();
|
||||
|
||||
$this->batch_fetcher = new BatchFetcher( $this->source_store );
|
||||
if ( $config->get_dry_run() ) {
|
||||
$this->log_migrator = new DryRun_LogMigrator( $this->source_logger, $this->destination_logger );
|
||||
$this->action_migrator = new DryRun_ActionMigrator( $this->source_store, $this->destination_store, $this->log_migrator );
|
||||
} else {
|
||||
$this->log_migrator = new LogMigrator( $this->source_logger, $this->destination_logger );
|
||||
$this->action_migrator = new ActionMigrator( $this->source_store, $this->destination_store, $this->log_migrator );
|
||||
}
|
||||
|
||||
if ( defined( 'WP_CLI' ) && WP_CLI ) {
|
||||
$this->progress_bar = $config->get_progress_bar();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run migration batch.
|
||||
*
|
||||
* @param int $batch_size Optional batch size. Default 10.
|
||||
*
|
||||
* @return int Size of batch processed.
|
||||
*/
|
||||
public function run( $batch_size = 10 ) {
|
||||
$batch = $this->batch_fetcher->fetch( $batch_size );
|
||||
$batch_size = count( $batch );
|
||||
|
||||
if ( ! $batch_size ) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if ( $this->progress_bar ) {
|
||||
/* translators: %d: amount of actions */
|
||||
$this->progress_bar->set_message( sprintf( _n( 'Migrating %d action', 'Migrating %d actions', $batch_size, 'action-scheduler' ), number_format_i18n( $batch_size ) ) );
|
||||
$this->progress_bar->set_count( $batch_size );
|
||||
}
|
||||
|
||||
$this->migrate_actions( $batch );
|
||||
|
||||
return $batch_size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Migration a batch of actions.
|
||||
*
|
||||
* @param array $action_ids List of action IDs to migrate.
|
||||
*/
|
||||
public function migrate_actions( array $action_ids ) {
|
||||
do_action( 'action_scheduler/migration_batch_starting', $action_ids );
|
||||
|
||||
\ActionScheduler::logger()->unhook_stored_action();
|
||||
$this->destination_logger->unhook_stored_action();
|
||||
|
||||
foreach ( $action_ids as $source_action_id ) {
|
||||
$destination_action_id = $this->action_migrator->migrate( $source_action_id );
|
||||
if ( $destination_action_id ) {
|
||||
$this->destination_logger->log( $destination_action_id, sprintf(
|
||||
/* translators: 1: source action ID 2: source store class 3: destination action ID 4: destination store class */
|
||||
__( 'Migrated action with ID %1$d in %2$s to ID %3$d in %4$s', 'action-scheduler' ),
|
||||
$source_action_id,
|
||||
get_class( $this->source_store ),
|
||||
$destination_action_id,
|
||||
get_class( $this->destination_store )
|
||||
) );
|
||||
}
|
||||
|
||||
if ( $this->progress_bar ) {
|
||||
$this->progress_bar->tick();
|
||||
}
|
||||
}
|
||||
|
||||
if ( $this->progress_bar ) {
|
||||
$this->progress_bar->finish();
|
||||
}
|
||||
|
||||
\ActionScheduler::logger()->hook_stored_action();
|
||||
|
||||
do_action( 'action_scheduler/migration_batch_complete', $action_ids );
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize destination store and logger.
|
||||
*/
|
||||
public function init_destination() {
|
||||
$this->destination_store->init();
|
||||
$this->destination_logger->init();
|
||||
}
|
||||
}
|
@ -1,128 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace Action_Scheduler\Migration;
|
||||
|
||||
/**
|
||||
* Class Scheduler
|
||||
*
|
||||
* @package Action_Scheduler\WP_CLI
|
||||
*
|
||||
* @since 3.0.0
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
class Scheduler {
|
||||
/** Migration action hook. */
|
||||
const HOOK = 'action_scheduler/migration_hook';
|
||||
|
||||
/** Migration action group. */
|
||||
const GROUP = 'action-scheduler-migration';
|
||||
|
||||
/**
|
||||
* Set up the callback for the scheduled job.
|
||||
*/
|
||||
public function hook() {
|
||||
add_action( self::HOOK, array( $this, 'run_migration' ), 10, 0 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the callback for the scheduled job.
|
||||
*/
|
||||
public function unhook() {
|
||||
remove_action( self::HOOK, array( $this, 'run_migration' ), 10 );
|
||||
}
|
||||
|
||||
/**
|
||||
* The migration callback.
|
||||
*/
|
||||
public function run_migration() {
|
||||
$migration_runner = $this->get_migration_runner();
|
||||
$count = $migration_runner->run( $this->get_batch_size() );
|
||||
|
||||
if ( $count === 0 ) {
|
||||
$this->mark_complete();
|
||||
} else {
|
||||
$this->schedule_migration( time() + $this->get_schedule_interval() );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the migration complete.
|
||||
*/
|
||||
public function mark_complete() {
|
||||
$this->unschedule_migration();
|
||||
|
||||
\ActionScheduler_DataController::mark_migration_complete();
|
||||
do_action( 'action_scheduler/migration_complete' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a flag indicating whether the migration is scheduled.
|
||||
*
|
||||
* @return bool Whether there is a pending action in the store to handle the migration
|
||||
*/
|
||||
public function is_migration_scheduled() {
|
||||
$next = as_next_scheduled_action( self::HOOK );
|
||||
|
||||
return ! empty( $next );
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule the migration.
|
||||
*
|
||||
* @param int $when Optional timestamp to run the next migration batch. Defaults to now.
|
||||
*
|
||||
* @return string The action ID
|
||||
*/
|
||||
public function schedule_migration( $when = 0 ) {
|
||||
$next = as_next_scheduled_action( self::HOOK );
|
||||
|
||||
if ( ! empty( $next ) ) {
|
||||
return $next;
|
||||
}
|
||||
|
||||
if ( empty( $when ) ) {
|
||||
$when = time() + MINUTE_IN_SECONDS;
|
||||
}
|
||||
|
||||
return as_schedule_single_action( $when, self::HOOK, array(), self::GROUP );
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the scheduled migration action.
|
||||
*/
|
||||
public function unschedule_migration() {
|
||||
as_unschedule_action( self::HOOK, null, self::GROUP );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get migration batch schedule interval.
|
||||
*
|
||||
* @return int Seconds between migration runs. Defaults to 0 seconds to allow chaining migration via Async Runners.
|
||||
*/
|
||||
private function get_schedule_interval() {
|
||||
return (int) apply_filters( 'action_scheduler/migration_interval', 0 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get migration batch size.
|
||||
*
|
||||
* @return int Number of actions to migrate in each batch. Defaults to 250.
|
||||
*/
|
||||
private function get_batch_size() {
|
||||
return (int) apply_filters( 'action_scheduler/migration_batch_size', 250 );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get migration runner object.
|
||||
*
|
||||
* @return Runner
|
||||
*/
|
||||
private function get_migration_runner() {
|
||||
$config = Controller::instance()->get_migration_config_object();
|
||||
|
||||
return new Runner( $config );
|
||||
}
|
||||
|
||||
}
|
@ -1,57 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_SimpleSchedule
|
||||
*/
|
||||
class ActionScheduler_CanceledSchedule extends ActionScheduler_SimpleSchedule {
|
||||
|
||||
/**
|
||||
* Deprecated property @see $this->__wakeup() for details.
|
||||
**/
|
||||
private $timestamp = NULL;
|
||||
|
||||
/**
|
||||
* @param DateTime $after
|
||||
*
|
||||
* @return DateTime|null
|
||||
*/
|
||||
public function calculate_next( DateTime $after ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancelled actions should never have a next schedule, even if get_next()
|
||||
* is called with $after < $this->scheduled_date.
|
||||
*
|
||||
* @param DateTime $after
|
||||
* @return DateTime|null
|
||||
*/
|
||||
public function get_next( DateTime $after ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function is_recurring() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unserialize recurring schedules serialized/stored prior to AS 3.0.0
|
||||
*
|
||||
* Prior to Action Scheduler 3.0.0, schedules used different property names to refer
|
||||
* to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
|
||||
* was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
|
||||
* aligned properties and property names for better inheritance. To maintain backward
|
||||
* compatibility with schedules serialized and stored prior to 3.0, we need to correctly
|
||||
* map the old property names with matching visibility.
|
||||
*/
|
||||
public function __wakeup() {
|
||||
if ( ! is_null( $this->timestamp ) ) {
|
||||
$this->scheduled_timestamp = $this->timestamp;
|
||||
unset( $this->timestamp );
|
||||
}
|
||||
parent::__wakeup();
|
||||
}
|
||||
}
|
@ -1,102 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_CronSchedule
|
||||
*/
|
||||
class ActionScheduler_CronSchedule extends ActionScheduler_Abstract_RecurringSchedule implements ActionScheduler_Schedule {
|
||||
|
||||
/**
|
||||
* Deprecated property @see $this->__wakeup() for details.
|
||||
**/
|
||||
private $start_timestamp = NULL;
|
||||
|
||||
/**
|
||||
* Deprecated property @see $this->__wakeup() for details.
|
||||
**/
|
||||
private $cron = NULL;
|
||||
|
||||
/**
|
||||
* Wrapper for parent constructor to accept a cron expression string and map it to a CronExpression for this
|
||||
* objects $recurrence property.
|
||||
*
|
||||
* @param DateTime $start The date & time to run the action at or after. If $start aligns with the CronSchedule passed via $recurrence, it will be used. If it does not align, the first matching date after it will be used.
|
||||
* @param CronExpression|string $recurrence The CronExpression used to calculate the schedule's next instance.
|
||||
* @param DateTime|null $first (Optional) The date & time the first instance of this interval schedule ran. Default null, meaning this is the first instance.
|
||||
*/
|
||||
public function __construct( DateTime $start, $recurrence, DateTime $first = null ) {
|
||||
if ( ! is_a( $recurrence, 'CronExpression' ) ) {
|
||||
$recurrence = CronExpression::factory( $recurrence );
|
||||
}
|
||||
|
||||
// For backward compatibility, we need to make sure the date is set to the first matching cron date, not whatever date is passed in. Importantly, by passing true as the 3rd param, if $start matches the cron expression, then it will be used. This was previously handled in the now deprecated next() method.
|
||||
$date = $recurrence->getNextRunDate( $start, 0, true );
|
||||
|
||||
// parent::__construct() will set this to $date by default, but that may be different to $start now.
|
||||
$first = empty( $first ) ? $start : $first;
|
||||
|
||||
parent::__construct( $date, $recurrence, $first );
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate when an instance of this schedule would start based on a given
|
||||
* date & time using its the CronExpression.
|
||||
*
|
||||
* @param DateTime $after
|
||||
* @return DateTime
|
||||
*/
|
||||
protected function calculate_next( DateTime $after ) {
|
||||
return $this->recurrence->getNextRunDate( $after, 0, false );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function get_recurrence() {
|
||||
return strval( $this->recurrence );
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize cron schedules with data required prior to AS 3.0.0
|
||||
*
|
||||
* Prior to Action Scheduler 3.0.0, reccuring schedules used different property names to
|
||||
* refer to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
|
||||
* was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
|
||||
* aligned properties and property names for better inheritance. To guard against the
|
||||
* possibility of infinite loops if downgrading to Action Scheduler < 3.0.0, we need to
|
||||
* also store the data with the old property names so if it's unserialized in AS < 3.0,
|
||||
* the schedule doesn't end up with a null recurrence.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function __sleep() {
|
||||
|
||||
$sleep_params = parent::__sleep();
|
||||
|
||||
$this->start_timestamp = $this->scheduled_timestamp;
|
||||
$this->cron = $this->recurrence;
|
||||
|
||||
return array_merge( $sleep_params, array(
|
||||
'start_timestamp',
|
||||
'cron'
|
||||
) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Unserialize cron schedules serialized/stored prior to AS 3.0.0
|
||||
*
|
||||
* For more background, @see ActionScheduler_Abstract_RecurringSchedule::__wakeup().
|
||||
*/
|
||||
public function __wakeup() {
|
||||
if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->start_timestamp ) ) {
|
||||
$this->scheduled_timestamp = $this->start_timestamp;
|
||||
unset( $this->start_timestamp );
|
||||
}
|
||||
|
||||
if ( is_null( $this->recurrence ) && ! is_null( $this->cron ) ) {
|
||||
$this->recurrence = $this->cron;
|
||||
unset( $this->cron );
|
||||
}
|
||||
parent::__wakeup();
|
||||
}
|
||||
}
|
||||
|
@ -1,81 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_IntervalSchedule
|
||||
*/
|
||||
class ActionScheduler_IntervalSchedule extends ActionScheduler_Abstract_RecurringSchedule implements ActionScheduler_Schedule {
|
||||
|
||||
/**
|
||||
* Deprecated property @see $this->__wakeup() for details.
|
||||
**/
|
||||
private $start_timestamp = NULL;
|
||||
|
||||
/**
|
||||
* Deprecated property @see $this->__wakeup() for details.
|
||||
**/
|
||||
private $interval_in_seconds = NULL;
|
||||
|
||||
/**
|
||||
* Calculate when this schedule should start after a given date & time using
|
||||
* the number of seconds between recurrences.
|
||||
*
|
||||
* @param DateTime $after
|
||||
* @return DateTime
|
||||
*/
|
||||
protected function calculate_next( DateTime $after ) {
|
||||
$after->modify( '+' . (int) $this->get_recurrence() . ' seconds' );
|
||||
return $after;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function interval_in_seconds() {
|
||||
_deprecated_function( __METHOD__, '3.0.0', '(int)ActionScheduler_Abstract_RecurringSchedule::get_recurrence()' );
|
||||
return (int) $this->get_recurrence();
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize interval schedules with data required prior to AS 3.0.0
|
||||
*
|
||||
* Prior to Action Scheduler 3.0.0, reccuring schedules used different property names to
|
||||
* refer to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
|
||||
* was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
|
||||
* aligned properties and property names for better inheritance. To guard against the
|
||||
* possibility of infinite loops if downgrading to Action Scheduler < 3.0.0, we need to
|
||||
* also store the data with the old property names so if it's unserialized in AS < 3.0,
|
||||
* the schedule doesn't end up with a null/false/0 recurrence.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function __sleep() {
|
||||
|
||||
$sleep_params = parent::__sleep();
|
||||
|
||||
$this->start_timestamp = $this->scheduled_timestamp;
|
||||
$this->interval_in_seconds = $this->recurrence;
|
||||
|
||||
return array_merge( $sleep_params, array(
|
||||
'start_timestamp',
|
||||
'interval_in_seconds'
|
||||
) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Unserialize interval schedules serialized/stored prior to AS 3.0.0
|
||||
*
|
||||
* For more background, @see ActionScheduler_Abstract_RecurringSchedule::__wakeup().
|
||||
*/
|
||||
public function __wakeup() {
|
||||
if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->start_timestamp ) ) {
|
||||
$this->scheduled_timestamp = $this->start_timestamp;
|
||||
unset( $this->start_timestamp );
|
||||
}
|
||||
|
||||
if ( is_null( $this->recurrence ) && ! is_null( $this->interval_in_seconds ) ) {
|
||||
$this->recurrence = $this->interval_in_seconds;
|
||||
unset( $this->interval_in_seconds );
|
||||
}
|
||||
parent::__wakeup();
|
||||
}
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_NullSchedule
|
||||
*/
|
||||
class ActionScheduler_NullSchedule extends ActionScheduler_SimpleSchedule {
|
||||
|
||||
/**
|
||||
* Make the $date param optional and default to null.
|
||||
*
|
||||
* @param null $date The date & time to run the action.
|
||||
*/
|
||||
public function __construct( DateTime $date = null ) {
|
||||
$this->scheduled_date = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* This schedule has no scheduled DateTime, so we need to override the parent __sleep()
|
||||
* @return array
|
||||
*/
|
||||
public function __sleep() {
|
||||
return array();
|
||||
}
|
||||
|
||||
public function __wakeup() {
|
||||
$this->scheduled_date = null;
|
||||
}
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
<?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();
|
||||
}
|
||||
|
@ -1,71 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_SimpleSchedule
|
||||
*/
|
||||
class ActionScheduler_SimpleSchedule extends ActionScheduler_Abstract_Schedule {
|
||||
|
||||
/**
|
||||
* Deprecated property @see $this->__wakeup() for details.
|
||||
**/
|
||||
private $timestamp = NULL;
|
||||
|
||||
/**
|
||||
* @param DateTime $after
|
||||
*
|
||||
* @return DateTime|null
|
||||
*/
|
||||
public function calculate_next( DateTime $after ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function is_recurring() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize schedule with data required prior to AS 3.0.0
|
||||
*
|
||||
* Prior to Action Scheduler 3.0.0, schedules used different property names to refer
|
||||
* to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
|
||||
* was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
|
||||
* aligned properties and property names for better inheritance. To guard against the
|
||||
* scheduled date for single actions always being seen as "now" if downgrading to
|
||||
* Action Scheduler < 3.0.0, we need to also store the data with the old property names
|
||||
* so if it's unserialized in AS < 3.0, the schedule doesn't end up with a null recurrence.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function __sleep() {
|
||||
|
||||
$sleep_params = parent::__sleep();
|
||||
|
||||
$this->timestamp = $this->scheduled_timestamp;
|
||||
|
||||
return array_merge( $sleep_params, array(
|
||||
'timestamp',
|
||||
) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Unserialize recurring schedules serialized/stored prior to AS 3.0.0
|
||||
*
|
||||
* Prior to Action Scheduler 3.0.0, schedules used different property names to refer
|
||||
* to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
|
||||
* was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
|
||||
* aligned properties and property names for better inheritance. To maintain backward
|
||||
* compatibility with schedules serialized and stored prior to 3.0, we need to correctly
|
||||
* map the old property names with matching visibility.
|
||||
*/
|
||||
public function __wakeup() {
|
||||
|
||||
if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->timestamp ) ) {
|
||||
$this->scheduled_timestamp = $this->timestamp;
|
||||
unset( $this->timestamp );
|
||||
}
|
||||
parent::__wakeup();
|
||||
}
|
||||
}
|
@ -1,47 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_LoggerSchema
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*
|
||||
* Creates a custom table for storing action logs
|
||||
*/
|
||||
class ActionScheduler_LoggerSchema extends ActionScheduler_Abstract_Schema {
|
||||
const LOG_TABLE = 'actionscheduler_logs';
|
||||
|
||||
/**
|
||||
* @var int Increment this value to trigger a schema update.
|
||||
*/
|
||||
protected $schema_version = 2;
|
||||
|
||||
public function __construct() {
|
||||
$this->tables = [
|
||||
self::LOG_TABLE,
|
||||
];
|
||||
}
|
||||
|
||||
protected function get_table_definition( $table ) {
|
||||
global $wpdb;
|
||||
$table_name = $wpdb->$table;
|
||||
$charset_collate = $wpdb->get_charset_collate();
|
||||
switch ( $table ) {
|
||||
|
||||
case self::LOG_TABLE:
|
||||
|
||||
return "CREATE TABLE {$table_name} (
|
||||
log_id bigint(20) unsigned NOT NULL auto_increment,
|
||||
action_id bigint(20) unsigned NOT NULL,
|
||||
message text NOT NULL,
|
||||
log_date_gmt datetime NOT NULL default '0000-00-00 00:00:00',
|
||||
log_date_local datetime NOT NULL default '0000-00-00 00:00:00',
|
||||
PRIMARY KEY (log_id),
|
||||
KEY action_id (action_id),
|
||||
KEY log_date_gmt (log_date_gmt)
|
||||
) $charset_collate";
|
||||
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
@ -1,83 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_StoreSchema
|
||||
*
|
||||
* @codeCoverageIgnore
|
||||
*
|
||||
* Creates custom tables for storing scheduled actions
|
||||
*/
|
||||
class ActionScheduler_StoreSchema extends ActionScheduler_Abstract_Schema {
|
||||
const ACTIONS_TABLE = 'actionscheduler_actions';
|
||||
const CLAIMS_TABLE = 'actionscheduler_claims';
|
||||
const GROUPS_TABLE = 'actionscheduler_groups';
|
||||
|
||||
/**
|
||||
* @var int Increment this value to trigger a schema update.
|
||||
*/
|
||||
protected $schema_version = 3;
|
||||
|
||||
public function __construct() {
|
||||
$this->tables = [
|
||||
self::ACTIONS_TABLE,
|
||||
self::CLAIMS_TABLE,
|
||||
self::GROUPS_TABLE,
|
||||
];
|
||||
}
|
||||
|
||||
protected function get_table_definition( $table ) {
|
||||
global $wpdb;
|
||||
$table_name = $wpdb->$table;
|
||||
$charset_collate = $wpdb->get_charset_collate();
|
||||
$max_index_length = 191; // @see wp_get_db_schema()
|
||||
switch ( $table ) {
|
||||
|
||||
case self::ACTIONS_TABLE:
|
||||
|
||||
return "CREATE TABLE {$table_name} (
|
||||
action_id bigint(20) unsigned NOT NULL auto_increment,
|
||||
hook varchar(191) NOT NULL,
|
||||
status varchar(20) NOT NULL,
|
||||
scheduled_date_gmt datetime NOT NULL default '0000-00-00 00:00:00',
|
||||
scheduled_date_local datetime NOT NULL default '0000-00-00 00:00:00',
|
||||
args varchar($max_index_length),
|
||||
schedule longtext,
|
||||
group_id bigint(20) unsigned NOT NULL default '0',
|
||||
attempts int(11) NOT NULL default '0',
|
||||
last_attempt_gmt datetime NOT NULL default '0000-00-00 00:00:00',
|
||||
last_attempt_local datetime NOT NULL default '0000-00-00 00:00:00',
|
||||
claim_id bigint(20) unsigned NOT NULL default '0',
|
||||
extended_args varchar(8000) DEFAULT NULL,
|
||||
PRIMARY KEY (action_id),
|
||||
KEY hook (hook($max_index_length)),
|
||||
KEY status (status),
|
||||
KEY scheduled_date_gmt (scheduled_date_gmt),
|
||||
KEY args (args($max_index_length)),
|
||||
KEY group_id (group_id),
|
||||
KEY last_attempt_gmt (last_attempt_gmt),
|
||||
KEY claim_id (claim_id)
|
||||
) $charset_collate";
|
||||
|
||||
case self::CLAIMS_TABLE:
|
||||
|
||||
return "CREATE TABLE {$table_name} (
|
||||
claim_id bigint(20) unsigned NOT NULL auto_increment,
|
||||
date_created_gmt datetime NOT NULL default '0000-00-00 00:00:00',
|
||||
PRIMARY KEY (claim_id),
|
||||
KEY date_created_gmt (date_created_gmt)
|
||||
) $charset_collate";
|
||||
|
||||
case self::GROUPS_TABLE:
|
||||
|
||||
return "CREATE TABLE {$table_name} (
|
||||
group_id bigint(20) unsigned NOT NULL auto_increment,
|
||||
slug varchar(255) NOT NULL,
|
||||
PRIMARY KEY (group_id),
|
||||
KEY slug (slug($max_index_length))
|
||||
) $charset_collate";
|
||||
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
@ -1,13 +0,0 @@
|
||||
codecov:
|
||||
branch: master
|
||||
|
||||
coverage:
|
||||
ignore:
|
||||
- tests/.*
|
||||
- lib/.*
|
||||
status:
|
||||
project: false
|
||||
patch: false
|
||||
changes: false
|
||||
|
||||
comment: false
|
@ -1,41 +0,0 @@
|
||||
{
|
||||
"name": "woocommerce/action-scheduler",
|
||||
"description": "Action Scheduler for WordPress and WooCommerce",
|
||||
"homepage": "https://actionscheduler.org/",
|
||||
"type": "wordpress-plugin",
|
||||
"license": "GPL-3.0-or-later",
|
||||
"prefer-stable": true,
|
||||
"minimum-stability": "dev",
|
||||
"require": {},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^7.5",
|
||||
"wp-cli/wp-cli": "~1.5.1",
|
||||
"woocommerce/woocommerce-sniffs": "0.0.8"
|
||||
},
|
||||
"config": {
|
||||
"platform": {
|
||||
"php": "7.1"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": [
|
||||
"./vendor/bin/phpunit tests -c tests/phpunit.xml.dist"
|
||||
],
|
||||
"phpcs": [
|
||||
"phpcs -s -p"
|
||||
],
|
||||
"phpcs-pre-commit": [
|
||||
"phpcs -s -p -n"
|
||||
],
|
||||
"phpcbf": [
|
||||
"phpcbf -p"
|
||||
]
|
||||
},
|
||||
"extra": {
|
||||
"scripts-description": {
|
||||
"test": "Run unit tests",
|
||||
"phpcs": "Analyze code against the WordPress coding standards with PHP_CodeSniffer",
|
||||
"phpcbf": "Fix coding standards warnings/errors automatically with PHP Code Beautifier"
|
||||
}
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -1,27 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Abstract class with common Queue Cleaner functionality.
|
||||
*/
|
||||
abstract class ActionScheduler_Abstract_QueueRunner_Deprecated {
|
||||
|
||||
/**
|
||||
* Get the maximum number of seconds a batch can run for.
|
||||
*
|
||||
* @deprecated 2.1.1
|
||||
* @return int The number of seconds.
|
||||
*/
|
||||
protected function get_maximum_execution_time() {
|
||||
_deprecated_function( __METHOD__, '2.1.1', 'ActionScheduler_Abstract_QueueRunner::get_time_limit()' );
|
||||
|
||||
$maximum_execution_time = 30;
|
||||
|
||||
// Apply deprecated filter
|
||||
if ( has_filter( 'action_scheduler_maximum_execution_time' ) ) {
|
||||
_deprecated_function( 'action_scheduler_maximum_execution_time', '2.1.1', 'action_scheduler_queue_runner_time_limit' );
|
||||
$maximum_execution_time = apply_filters( 'action_scheduler_maximum_execution_time', $maximum_execution_time );
|
||||
}
|
||||
|
||||
return absint( $maximum_execution_time );
|
||||
}
|
||||
}
|
@ -1,147 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_Abstract_Schedule
|
||||
*/
|
||||
abstract class ActionScheduler_Schedule_Deprecated implements ActionScheduler_Schedule {
|
||||
|
||||
/**
|
||||
* Get the date & time this schedule was created to run, or calculate when it should be run
|
||||
* after a given date & time.
|
||||
*
|
||||
* @param DateTime $after
|
||||
*
|
||||
* @return DateTime|null
|
||||
*/
|
||||
public function next( DateTime $after = NULL ) {
|
||||
if ( empty( $after ) ) {
|
||||
$return_value = $this->get_date();
|
||||
$replacement_method = 'get_date()';
|
||||
} else {
|
||||
$return_value = $this->get_next( $after );
|
||||
$replacement_method = 'get_next( $after )';
|
||||
}
|
||||
|
||||
_deprecated_function( __METHOD__, '3.0.0', __CLASS__ . '::' . $replacement_method );
|
||||
|
||||
return $return_value;
|
||||
}
|
||||
}
|
@ -1,49 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ActionScheduler_Store_Deprecated
|
||||
* @codeCoverageIgnore
|
||||
*/
|
||||
abstract class ActionScheduler_Store_Deprecated {
|
||||
|
||||
/**
|
||||
* Mark an action that failed to fetch correctly as failed.
|
||||
*
|
||||
* @since 2.2.6
|
||||
*
|
||||
* @param int $action_id The ID of the action.
|
||||
*/
|
||||
public function mark_failed_fetch_action( $action_id ) {
|
||||
_deprecated_function( __METHOD__, '3.0.0', 'ActionScheduler_Store::mark_failure()' );
|
||||
self::$store->mark_failure( $action_id );
|
||||
}
|
||||
|
||||
/**
|
||||
* Add base hooks
|
||||
*
|
||||
* @since 2.2.6
|
||||
*/
|
||||
protected static function hook() {
|
||||
_deprecated_function( __METHOD__, '3.0.0' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove base hooks
|
||||
*
|
||||
* @since 2.2.6
|
||||
*/
|
||||
protected static function unhook() {
|
||||
_deprecated_function( __METHOD__, '3.0.0' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the site's local time.
|
||||
*
|
||||
* @deprecated 2.1.0
|
||||
* @return DateTimeZone
|
||||
*/
|
||||
protected function get_local_timezone() {
|
||||
_deprecated_function( __FUNCTION__, '2.1.0', 'ActionScheduler_TimezoneHelper::set_local_timezone()' );
|
||||
return ActionScheduler_TimezoneHelper::get_local_timezone();
|
||||
}
|
||||
}
|
@ -1,126 +0,0 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Deprecated API functions for scheduling actions
|
||||
*
|
||||
* Functions with the wc prefix were deprecated to avoid confusion with
|
||||
* Action Scheduler being included in WooCommerce core, and it providing
|
||||
* a different set of APIs for working with the action queue.
|
||||
*/
|
||||
|
||||
/**
|
||||
* 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 = '' ) {
|
||||
_deprecated_function( __FUNCTION__, '2.1.0', 'as_schedule_single_action()' );
|
||||
return as_schedule_single_action( $timestamp, $hook, $args, $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
|
||||
*
|
||||
* @deprecated 2.1.0
|
||||
*
|
||||
* @return string The job ID
|
||||
*/
|
||||
function wc_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args = array(), $group = '' ) {
|
||||
_deprecated_function( __FUNCTION__, '2.1.0', 'as_schedule_recurring_action()' );
|
||||
return as_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook, $args, $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
|
||||
*
|
||||
* @deprecated 2.1.0
|
||||
*
|
||||
* @return string The job ID
|
||||
*/
|
||||
function wc_schedule_cron_action( $timestamp, $schedule, $hook, $args = array(), $group = '' ) {
|
||||
_deprecated_function( __FUNCTION__, '2.1.0', 'as_schedule_cron_action()' );
|
||||
return as_schedule_cron_action( $timestamp, $schedule, $hook, $args, $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
|
||||
*
|
||||
* @deprecated 2.1.0
|
||||
*/
|
||||
function wc_unschedule_action( $hook, $args = array(), $group = '' ) {
|
||||
_deprecated_function( __FUNCTION__, '2.1.0', 'as_unschedule_action()' );
|
||||
as_unschedule_action( $hook, $args, $group );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $hook
|
||||
* @param array $args
|
||||
* @param string $group
|
||||
*
|
||||
* @deprecated 2.1.0
|
||||
*
|
||||
* @return int|bool The timestamp for the next occurrence, or false if nothing was found
|
||||
*/
|
||||
function wc_next_scheduled_action( $hook, $args = NULL, $group = '' ) {
|
||||
_deprecated_function( __FUNCTION__, '2.1.0', 'as_next_scheduled_action()' );
|
||||
return as_next_scheduled_action( $hook, $args, $group );
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @deprecated 2.1.0
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
function wc_get_scheduled_actions( $args = array(), $return_format = OBJECT ) {
|
||||
_deprecated_function( __FUNCTION__, '2.1.0', 'as_get_scheduled_actions()' );
|
||||
return as_get_scheduled_actions( $args, $return_format );
|
||||
}
|
@ -1 +0,0 @@
|
||||
actionscheduler.org
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user