-
+
-
+
+
+
-
+
-
-
+
+
+
+
get_status() ),
+ );
+
if ( wcs_is_subscription( $order ) ) {
- echo esc_html( wcs_get_subscription_status_name( $order->get_status( 'view' ) ) );
+ $status_name = wcs_get_subscription_status_name( $order->get_status() );
+ $classes[] = 'subscription-status';
} else {
- echo esc_html( wc_get_order_status_name( $order->get_status( 'view' ) ) );
+ $status_name = wc_get_order_status_name( $order->get_status() );
}
+
+ printf( '%s ', esc_attr( implode( ' ', $classes ) ), esc_html( $status_name ) );
?>
diff --git a/includes/admin/meta-boxes/views/html-retries-table.php b/includes/admin/meta-boxes/views/html-retries-table.php
index b5d3935..d8272cf 100755
--- a/includes/admin/meta-boxes/views/html-retries-table.php
+++ b/includes/admin/meta-boxes/views/html-retries-table.php
@@ -53,12 +53,22 @@ if ( ! defined( 'ABSPATH' ) ) {
get_status() ) ); ?>
+ get_status_to_apply( $object_type );
+ $css_classes = array( 'order-status', 'status-' . $status );
+
+ if ( 'subscription' === $object_type ) :
+ $status_name = wcs_get_subscription_status_name( $status );
+ $css_classes[] = 'subscription-status';
+ else :
+ $status_name = wc_get_order_status_name( $status );
+ endif;
+ ?>
- get_status_to_apply( 'order' ) ) ); ?>
-
-
- get_status_to_apply( 'subscription' ) ) ); ?>
+
+
get_email_template(); ?>
diff --git a/includes/admin/reports/class-wcs-report-subscription-events-by-date.php b/includes/admin/reports/class-wcs-report-subscription-events-by-date.php
index e91fd32..7d2ce50 100755
--- a/includes/admin/reports/class-wcs-report-subscription-events-by-date.php
+++ b/includes/admin/reports/class-wcs-report-subscription-events-by-date.php
@@ -566,7 +566,7 @@ class WCS_Report_Subscription_Events_By_Date extends WC_Admin_Report {
);
// For the subscriptions count we only need to display the subscriptions included on the last day of the report period so pass the last cache key. The array keys are integers so using max() returns the last array key.
- $data_key = max( array_keys( $this->report_data->subscriber_counts ) );
+ $data_key = $this->report_data->subscriber_counts ? max( array_keys( $this->report_data->subscriber_counts ) ) : false;
$legend[] = array(
'title' => sprintf( __( '%2$s %1$s current subscriptions', 'woocommerce-subscriptions' ), ' ' . $this->report_data->total_subscriptions_at_period_end . ' ',
diff --git a/includes/class-wc-subscriptions-cart-validator.php b/includes/class-wc-subscriptions-cart-validator.php
index 0301a82..4b570e7 100755
--- a/includes/class-wc-subscriptions-cart-validator.php
+++ b/includes/class-wc-subscriptions-cart-validator.php
@@ -69,9 +69,9 @@ class WC_Subscriptions_Cart_Validator {
// Redirect to cart page to remove subscription & notify shopper
if ( WC_Subscriptions::is_woocommerce_pre( '3.0.8' ) ) {
- add_filter( 'add_to_cart_fragments', __CLASS__ . '::redirect_ajax_add_to_cart' );
+ add_filter( 'add_to_cart_fragments', 'WC_Subscriptions::redirect_ajax_add_to_cart' );
} else {
- add_filter( 'woocommerce_add_to_cart_fragments', __CLASS__ . '::redirect_ajax_add_to_cart' );
+ add_filter( 'woocommerce_add_to_cart_fragments', 'WC_Subscriptions::redirect_ajax_add_to_cart' );
}
}
@@ -98,10 +98,8 @@ class WC_Subscriptions_Cart_Validator {
}
foreach ( $cart->cart_contents as $key => $item ) {
- $is_subscription = WC_Subscriptions_Product::is_subscription( $item['product_id'] );
-
// If a non-subscription product is found in the cart containing subscriptions ( maybe because of carts merge while logging in )
- if ( ! $is_subscription ) {
+ if ( ! WC_Subscriptions_Product::is_subscription( $item['data'] ) ) {
// remove the subscriptions from the cart
WC_Subscriptions_Cart::remove_subscriptions_from_cart();
@@ -115,9 +113,11 @@ class WC_Subscriptions_Cart_Validator {
} else {
add_filter( 'woocommerce_add_to_cart_fragments', array( 'WC_Subscriptions', 'redirect_ajax_add_to_cart' ) );
}
+
break;
}
}
+
return $cart;
}
diff --git a/includes/class-wc-subscriptions-change-payment-gateway.php b/includes/class-wc-subscriptions-change-payment-gateway.php
index 2a4286b..0cb625c 100755
--- a/includes/class-wc-subscriptions-change-payment-gateway.php
+++ b/includes/class-wc-subscriptions-change-payment-gateway.php
@@ -12,11 +12,12 @@ class WC_Subscriptions_Change_Payment_Gateway {
public static $is_request_to_change_payment = false;
- private static $woocommerce_messages = array();
-
- private static $woocommerce_errors = array();
-
- private static $original_order_dates = array();
+ /**
+ * An internal cache of WooCommerce customer notices.
+ *
+ * @var array
+ */
+ private static $notices = array();
/**
* Bootstraps the class and hooks required actions & filters.
@@ -32,7 +33,7 @@ class WC_Subscriptions_Change_Payment_Gateway {
add_action( 'woocommerce_loaded', __CLASS__ . '::attach_dependant_hooks' );
// Keep a record of any messages or errors that should be displayed
- add_action( 'before_woocommerce_pay', __CLASS__ . '::store_pay_shortcode_messages', 100 );
+ add_action( 'before_woocommerce_pay', __CLASS__ . '::store_pay_shortcode_messages', 5 );
// Hijack the default pay shortcode
add_action( 'after_woocommerce_pay', __CLASS__ . '::maybe_replace_pay_shortcode', 100 );
@@ -113,14 +114,7 @@ class WC_Subscriptions_Change_Payment_Gateway {
* @since 2.3.6
*/
public static function store_pay_shortcode_messages() {
- if ( wc_notice_count( 'notice' ) > 0 ) {
- self::$woocommerce_messages = wc_get_notices( 'success' );
- self::$woocommerce_messages += wc_get_notices( 'notice' );
- }
-
- if ( wc_notice_count( 'error' ) > 0 ) {
- self::$woocommerce_errors = wc_get_notices( 'error' );
- }
+ self::$notices = wc_get_notices();
}
/**
@@ -144,23 +138,35 @@ class WC_Subscriptions_Change_Payment_Gateway {
global $wp;
$valid_request = false;
- // if the request to pay for the order belongs to a subscription but there's no GET params for changing payment method, show receipt page.
- if ( ! self::$is_request_to_change_payment && isset( $wp->query_vars['order-pay'] ) && wcs_is_subscription( absint( $wp->query_vars['order-pay'] ) ) ) {
+ // Exit early if this isn't a change payment request and it's not a order-pay page for a subscription
+ if ( ! self::$is_request_to_change_payment && ( ! isset( $wp->query_vars['order-pay'] ) || ! wcs_is_subscription( absint( $wp->query_vars['order-pay'] ) ) ) ) {
+ return;
+ }
- $valid_request = true;
+ /*
+ * Clear the output buffer.
+ *
+ * Because this function is hooked onto 'after_woocommerce_pay', WC would have started outputting
+ * the core order pay shortcode. Clearing the output buffer removes that partially outputted template.
+ */
+ ob_clean();
- ob_clean();
+ // Because we've cleared the buffer, we need to re-include the opening container div.
+ echo '';
+
+ // If the request to pay for the order belongs to a subscription but there's no GET params for changing payment method, show receipt page.
+ if ( ! self::$is_request_to_change_payment ) {
+ $valid_request = true;
+ $subscription = wcs_get_subscription( absint( $wp->query_vars['order-pay'] ) );
+ $subscription_key = isset( $_GET['key'] ) ? wc_clean( $_GET['key'] ) : '';
do_action( 'before_woocommerce_pay' );
- $subscription_key = isset( $_GET['key'] ) ? wc_clean( $_GET['key'] ) : '';
- $subscription = wcs_get_subscription( absint( $wp->query_vars['order-pay'] ) );
-
/**
* wcs_before_replace_pay_shortcode
*
* Action that allows payment methods to modify the subscription object so, for example,
- * if the new payment method still hasn't been set, they can set it temporarily (without saving)
+ * if the new payment method still hasn't been set, they can set it temporarily (without saving).
*
* @since 2.4.0
*
@@ -168,93 +174,28 @@ class WC_Subscriptions_Change_Payment_Gateway {
*/
do_action( 'wcs_before_replace_pay_shortcode', $subscription );
- if ( $subscription->get_id() == absint( $wp->query_vars['order-pay'] ) && $subscription->get_order_key() == $subscription_key ) {
-
- ?>
-
-
-
- tags
- echo wp_kses( sprintf( esc_html__( 'Subscription Number: %s', 'woocommerce-subscriptions' ), '' . esc_html( $subscription->get_order_number() ) . ' ' ), array( 'strong' => true ) );
- ?>
-
-
- tags
- echo wp_kses( sprintf( esc_html__( 'Next Payment Date: %s', 'woocommerce-subscriptions' ), '' . esc_html( $subscription->get_date_to_display( 'next_payment' ) ) . ' ' ), array( 'strong' => true ) );
- ?>
-
-
- tags
- echo wp_kses_post( sprintf( esc_html__( 'Total: %s', 'woocommerce-subscriptions' ), '' . $subscription->get_formatted_order_total() . ' ' ) );
- ?>
-
- get_payment_method_title() ) : ?>
-
- ' . esc_html( $subscription->get_payment_method_to_display() ) . '' ), array( 'strong' => true ) );
- ?>
-
-
-
-
- get_payment_method(), $subscription->get_id() ); ?>
-
-
- get_id() === absint( $wp->query_vars['order-pay'] ) && $subscription->get_order_key() === $subscription_key ) {
+ WCS_Template_Loader::get_subscription_receipt_template( $subscription );
} else {
- wc_add_notice( __( 'Sorry, this subscription change payment method request is invalid and cannot be processed.', 'woocommerce-subscriptions' ), 'error' );
+ // The before_woocommerce_pay action would have printed all the notices so we need to print the notice directly.
+ wc_print_notice( __( 'Sorry, this subscription change payment method request is invalid and cannot be processed.', 'woocommerce-subscriptions' ), 'error' );
}
-
- wc_print_notices();
-
- } elseif ( ! self::$is_request_to_change_payment ) {
- return;
-
} else {
- ob_clean();
+ // Re-add all the notices that would have been displayed but have now been cleared from the output.
+ foreach ( self::$notices as $notice_type => $notices ) {
+ foreach ( $notices as $notice ) {
+ wc_add_notice( $notice, $notice_type );
+ }
+ }
+ $subscription = wcs_get_subscription( absint( $_GET['change_payment_method'] ) );
+ $valid_request = self::validate_change_payment_request( $subscription );
+
+ // WC display notices on this hook so trigger it after all notices have been added,
do_action( 'before_woocommerce_pay' );
- echo '
';
-
- if ( ! empty( self::$woocommerce_errors ) ) {
- foreach ( self::$woocommerce_errors as $error ) {
- wc_add_notice( $error, 'error' );
- }
- }
-
- if ( ! empty( self::$woocommerce_messages ) ) {
- foreach ( self::$woocommerce_messages as $message ) {
- wc_add_notice( $message, 'success' );
- }
- }
-
- $subscription = wcs_get_subscription( absint( $_GET['change_payment_method'] ) );
-
- if ( wp_verify_nonce( $_GET['_wpnonce'] ) === false ) {
-
- wc_add_notice( __( 'There was an error with your request. Please try again.', 'woocommerce-subscriptions' ), 'error' );
-
- } elseif ( empty( $subscription ) ) {
-
- wc_add_notice( __( 'Invalid Subscription.', 'woocommerce-subscriptions' ), 'error' );
-
- } elseif ( ! current_user_can( 'edit_shop_subscription_payment_method', $subscription->get_id() ) ) {
-
- wc_add_notice( __( 'That doesn\'t appear to be one of your subscriptions.', 'woocommerce-subscriptions' ), 'error' );
-
- } elseif ( ! $subscription->can_be_updated_to( 'new-payment-method' ) ) {
-
- wc_add_notice( __( 'The payment method can not be changed for that subscription.', 'woocommerce-subscriptions' ), 'error' );
-
- } else {
-
+ if ( $valid_request ) {
if ( $subscription->get_time( 'next_payment' ) > 0 ) {
// translators: placeholder is next payment's date
$next_payment_string = sprintf( __( ' Next payment is due %s.', 'woocommerce-subscriptions' ), $subscription->get_date_to_display( 'next_payment' ) );
@@ -263,38 +204,18 @@ class WC_Subscriptions_Change_Payment_Gateway {
}
// translators: placeholder is either empty or "Next payment is due..."
- wc_add_notice( sprintf( __( 'Choose a new payment method.%s', 'woocommerce-subscriptions' ), $next_payment_string ), 'notice' );
- wc_print_notices();
+ wc_print_notice( sprintf( __( 'Choose a new payment method.%s', 'woocommerce-subscriptions' ), $next_payment_string ), 'notice' );
- if ( $subscription->get_order_key() == $_GET['key'] ) {
+ // Set the customer location to subscription billing location
+ foreach ( array( 'country', 'state', 'postcode' ) as $address_property ) {
+ $subscription_address = $subscription->{"get_billing_$address_property"}();
- $subscription_billing_country = $subscription->get_billing_country();
- $subscription_billing_state = $subscription->get_billing_state();
- $subscription_billing_postcode = $subscription->get_billing_postcode();
-
- // Set customer location to order location
- if ( $subscription_billing_country ) {
- $setter = is_callable( array( WC()->customer, 'set_billing_country' ) ) ? 'set_billing_country' : 'set_country';
- WC()->customer->$setter( $subscription_billing_country );
+ if ( $subscription_address ) {
+ WC()->customer->{"set_billing_$address_property"}( $subscription_address );
}
- if ( $subscription_billing_state ) {
- $setter = is_callable( array( WC()->customer, 'set_billing_state' ) ) ? 'set_billing_state' : 'set_state';
- WC()->customer->$setter( $subscription_billing_state );
- }
- if ( $subscription_billing_postcode ) {
- $setter = is_callable( array( WC()->customer, 'set_billing_postcode' ) ) ? 'set_billing_postcode' : 'set_postcode';
- WC()->customer->$setter( $subscription_billing_postcode );
- }
-
- wc_get_template( 'checkout/form-change-payment-method.php', array( 'subscription' => $subscription ), '', plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'templates/' );
-
- $valid_request = true;
-
- } else {
-
- wc_add_notice( __( 'Invalid order.', 'woocommerce-subscriptions' ), 'error' );
-
}
+
+ wc_get_template( 'checkout/form-change-payment-method.php', array( 'subscription' => $subscription ), '', plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'templates/' );
}
}
@@ -303,6 +224,40 @@ class WC_Subscriptions_Change_Payment_Gateway {
}
}
+
+ /**
+ * Validates the request to change a subscription's payment method.
+ *
+ * Will display a customer facing notice if the request is invalid.
+ *
+ * @since 3.0.0
+ *
+ * @param WC_Subscription $subscription
+ * @return bool Whether the request is valid or not.
+ */
+ private static function validate_change_payment_request( $subscription ) {
+ $is_valid = true;
+
+ if ( wp_verify_nonce( $_GET['_wpnonce'] ) === false ) {
+ $is_valid = false;
+ wc_add_notice( __( 'There was an error with your request. Please try again.', 'woocommerce-subscriptions' ), 'error' );
+ } elseif ( empty( $subscription ) ) {
+ $is_valid = false;
+ wc_add_notice( __( 'Invalid Subscription.', 'woocommerce-subscriptions' ), 'error' );
+ } elseif ( ! current_user_can( 'edit_shop_subscription_payment_method', $subscription->get_id() ) ) {
+ $is_valid = false;
+ wc_add_notice( __( 'That doesn\'t appear to be one of your subscriptions.', 'woocommerce-subscriptions' ), 'error' );
+ } elseif ( ! $subscription->can_be_updated_to( 'new-payment-method' ) ) {
+ $is_valid = false;
+ wc_add_notice( __( 'The payment method can not be changed for that subscription.', 'woocommerce-subscriptions' ), 'error' );
+ } elseif ( $subscription->get_order_key() !== $_GET['key'] ) {
+ $is_valid = false;
+ wc_add_notice( __( 'Invalid order.', 'woocommerce-subscriptions' ), 'error' );
+ }
+
+ return $is_valid;
+ }
+
/**
* Add a "Change Payment Method" button to the "My Subscriptions" table.
*
@@ -697,8 +652,8 @@ class WC_Subscriptions_Change_Payment_Gateway {
return false;
}
- // If there's no recurring payment, there's no need to add or update the payment method.
- if ( $subscription->get_total() == 0 ) {
+ // If there's no recurring payment, there's no need to add or update the payment method. Use the 'edit' context so we check the unfiltered total.
+ if ( $subscription->get_total( 'edit' ) == 0 ) {
return false;
}
diff --git a/includes/class-wc-subscriptions-email.php b/includes/class-wc-subscriptions-email.php
index dbca723..8c388f5 100755
--- a/includes/class-wc-subscriptions-email.php
+++ b/includes/class-wc-subscriptions-email.php
@@ -36,15 +36,16 @@ class WC_Subscriptions_Email {
* @since 1.4
*/
public static function add_emails( $email_classes ) {
- $email_classes['WCS_Email_New_Renewal_Order'] = new WCS_Email_New_Renewal_Order();
- $email_classes['WCS_Email_New_Switch_Order'] = new WCS_Email_New_Switch_Order();
- $email_classes['WCS_Email_Processing_Renewal_Order'] = new WCS_Email_Processing_Renewal_Order();
- $email_classes['WCS_Email_Completed_Renewal_Order'] = new WCS_Email_Completed_Renewal_Order();
- $email_classes['WCS_Email_Completed_Switch_Order'] = new WCS_Email_Completed_Switch_Order();
- $email_classes['WCS_Email_Customer_Renewal_Invoice'] = new WCS_Email_Customer_Renewal_Invoice();
- $email_classes['WCS_Email_Cancelled_Subscription'] = new WCS_Email_Cancelled_Subscription();
- $email_classes['WCS_Email_Expired_Subscription'] = new WCS_Email_Expired_Subscription();
- $email_classes['WCS_Email_On_Hold_Subscription'] = new WCS_Email_On_Hold_Subscription();
+ $email_classes['WCS_Email_New_Renewal_Order'] = new WCS_Email_New_Renewal_Order();
+ $email_classes['WCS_Email_New_Switch_Order'] = new WCS_Email_New_Switch_Order();
+ $email_classes['WCS_Email_Processing_Renewal_Order'] = new WCS_Email_Processing_Renewal_Order();
+ $email_classes['WCS_Email_Completed_Renewal_Order'] = new WCS_Email_Completed_Renewal_Order();
+ $email_classes['WCS_Email_Customer_On_Hold_Renewal_Order'] = new WCS_Email_Customer_On_Hold_Renewal_Order();
+ $email_classes['WCS_Email_Completed_Switch_Order'] = new WCS_Email_Completed_Switch_Order();
+ $email_classes['WCS_Email_Customer_Renewal_Invoice'] = new WCS_Email_Customer_Renewal_Invoice();
+ $email_classes['WCS_Email_Cancelled_Subscription'] = new WCS_Email_Cancelled_Subscription();
+ $email_classes['WCS_Email_Expired_Subscription'] = new WCS_Email_Expired_Subscription();
+ $email_classes['WCS_Email_On_Hold_Subscription'] = new WCS_Email_On_Hold_Subscription();
return $email_classes;
}
@@ -67,13 +68,26 @@ class WC_Subscriptions_Email {
add_action( 'woocommerce_subscriptions_switch_completed', __CLASS__ . '::send_switch_order_email', 10 );
$order_email_actions = array(
- 'woocommerce_order_status_pending_to_processing',
+ // WC New Order Emails (Admin) -- other hooks below also trigger this email.
'woocommerce_order_status_pending_to_completed',
- 'woocommerce_order_status_pending_to_on-hold',
- 'woocommerce_order_status_failed_to_processing',
'woocommerce_order_status_failed_to_completed',
- 'woocommerce_order_status_failed_to_on-hold',
+ 'woocommerce_order_status_cancelled_to_completed',
+
+ // WC Order Processing Emails.
+ 'woocommerce_order_status_pending_to_processing',
+ 'woocommerce_order_status_failed_to_processing',
+ 'woocommerce_order_status_cancelled_to_processing',
+ 'woocommerce_order_status_on-hold_to_processing',
+
+ // WC Order Completed Emails.
'woocommerce_order_status_completed',
+
+ // WC On-hold Order Emails.
+ 'woocommerce_order_status_pending_to_on-hold',
+ 'woocommerce_order_status_failed_to_on-hold',
+ 'woocommerce_order_status_cancelled_to_on-hold',
+
+ // WCS Order Invoice Emails.
'woocommerce_generated_manual_renewal_order',
'woocommerce_order_status_failed',
);
@@ -318,7 +332,7 @@ class WC_Subscriptions_Email {
$hook = current_filter();
}
- if ( false === WC_Subscriptions::is_woocommerce_pre( '3.0' ) && apply_filters( 'woocommerce_defer_transactional_emails', true ) ) {
+ if ( false === WC_Subscriptions::is_woocommerce_pre( '3.0' ) && apply_filters( 'woocommerce_defer_transactional_emails', false ) ) {
add_action( $hook, array( 'WC_Emails', 'queue_transactional_email' ), $priority, $accepted_args );
} else {
add_action( $hook, array( 'WC_Emails', 'send_transactional_email' ), $priority, $accepted_args );
diff --git a/includes/class-wc-subscriptions-manager.php b/includes/class-wc-subscriptions-manager.php
index 0e88f0e..3d749df 100755
--- a/includes/class-wc-subscriptions-manager.php
+++ b/includes/class-wc-subscriptions-manager.php
@@ -125,11 +125,7 @@ class WC_Subscriptions_Manager {
}
if ( 0 == $renewal_order->get_total() ) {
-
- $renewal_order->payment_complete();
-
- $subscription->update_status( 'active' ); // don't call payment_complete() because technically, no payment was received
-
+ $renewal_order->payment_complete(); // We don't need to reactivate the subscription here because calling payment complete on the order will do that for us.
} else {
if ( $subscription->is_manual() ) {
diff --git a/includes/class-wc-subscriptions-switcher.php b/includes/class-wc-subscriptions-switcher.php
index df9b0da..3d86baf 100755
--- a/includes/class-wc-subscriptions-switcher.php
+++ b/includes/class-wc-subscriptions-switcher.php
@@ -509,7 +509,10 @@ class WC_Subscriptions_Switcher {
$name = WC_Subscriptions_Admin::$option_prefix . '_allow_switching_' . $option['id'];
$value = get_option( $name, 'no' );
- echo sprintf( ' %s ', checked( $value, 'yes', false ), esc_attr( $name ), esc_html( $label ) );
+ echo '';
+ echo sprintf( ' %s', checked( $value, 'yes', false ), esc_attr( $name ), esc_html( $label ) );
+ echo isset( $option['desc_tip'] ) ? wcs_help_tip( $option['desc_tip'], true ) : '';
+ echo ' ';
}
?>
diff --git a/includes/class-wcs-cart-renewal.php b/includes/class-wcs-cart-renewal.php
index 6728d03..b42b0e0 100755
--- a/includes/class-wcs-cart-renewal.php
+++ b/includes/class-wcs-cart-renewal.php
@@ -423,7 +423,7 @@ class WCS_Cart_Renewal {
$price = $item_to_renew['line_subtotal'];
if ( $_product->is_taxable() && $subscription->get_prices_include_tax() ) {
- $price += $item_to_renew['subtotal_tax'];
+ $price += array_sum( $item_to_renew['taxes']['subtotal'] ); // Use the taxes array items here as they contain taxes to a more accurate number of decimals.
}
$_product->set_price( $price / $item_to_renew['qty'] );
diff --git a/includes/class-wcs-dependent-hook-manager.php b/includes/class-wcs-dependent-hook-manager.php
index c06e0d8..94db026 100755
--- a/includes/class-wcs-dependent-hook-manager.php
+++ b/includes/class-wcs-dependent-hook-manager.php
@@ -6,7 +6,7 @@
*
* @package WooCommerce Subscriptions
* @category Class
- * @author Automattic
+ * @author WooCommerce
* @since 2.6.0
*/
diff --git a/includes/class-wcs-my-account-auto-renew-toggle.php b/includes/class-wcs-my-account-auto-renew-toggle.php
index ab2e71e..24aa1c1 100755
--- a/includes/class-wcs-my-account-auto-renew-toggle.php
+++ b/includes/class-wcs-my-account-auto-renew-toggle.php
@@ -62,6 +62,24 @@ class WCS_My_Account_Auto_Renew_Toggle {
return true;
}
+ /**
+ * Determines if a subscription is eligible for toggling auto renewal and whether the user, or current user has permission to do so.
+ *
+ * @since 3.0.1
+ *
+ * @param WC_Subscription $subscription The subscription to check if auto renewal is allowed.
+ * @param int $user_id The user ID to check if they have permission. Optional. Default is current user.
+ *
+ * @return bool Whether the subscription can be toggled and the user has the permission to do so.
+ */
+ public static function can_user_toggle_auto_renewal( $subscription, $user_id = 0 ) {
+ if ( empty( $user_id ) ) {
+ $user_id = get_current_user_id();
+ }
+
+ return user_can( absint( $user_id ), 'toggle_shop_subscription_auto_renewal', $subscription->get_id() ) && self::can_subscription_auto_renewal_be_changed( $subscription );
+ }
+
/**
* Disable auto renewal of subscription
*
@@ -78,7 +96,7 @@ class WCS_My_Account_Auto_Renew_Toggle {
$subscription = wcs_get_subscription( $subscription_id );
- if ( $subscription ) {
+ if ( $subscription && self::can_user_toggle_auto_renewal( $subscription ) ) {
$subscription->set_requires_manual_renewal( true );
$subscription->save();
@@ -102,7 +120,7 @@ class WCS_My_Account_Auto_Renew_Toggle {
$subscription = wcs_get_subscription( $subscription_id );
- if ( wc_get_payment_gateway_by_order( $subscription ) ) {
+ if ( wc_get_payment_gateway_by_order( $subscription ) && self::can_user_toggle_auto_renewal( $subscription ) ) {
$subscription->set_requires_manual_renewal( false );
$subscription->save();
diff --git a/includes/class-wcs-retry-manager.php b/includes/class-wcs-retry-manager.php
index 95d4bfc..c2c6ca4 100755
--- a/includes/class-wcs-retry-manager.php
+++ b/includes/class-wcs-retry-manager.php
@@ -85,12 +85,12 @@ class WCS_Retry_Manager {
* Adds any extra status that may be needed for a given order to check if it may
* need payment
*
- * @param Array $statuses
+ * @param array $statuses
* @param WC_Order $order
* @return array
* @since 2.2.1
*/
- public static function check_order_statuses_for_payment( $statuses, $order ) {
+ public static function check_order_statuses_for_payment( $statuses, $order = null ) {
$last_retry = self::store()->get_last_retry_for_order( wcs_get_objects_property( $order, 'id' ) );
if ( $last_retry ) {
diff --git a/includes/class-wcs-switch-totals-calculator.php b/includes/class-wcs-switch-totals-calculator.php
index e3123a4..a53d382 100755
--- a/includes/class-wcs-switch-totals-calculator.php
+++ b/includes/class-wcs-switch-totals-calculator.php
@@ -174,7 +174,7 @@ class WCS_Switch_Totals_Calculator {
/**
* Allow third-parties to filter the switch item and its properties.
*
- * @since 2.7.2
+ * @since 3.0.0
*
* @param WCS_Switch_Cart_Item $switch_item The switch item.
* @param array $cart_item The item in the cart the switch item was created for.
diff --git a/includes/class-wcs-template-loader.php b/includes/class-wcs-template-loader.php
index a668c08..35fc7cc 100755
--- a/includes/class-wcs-template-loader.php
+++ b/includes/class-wcs-template-loader.php
@@ -88,4 +88,15 @@ class WCS_Template_Loader {
add_action( 'woocommerce_order_item_meta_end', 'WC_Subscriptions_Switcher::print_switch_link', 10, 3 );
}
}
+
+ /**
+ * Gets the subscription receipt template content.
+ *
+ * @since 3.0.0
+ *
+ * @param WC_Subscription $subscription The subscription to display the receipt for.
+ */
+ public static function get_subscription_receipt_template( $subscription ) {
+ wc_get_template( 'checkout/subscription-receipt.php', array( 'subscription' => $subscription ), '', plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'templates/' );
+ }
}
diff --git a/includes/emails/class-wcs-email-customer-on-hold-renewal-order.php b/includes/emails/class-wcs-email-customer-on-hold-renewal-order.php
new file mode 100755
index 0000000..a020fde
--- /dev/null
+++ b/includes/emails/class-wcs-email-customer-on-hold-renewal-order.php
@@ -0,0 +1,105 @@
+id = 'customer_on_hold_renewal_order';
+ $this->customer_email = true;
+ $this->title = __( 'On-hold Renewal Order', 'woocommerce-subscriptions' );
+ $this->description = __( 'This is an order notification sent to customers containing order details after a renewal order is placed on-hold.', 'woocommerce-subscriptions' );
+ $this->subject = __( 'Your {blogname} renewal order has been received!', 'woocommerce-subscriptions' );
+ $this->heading = __( 'Thank you for your renewal order', 'woocommerce-subscriptions' );
+ $this->template_html = 'emails/customer-on-hold-renewal-order.php';
+ $this->template_plain = 'emails/plain/customer-on-hold-renewal-order.php';
+ $this->template_base = plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'templates/';
+ $this->placeholders = array(
+ '{order_date}' => '',
+ '{order_number}' => '',
+ );
+
+ // Triggers for this email.
+ add_action( 'woocommerce_order_status_pending_to_on-hold_renewal_notification', array( $this, 'trigger' ), 10, 2 );
+ add_action( 'woocommerce_order_status_failed_to_on-hold_renewal_notification', array( $this, 'trigger' ), 10, 2 );
+ add_action( 'woocommerce_order_status_cancelled_to_on-hold_renewal_notification', array( $this, 'trigger' ), 10, 2 );
+
+ // We want most of the parent's methods, with none of its properties, so call its parent's constructor
+ WC_Email::__construct();
+ }
+
+ /**
+ * Get the default e-mail subject.
+ *
+ * @since 3.0.0
+ * @return string
+ */
+ public function get_default_subject() {
+ return $this->subject;
+ }
+
+ /**
+ * Get the default e-mail heading.
+ *
+ * @since 3.0.0
+ * @return string
+ */
+ public function get_default_heading() {
+ return $this->heading;
+ }
+
+ /**
+ * Get content html.
+ *
+ * @return string
+ */
+ public function get_content_html() {
+ return wc_get_template_html(
+ $this->template_html,
+ array(
+ 'order' => $this->object,
+ 'email_heading' => $this->get_heading(),
+ 'additional_content' => is_callable( array( $this, 'get_additional_content' ) ) ? $this->get_additional_content() : '', // WC 3.7 introduced an additional content field for all emails.
+ 'sent_to_admin' => false,
+ 'plain_text' => false,
+ 'email' => $this,
+ ),
+ '',
+ $this->template_base
+ );
+ }
+
+ /**
+ * Get content plain.
+ *
+ * @return string
+ */
+ public function get_content_plain() {
+ return wc_get_template_html(
+ $this->template_plain,
+ array(
+ 'order' => $this->object,
+ 'email_heading' => $this->get_heading(),
+ 'additional_content' => is_callable( array( $this, 'get_additional_content' ) ) ? $this->get_additional_content() : '', // WC 3.7 introduced an additional content field for all emails.
+ 'sent_to_admin' => false,
+ 'plain_text' => true,
+ 'email' => $this,
+ ),
+ '',
+ $this->template_base
+ );
+ }
+}
diff --git a/includes/emails/class-wcs-email-new-renewal-order.php b/includes/emails/class-wcs-email-new-renewal-order.php
index c1d9ed4..f3467fc 100755
--- a/includes/emails/class-wcs-email-new-renewal-order.php
+++ b/includes/emails/class-wcs-email-new-renewal-order.php
@@ -36,6 +36,9 @@ class WCS_Email_New_Renewal_Order extends WC_Email_New_Order {
add_action( 'woocommerce_order_status_failed_to_processing_renewal_notification', array( $this, 'trigger' ) );
add_action( 'woocommerce_order_status_failed_to_completed_renewal_notification', array( $this, 'trigger' ) );
add_action( 'woocommerce_order_status_failed_to_on-hold_renewal_notification', array( $this, 'trigger' ) );
+ add_action( 'woocommerce_order_status_cancelled_to_processing_renewal_notification', array( $this, 'trigger' ) );
+ add_action( 'woocommerce_order_status_cancelled_to_completed_renewal_notification', array( $this, 'trigger' ) );
+ add_action( 'woocommerce_order_status_cancelled_to_on-hold_renewal_notification', array( $this, 'trigger' ) );
// We want all the parent's methods, with none of its properties, so call its parent's constructor, rather than my parent constructor
WC_Email::__construct();
diff --git a/includes/emails/class-wcs-email-processing-renewal-order.php b/includes/emails/class-wcs-email-processing-renewal-order.php
index 108d2f1..0a4690a 100755
--- a/includes/emails/class-wcs-email-processing-renewal-order.php
+++ b/includes/emails/class-wcs-email-processing-renewal-order.php
@@ -34,7 +34,9 @@ class WCS_Email_Processing_Renewal_Order extends WC_Email_Customer_Processing_Or
// Triggers for this email
add_action( 'woocommerce_order_status_pending_to_processing_renewal_notification', array( $this, 'trigger' ) );
- add_action( 'woocommerce_order_status_pending_to_on-hold_renewal_notification', array( $this, 'trigger' ) );
+ add_action( 'woocommerce_order_status_cancelled_to_processing_renewal_notification', array( $this, 'trigger' ) );
+ add_action( 'woocommerce_order_status_failed_to_processing_renewal_notification', array( $this, 'trigger' ) );
+ add_action( 'woocommerce_order_status_on-hold_to_processing_renewal_notification', array( $this, 'trigger' ) );
// We want all the parent's methods, with none of its properties, so call its parent's constructor
WC_Email::__construct();
diff --git a/includes/libraries/action-scheduler/action-scheduler.php b/includes/libraries/action-scheduler/action-scheduler.php
index 8c3117d..4ffb266 100755
--- a/includes/libraries/action-scheduler/action-scheduler.php
+++ b/includes/libraries/action-scheduler/action-scheduler.php
@@ -3,12 +3,12 @@
* Plugin Name: Action Scheduler
* Plugin URI: https://actionscheduler.org
* Description: A robust scheduling library for use in WordPress plugins.
- * Author: Prospress
- * Author URI: http://prospress.com/
- * Version: 2.2.4
+ * Author: Automattic
+ * Author URI: https://automattic.com/
+ * Version: 3.0.1
* License: GPLv3
*
- * Copyright 2019 Prospress, Inc. (email : freedoms@prospress.com)
+ * 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
@@ -21,27 +21,33 @@
* 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
.
+ * along with this program. If not, see
.
*
*/
-if ( ! function_exists( 'action_scheduler_register_2_dot_2_dot_4' ) ) {
+if ( ! function_exists( 'action_scheduler_register_3_dot_0_dot_1' ) ) {
if ( ! class_exists( 'ActionScheduler_Versions' ) ) {
require_once( 'classes/ActionScheduler_Versions.php' );
add_action( 'plugins_loaded', array( 'ActionScheduler_Versions', 'initialize_latest_version' ), 1, 0 );
}
- add_action( 'plugins_loaded', 'action_scheduler_register_2_dot_2_dot_4', 0, 0 );
+ add_action( 'plugins_loaded', 'action_scheduler_register_3_dot_0_dot_1', 0, 0 );
- function action_scheduler_register_2_dot_2_dot_4() {
+ function action_scheduler_register_3_dot_0_dot_1() {
$versions = ActionScheduler_Versions::instance();
- $versions->register( '2.2.4', 'action_scheduler_initialize_2_dot_2_dot_4' );
+ $versions->register( '3.0.1', 'action_scheduler_initialize_3_dot_0_dot_1' );
}
- function action_scheduler_initialize_2_dot_2_dot_4() {
- require_once( 'classes/ActionScheduler.php' );
+ function action_scheduler_initialize_3_dot_0_dot_1() {
+ 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_register_3_dot_0_dot_1();
+ do_action( 'action_scheduler_pre_theme_init' );
+ ActionScheduler_Versions::initialize_latest_version();
+ }
}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler.php b/includes/libraries/action-scheduler/classes/ActionScheduler.php
deleted file mode 100755
index 2c5d031..0000000
--- a/includes/libraries/action-scheduler/classes/ActionScheduler.php
+++ /dev/null
@@ -1,133 +0,0 @@
-get_date() );
+ }
break;
default :
$action_class = 'ActionScheduler_FinishedAction';
@@ -44,6 +47,28 @@ class ActionScheduler_ActionFactory {
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 string 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
@@ -60,6 +85,8 @@ class ActionScheduler_ActionFactory {
}
/**
+ * 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
@@ -78,27 +105,68 @@ class ActionScheduler_ActionFactory {
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 $first Unix timestamp for the first run
+ * @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 string The ID of the stored action
*/
- public function cron( $hook, $args = array(), $first = null, $schedule = null, $group = '' ) {
+ public function cron( $hook, $args = array(), $base_timestamp = null, $schedule = null, $group = '' ) {
if ( empty($schedule) ) {
- return $this->single( $hook, $args, $first, $group );
+ return $this->single( $hook, $args, $base_timestamp, $group );
}
- $date = as_get_datetime_object( $first );
+ $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
*
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_AdminView.php b/includes/libraries/action-scheduler/classes/ActionScheduler_AdminView.php
index d87861e..b46ddc2 100755
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_AdminView.php
+++ b/includes/libraries/action-scheduler/classes/ActionScheduler_AdminView.php
@@ -8,8 +8,10 @@ class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {
private static $admin_view = NULL;
+ private static $screen_id = 'tools_page_action-scheduler';
+
/**
- * @return ActionScheduler_QueueRunner
+ * @return ActionScheduler_AdminView
* @codeCoverageIgnore
*/
public static function instance() {
@@ -35,6 +37,8 @@ class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {
}
add_action( 'admin_menu', array( $this, 'register_menu' ) );
+
+ add_action( 'current_screen', array( $this, 'add_help_tabs' ) );
}
}
@@ -63,7 +67,7 @@ class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {
* System Status page, and for sites where WooCommerce isn't active.
*/
public function register_menu() {
- add_submenu_page(
+ $hook_suffix = add_submenu_page(
'tools.php',
__( 'Scheduled Actions', 'action-scheduler' ),
__( 'Scheduled Actions', 'action-scheduler' ),
@@ -71,6 +75,15 @@ class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {
'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() {
+ $table = new ActionScheduler_ListTable( ActionScheduler::store(), ActionScheduler::logger(), ActionScheduler::runner() );
+ $table->process_actions();
}
/**
@@ -80,4 +93,45 @@ class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {
$table = new ActionScheduler_ListTable( ActionScheduler::store(), ActionScheduler::logger(), ActionScheduler::runner() );
$table->display_page();
}
+
+ /**
+ * 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;
+ }
+
+ $screen->add_help_tab(
+ array(
+ 'id' => 'action_scheduler_about',
+ 'title' => __( 'About', 'action-scheduler' ),
+ 'content' =>
+ '
' . __( 'About Action Scheduler', 'action-scheduler' ) . ' ' .
+ '
' .
+ __( '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' ) .
+ '
',
+ )
+ );
+
+ $screen->add_help_tab(
+ array(
+ 'id' => 'action_scheduler_columns',
+ 'title' => __( 'Columns', 'action-scheduler' ),
+ 'content' =>
+ '
' . __( 'Scheduled Action Columns', 'action-scheduler' ) . ' ' .
+ '
' .
+ sprintf( '%1$s : %2$s ', __( 'Hook', 'action-scheduler' ), __( 'Name of the action hook that will be triggered.', 'action-scheduler' ) ) .
+ sprintf( '%1$s : %2$s ', __( 'Status', 'action-scheduler' ), __( 'Action statuses are Pending, Complete, Canceled, Failed', 'action-scheduler' ) ) .
+ sprintf( '%1$s : %2$s ', __( 'Arguments', 'action-scheduler' ), __( 'Optional data array passed to the action hook.', 'action-scheduler' ) ) .
+ sprintf( '%1$s : %2$s ', __( 'Group', 'action-scheduler' ), __( 'Optional action group.', 'action-scheduler' ) ) .
+ sprintf( '%1$s : %2$s ', __( 'Recurrence', 'action-scheduler' ), __( 'The action\'s schedule frequency.', 'action-scheduler' ) ) .
+ sprintf( '%1$s : %2$s ', __( 'Scheduled', 'action-scheduler' ), __( 'The date/time the action is/was scheduled to run.', 'action-scheduler' ) ) .
+ sprintf( '%1$s : %2$s ', __( 'Log', 'action-scheduler' ), __( 'Activity log for the action.', 'action-scheduler' ) ) .
+ ' ',
+ )
+ );
+ }
}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_AsyncRequest_QueueRunner.php b/includes/libraries/action-scheduler/classes/ActionScheduler_AsyncRequest_QueueRunner.php
new file mode 100755
index 0000000..c1ab036
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/ActionScheduler_AsyncRequest_QueueRunner.php
@@ -0,0 +1,96 @@
+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();
+ }
+
+ /**
+ * 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', 1, $this );
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_CronSchedule.php b/includes/libraries/action-scheduler/classes/ActionScheduler_CronSchedule.php
deleted file mode 100755
index 0441e40..0000000
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_CronSchedule.php
+++ /dev/null
@@ -1,57 +0,0 @@
-start = $start;
- $this->cron = $cron;
- }
-
- /**
- * @param DateTime $after
- * @return DateTime|null
- */
- public function next( DateTime $after = NULL ) {
- $after = empty($after) ? clone $this->start : clone $after;
- return $this->cron->getNextRunDate($after, 0, false);
- }
-
- /**
- * @return bool
- */
- public function is_recurring() {
- return true;
- }
-
- /**
- * @return string
- */
- public function get_recurrence() {
- return strval($this->cron);
- }
-
- /**
- * For PHP 5.2 compat, since DateTime objects can't be serialized
- * @return array
- */
- public function __sleep() {
- $this->start_timestamp = $this->start->getTimestamp();
- return array(
- 'start_timestamp',
- 'cron'
- );
- }
-
- public function __wakeup() {
- $this->start = as_get_datetime_object($this->start_timestamp);
- }
-}
-
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_DataController.php b/includes/libraries/action-scheduler/classes/ActionScheduler_DataController.php
new file mode 100755
index 0000000..d2c889b
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/ActionScheduler_DataController.php
@@ -0,0 +1,177 @@
+=' );
+ 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 );
+ }
+
+ /**
+ * 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 = $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 = $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 );
+ } 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;
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_Exception.php b/includes/libraries/action-scheduler/classes/ActionScheduler_Exception.php
index 9ec713f..353d3c0 100755
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_Exception.php
+++ b/includes/libraries/action-scheduler/classes/ActionScheduler_Exception.php
@@ -5,7 +5,7 @@
*
* Facilitates catching Exceptions unique to Action Scheduler.
*
- * @package Prospress\ActionScheduler
+ * @package ActionScheduler
* @since %VERSION%
*/
interface ActionScheduler_Exception {}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_IntervalSchedule.php b/includes/libraries/action-scheduler/classes/ActionScheduler_IntervalSchedule.php
deleted file mode 100755
index 604ad61..0000000
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_IntervalSchedule.php
+++ /dev/null
@@ -1,60 +0,0 @@
-start = $start;
- $this->interval_in_seconds = (int)$interval;
- }
-
- /**
- * @param DateTime $after
- *
- * @return DateTime|null
- */
- public function next( DateTime $after = NULL ) {
- $after = empty($after) ? as_get_datetime_object('@0') : clone $after;
- if ( $after > $this->start ) {
- $after->modify('+'.$this->interval_in_seconds.' seconds');
- return $after;
- }
- return clone $this->start;
- }
-
- /**
- * @return bool
- */
- public function is_recurring() {
- return true;
- }
-
- /**
- * @return int
- */
- public function interval_in_seconds() {
- return $this->interval_in_seconds;
- }
-
- /**
- * For PHP 5.2 compat, since DateTime objects can't be serialized
- * @return array
- */
- public function __sleep() {
- $this->start_timestamp = $this->start->getTimestamp();
- return array(
- 'start_timestamp',
- 'interval_in_seconds'
- );
- }
-
- public function __wakeup() {
- $this->start = as_get_datetime_object($this->start_timestamp);
- }
-}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_InvalidActionException.php b/includes/libraries/action-scheduler/classes/ActionScheduler_InvalidActionException.php
index a7decdc..40b4559 100755
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_InvalidActionException.php
+++ b/includes/libraries/action-scheduler/classes/ActionScheduler_InvalidActionException.php
@@ -5,10 +5,27 @@
*
* Used for identifying actions that are invalid in some way.
*
- * @package Prospress\ActionScheduler
+ * @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.
*
@@ -17,10 +34,12 @@ class ActionScheduler_InvalidActionException extends \InvalidArgumentException i
* @param string $action_id The action ID with bad args.
* @return static
*/
- public static function from_decoding_args( $action_id ) {
+ public static function from_decoding_args( $action_id, $args = array() ) {
$message = sprintf(
- __( 'Action [%s] has invalid arguments. It cannot be JSON decoded to an array.', 'action-scheduler' ),
- $action_id
+ /* 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 );
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_ListTable.php b/includes/libraries/action-scheduler/classes/ActionScheduler_ListTable.php
index 95f97d6..6d1ea4f 100755
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_ListTable.php
+++ b/includes/libraries/action-scheduler/classes/ActionScheduler_ListTable.php
@@ -140,30 +140,37 @@ class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
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' ),
),
);
@@ -221,14 +228,15 @@ class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
* @return string
*/
protected function get_recurrence( $action ) {
- $recurrence = $action->get_schedule();
- if ( $recurrence->is_recurring() ) {
- if ( method_exists( $recurrence, 'interval_in_seconds' ) ) {
- return sprintf( __( 'Every %s', 'action-scheduler' ), self::human_interval( $recurrence->interval_in_seconds() ) );
- }
+ $schedule = $action->get_schedule();
+ if ( $schedule->is_recurring() ) {
+ $recurrence = $schedule->get_recurrence();
- if ( method_exists( $recurrence, 'get_recurrence' ) ) {
- return sprintf( __( 'Cron %s', 'action-scheduler' ), $recurrence->get_recurrence() );
+ if ( is_numeric( $recurrence ) ) {
+ /* translators: %s: time interval */
+ return sprintf( __( 'Every %s', 'action-scheduler' ), self::human_interval( $recurrence ) );
+ } else {
+ return $recurrence;
}
}
@@ -315,10 +323,32 @@ class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
*/
public function display_admin_notices() {
- if ( $this->store->get_claim_count() >= $this->runner->get_allowed_concurrent_batches() ) {
+ if ( $this->runner->has_maximum_concurrent_batches() ) {
$this->admin_notices[] = array(
'class' => 'updated',
- 'message' => sprintf( __( 'Maximum simultaneous batches already in progress (%s queues). No actions will be processed until the current batches are complete.', 'action-scheduler' ), $this->store->get_claim_count() ),
+ 'message' => sprintf(
+ /* translators: %s: amount of claims */
+ __( 'Maximum simultaneous queues already in progress (%s queues). No additional queues will begin processing until the current queues are complete.', 'action-scheduler' ),
+ $this->store->get_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.
View actions in-progress » ', '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,
);
}
@@ -333,18 +363,22 @@ class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
$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';
- $action_message_html = sprintf( __( 'Could not process change for action: "%s" (ID: %d). Error: %s', 'action-scheduler' ), $action_hook_html, esc_html( $notification['action_id'] ), esc_html( $notification['error_message'] ) );
+ /* 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 );
@@ -379,18 +413,20 @@ class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
$schedule_display_string = '';
- if ( ! $schedule->next() ) {
- return $schedule_display_string;
+ if ( ! $schedule->get_date() ) {
+ return '0000-00-00 00:00:00';
}
- $next_timestamp = $schedule->next()->getTimestamp();
+ $next_timestamp = $schedule->get_date()->getTimestamp();
- $schedule_display_string .= $schedule->next()->format( 'Y-m-d H:i:s O' );
+ $schedule_display_string .= $schedule->get_date()->format( 'Y-m-d H:i:s O' );
$schedule_display_string .= '
';
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' ) ) );
}
@@ -442,7 +478,7 @@ class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
try {
switch ( $row_action_type ) {
case 'run' :
- $this->runner->process_action( $action_id );
+ $this->runner->process_action( $action_id, 'Admin List Table' );
break;
case 'cancel' :
$this->store->cancel_action( $action_id );
@@ -462,16 +498,6 @@ class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
* {@inheritDoc}
*/
public function prepare_items() {
- $this->process_bulk_action();
-
- $this->process_row_actions();
-
- if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
- // _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter
- wp_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
- exit;
- }
-
$this->prepare_column_headers();
$per_page = $this->get_items_per_page( $this->package . '_items_per_page', $this->items_per_page );
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_Logger.php b/includes/libraries/action-scheduler/classes/ActionScheduler_Logger.php
deleted file mode 100755
index 3da06ab..0000000
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_Logger.php
+++ /dev/null
@@ -1,98 +0,0 @@
-log( $action_id, __( 'action created', 'action-scheduler' ) );
- }
-
- public function log_canceled_action( $action_id ) {
- $this->log( $action_id, __( 'action canceled', 'action-scheduler' ) );
- }
-
- public function log_started_action( $action_id ) {
- $this->log( $action_id, __( 'action started', 'action-scheduler' ) );
- }
-
- public function log_completed_action( $action_id ) {
- $this->log( $action_id, __( 'action complete', 'action-scheduler' ) );
- }
-
- public function log_failed_action( $action_id, Exception $exception ) {
- $this->log( $action_id, sprintf( __( 'action failed: %s', 'action-scheduler' ), $exception->getMessage() ) );
- }
-
- public function log_timed_out_action( $action_id, $timeout ) {
- $this->log( $action_id, sprintf( __( 'action timed out after %s seconds', 'action-scheduler' ), $timeout ) );
- }
-
- public function log_unexpected_shutdown( $action_id, $error ) {
- if ( ! empty( $error ) ) {
- $this->log( $action_id, sprintf( __( 'unexpected shutdown: PHP Fatal error %s in %s on line %s', 'action-scheduler' ), $error['message'], $error['file'], $error['line'] ) );
- }
- }
-
- public function log_reset_action( $action_id ) {
- $this->log( $action_id, __( 'action reset', 'action_scheduler' ) );
- }
-
- public function log_ignored_action( $action_id ) {
- $this->log( $action_id, __( 'action ignored', 'action-scheduler' ) );
- }
-}
-
\ No newline at end of file
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_NullSchedule.php b/includes/libraries/action-scheduler/classes/ActionScheduler_NullSchedule.php
deleted file mode 100755
index fab1538..0000000
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_NullSchedule.php
+++ /dev/null
@@ -1,19 +0,0 @@
-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 );
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_QueueRunner.php b/includes/libraries/action-scheduler/classes/ActionScheduler_QueueRunner.php
index f1e5b83..25073c7 100755
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_QueueRunner.php
+++ b/includes/libraries/action-scheduler/classes/ActionScheduler_QueueRunner.php
@@ -8,6 +8,9 @@ class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
const WP_CRON_SCHEDULE = 'every_minute';
+ /** @var ActionScheduler_AsyncRequest_QueueRunner */
+ protected $async_request;
+
/** @var ActionScheduler_QueueRunner */
private static $runner = null;
@@ -30,8 +33,14 @@ class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
* @param ActionScheduler_FatalErrorMonitor $monitor
* @param ActionScheduler_QueueCleaner $cleaner
*/
- public function __construct( ActionScheduler_Store $store = null, ActionScheduler_FatalErrorMonitor $monitor = null, ActionScheduler_QueueCleaner $cleaner = null ) {
+ 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;
}
/**
@@ -41,24 +50,74 @@ class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
add_filter( 'cron_schedules', array( self::instance(), 'add_wp_cron_schedule' ) );
- if ( !wp_next_scheduled(self::WP_CRON_HOOK) ) {
+ $cron_context = array( 'WP Cron' );
+
+ if ( ! wp_next_scheduled( self::WP_CRON_HOOK, $cron_context ) ) {
+
+ // 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 );
+ }
+
$schedule = apply_filters( 'action_scheduler_run_schedule', self::WP_CRON_SCHEDULE );
- wp_schedule_event( time(), $schedule, self::WP_CRON_HOOK );
+ wp_schedule_event( time(), $schedule, self::WP_CRON_HOOK, $cron_context );
}
add_action( self::WP_CRON_HOOK, array( self::instance(), 'run' ) );
+
+ add_filter( 'shutdown', array( $this, 'maybe_dispatch_async_request' ) );
}
- public function run() {
+ /**
+ * 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 ( $this->store->get_claim_count() < $this->get_allowed_concurrent_batches() ) {
+ 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 );
+ $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
}
@@ -67,7 +126,18 @@ class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
return $processed_actions;
}
- protected function do_batch( $size = 100 ) {
+ /**
+ * 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;
@@ -77,7 +147,7 @@ class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $claim->get_id() ) ) ) {
break;
}
- $this->process_action( $action_id );
+ $this->process_action( $action_id, $context );
$processed_actions++;
if ( $this->batch_limits_exceeded( $processed_actions ) ) {
@@ -107,7 +177,7 @@ class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
public function add_wp_cron_schedule( $schedules ) {
$schedules['every_minute'] = array(
'interval' => 60, // in seconds
- 'display' => __( 'Every minute' ),
+ 'display' => __( 'Every minute', 'action-scheduler' ),
);
return $schedules;
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_SimpleSchedule.php b/includes/libraries/action-scheduler/classes/ActionScheduler_SimpleSchedule.php
deleted file mode 100755
index 42f789f..0000000
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_SimpleSchedule.php
+++ /dev/null
@@ -1,44 +0,0 @@
-date = clone $date;
- }
-
- /**
- * @param DateTime $after
- *
- * @return DateTime|null
- */
- public function next( DateTime $after = NULL ) {
- $after = empty($after) ? as_get_datetime_object('@0') : $after;
- return ( $after > $this->date ) ? NULL : clone $this->date;
- }
-
- /**
- * @return bool
- */
- public function is_recurring() {
- return false;
- }
-
- /**
- * For PHP 5.2 compat, since DateTime objects can't be serialized
- * @return array
- */
- public function __sleep() {
- $this->timestamp = $this->date->getTimestamp();
- return array(
- 'timestamp',
- );
- }
-
- public function __wakeup() {
- $this->date = as_get_datetime_object($this->timestamp);
- }
-}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_Store.php b/includes/libraries/action-scheduler/classes/ActionScheduler_Store.php
deleted file mode 100755
index 59ac236..0000000
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_Store.php
+++ /dev/null
@@ -1,212 +0,0 @@
-', '>=', '<', '<=', '=') ) ) {
- return $comparison_operator;
- }
- return '=';
- }
-
- /**
- * Get the time MySQL formated date/time string for an action's (next) scheduled date.
- *
- * @param ActionScheduler_Action $action
- * @param DateTime $scheduled_date (optional)
- * @return string
- */
- protected function get_scheduled_date_string( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
- $next = null === $scheduled_date ? $action->get_schedule()->next() : $scheduled_date;
- if ( ! $next ) {
- throw new InvalidArgumentException( __( 'Invalid schedule. Cannot save action.', 'action-scheduler' ) );
- }
- $next->setTimezone( new DateTimeZone( 'UTC' ) );
-
- return $next->format( 'Y-m-d H:i:s' );
- }
-
- /**
- * Get the time MySQL formated date/time string for an action's (next) scheduled date.
- *
- * @param ActionScheduler_Action $action
- * @param DateTime $scheduled_date (optional)
- * @return string
- */
- protected function get_scheduled_date_string_local( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
- $next = null === $scheduled_date ? $action->get_schedule()->next() : $scheduled_date;
- if ( ! $next ) {
- throw new InvalidArgumentException( __( 'Invalid schedule. Cannot save action.', 'action-scheduler' ) );
- }
-
- ActionScheduler_TimezoneHelper::set_local_timezone( $next );
- return $next->format( 'Y-m-d H:i:s' );
- }
-
- /**
- * @return array
- */
- public function get_status_labels() {
- return array(
- self::STATUS_COMPLETE => __( 'Complete', 'action-scheduler' ),
- self::STATUS_PENDING => __( 'Pending', 'action-scheduler' ),
- self::STATUS_RUNNING => __( 'In-progress', 'action-scheduler' ),
- self::STATUS_FAILED => __( 'Failed', 'action-scheduler' ),
- self::STATUS_CANCELED => __( 'Canceled', 'action-scheduler' ),
- );
- }
-
- public function init() {}
-
- /**
- * @return ActionScheduler_Store
- */
- public static function instance() {
- if ( empty(self::$store) ) {
- $class = apply_filters('action_scheduler_store_class', 'ActionScheduler_wpPostStore');
- self::$store = new $class();
- }
- return self::$store;
- }
-
- /**
- * 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();
- }
-}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_WPCommentCleaner.php b/includes/libraries/action-scheduler/classes/ActionScheduler_WPCommentCleaner.php
new file mode 100755
index 0000000..ceef177
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/ActionScheduler_WPCommentCleaner.php
@@ -0,0 +1,108 @@
+ Status administration screen
+ add_action( 'load-tools_page_action-scheduler', array( __CLASS__, 'print_admin_notice' ) );
+ add_action( 'load-woocommerce_page_wc-status', array( __CLASS__, 'print_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 );
+ }
+
+ /**
+ * 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
Learn more » ', 'action-scheduler' ),
+ $next_cleanup_message,
+ 'https://github.com/woocommerce/action-scheduler/issues/368'
+ );
+
+ echo '
' . wp_kses_post( $notice ) . '
';
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_wcSystemStatus.php b/includes/libraries/action-scheduler/classes/ActionScheduler_wcSystemStatus.php
index 3213d7c..1fc7541 100755
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_wcSystemStatus.php
+++ b/includes/libraries/action-scheduler/classes/ActionScheduler_wcSystemStatus.php
@@ -129,8 +129,8 @@ class ActionScheduler_wcSystemStatus {
/**
* is triggered when invoking inaccessible methods in an object context.
*
- * @param $name string
- * @param $arguments array
+ * @param string $name
+ * @param array $arguments
*
* @return mixed
* @link https://php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_WPCLI_QueueRunner.php b/includes/libraries/action-scheduler/classes/WP_CLI/ActionScheduler_WPCLI_QueueRunner.php
similarity index 79%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_WPCLI_QueueRunner.php
rename to includes/libraries/action-scheduler/classes/WP_CLI/ActionScheduler_WPCLI_QueueRunner.php
index c5689b5..c33de68 100755
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_WPCLI_QueueRunner.php
+++ b/includes/libraries/action-scheduler/classes/WP_CLI/ActionScheduler_WPCLI_QueueRunner.php
@@ -1,5 +1,7 @@
add_hooks();
// Check to make sure there aren't too many concurrent processes running.
- $claim_count = $this->store->get_claim_count();
- $too_many = $claim_count >= $this->get_allowed_concurrent_batches();
- if ( $too_many ) {
+ if ( $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 {
@@ -88,7 +88,8 @@ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRu
*/
protected function setup_progress_bar() {
$count = count( $this->actions );
- $this->progress_bar = \WP_CLI\Utils\make_progress_bar(
+ $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
);
@@ -98,9 +99,12 @@ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRu
* 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() {
+ public function run( $context = 'WP CLI' ) {
do_action( 'action_scheduler_before_process_queue' );
$this->setup_progress_bar();
foreach ( $this->actions as $action_id ) {
@@ -110,9 +114,8 @@ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRu
break;
}
- $this->process_action( $action_id );
+ $this->process_action( $action_id, $context );
$this->progress_bar->tick();
- $this->maybe_stop_the_insanity();
}
$completed = $this->progress_bar->current();
@@ -148,8 +151,8 @@ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRu
if ( null === $action ) {
$action = $this->store->fetch_action( $action_id );
}
- /* translators: %s refers to the action ID */
- WP_CLI::log( sprintf( __( 'Completed processing action %s with hook: %s', 'action-scheduler' ), $action_id, $action->get_hook() ) );
+ /* 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() ) );
}
/**
@@ -163,7 +166,7 @@ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRu
*/
public function action_failed( $action_id, $exception ) {
WP_CLI::error(
- /* translators: %1$s refers to the action ID, %2$s refers to the Exception message */
+ /* translators: 1: action ID 2: exception message */
sprintf( __( 'Error processing action %1$s: %2$s', 'action-scheduler' ), $action_id, $exception->getMessage() ),
false
);
@@ -173,35 +176,12 @@ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRu
* 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 ) {
- if ( 0 < $sleep_time ) {
- WP_CLI::warning( sprintf( 'Stopped the insanity for %d %s', $sleep_time, _n( 'second', 'seconds', $sleep_time ) ) );
- sleep( $sleep_time );
- }
+ _deprecated_function( 'ActionScheduler_WPCLI_QueueRunner::stop_the_insanity', '3.0.0', 'ActionScheduler_DataController::free_memory' );
- WP_CLI::warning( __( 'Attempting to reduce used memory...', 'action-scheduler' ) );
-
- /**
- * @var $wpdb \wpdb
- * @var $wp_object_cache \WP_Object_Cache
- */
- global $wpdb, $wp_object_cache;
-
- $wpdb->queries = array();
-
- if ( ! is_object( $wp_object_cache ) ) {
- return;
- }
-
- $wp_object_cache->group_ops = array();
- $wp_object_cache->stats = array();
- $wp_object_cache->memcache_debug = array();
- $wp_object_cache->cache = array();
-
- if ( is_callable( array( $wp_object_cache, '__remoteset' ) ) ) {
- call_user_func( array( $wp_object_cache, '__remoteset' ) ); // important
- }
+ ActionScheduler_DataController::free_memory();
}
/**
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_WPCLI_Scheduler_command.php b/includes/libraries/action-scheduler/classes/WP_CLI/ActionScheduler_WPCLI_Scheduler_command.php
similarity index 87%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_WPCLI_Scheduler_command.php
rename to includes/libraries/action-scheduler/classes/WP_CLI/ActionScheduler_WPCLI_Scheduler_command.php
index 30d0974..c27008b 100755
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_WPCLI_Scheduler_command.php
+++ b/includes/libraries/action-scheduler/classes/WP_CLI/ActionScheduler_WPCLI_Scheduler_command.php
@@ -1,7 +1,7 @@
]
* : Only run actions from the specified group. Omitting this option runs actions from all groups.
*
+ * [--free-memory-on=
]
+ * : The number of actions to process between freeing memory. 0 disables freeing memory. Default 50.
+ *
+ * [--pause=]
+ * : 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.
@@ -40,8 +48,13 @@ class ActionScheduler_WPCLI_Scheduler_command extends WP_CLI_Command {
$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', '' );
+ $sleep = \WP_CLI\Utils\get_flag_value( $assoc_args, 'pause', '' );
$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;
@@ -119,7 +132,7 @@ class ActionScheduler_WPCLI_Scheduler_command extends WP_CLI_Command {
protected function print_error( Exception $e ) {
WP_CLI::error(
sprintf(
- /* translators: %s refers to the exception error message. */
+ /* translators: %s refers to the exception error message */
__( 'There was an error running the action scheduler: %s', 'action-scheduler' ),
$e->getMessage()
)
diff --git a/includes/libraries/action-scheduler/classes/WP_CLI/Migration_Command.php b/includes/libraries/action-scheduler/classes/WP_CLI/Migration_Command.php
new file mode 100755
index 0000000..066697e
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/WP_CLI/Migration_Command.php
@@ -0,0 +1,148 @@
+ '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 );
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/WP_CLI/ProgressBar.php b/includes/libraries/action-scheduler/classes/WP_CLI/ProgressBar.php
new file mode 100755
index 0000000..c86c74e
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/WP_CLI/ProgressBar.php
@@ -0,0 +1,119 @@
+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
+ );
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler.php b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler.php
new file mode 100755
index 0000000..f009e42
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler.php
@@ -0,0 +1,269 @@
+allow_migration() ) {
+ $command = new Migration_Command();
+ $command->register();
+ }
+ }
+
+ /**
+ * 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' );
+ }
+
+ /**
+ * 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 );
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_Abstract_ListTable.php b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_ListTable.php
similarity index 94%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_Abstract_ListTable.php
rename to includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_ListTable.php
index 6af17b9..fc6520f 100755
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_Abstract_ListTable.php
+++ b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_ListTable.php
@@ -29,7 +29,7 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
protected $table_name;
/**
- * Package name, used in translations
+ * Package name, used to get options from WP_List_Table::get_items_per_page.
*/
protected $package;
@@ -104,10 +104,12 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
/**
* Makes translation easier, it basically just wraps
- * `_x` with some default (the package name)
+ * `_x` with some default (the package name).
+ *
+ * @deprecated 3.0.0
*/
protected function translate( $text, $context = '' ) {
- return _x( $text, $context, $this->package );
+ return $text;
}
/**
@@ -123,7 +125,7 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
throw new RuntimeException( "The bulk action $action does not have a callback method" );
}
- $actions[ $action ] = $this->translate( $label );
+ $actions[ $action ] = $label;
}
return $actions;
@@ -199,7 +201,7 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
public function get_columns() {
$columns = array_merge(
array( 'cb' => ' ' ),
- array_map( array( $this, 'translate' ), $this->columns )
+ $this->columns
);
return $columns;
@@ -355,7 +357,7 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
$filter = array();
foreach ( $this->search_by as $column ) {
- $filter[] = '`' . $column . '` like "%' . $wpdb->esc_like( $_GET['s'] ) . '%"';
+ $filter[] = $wpdb->prepare('`' . $column . '` like "%%s%"', $wpdb->esc_like( $_GET['s'] ));
}
return implode( ' OR ', $filter );
}
@@ -455,14 +457,14 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
foreach ( $options as $value => $label ) {
echo ''
- . esc_html( $this->translate( $label ) )
+ . esc_html( $label )
. ' ';
}
echo '';
}
- submit_button( $this->translate( 'Filter' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
+ submit_button( esc_html__( 'Filter', 'action-scheduler' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
echo ' ';
}
@@ -561,7 +563,8 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
protected function display_header() {
echo '
' . esc_attr( $this->table_header ) . ' ';
if ( $this->get_request_search_query() ) {
- echo '
' . esc_attr( $this->translate( sprintf( 'Search results for "%s"', $this->get_request_search_query() ) ) ) . ' ';
+ /* translators: %s: search query */
+ echo '
' . esc_attr( sprintf( __( 'Search results for "%s"', 'action-scheduler' ), $this->get_request_search_query() ) ) . ' ';
}
echo '';
}
@@ -633,6 +636,21 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
echo '';
}
+ /**
+ * 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.
*/
@@ -651,6 +669,6 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
* Get the text to display in the search box on the list table.
*/
protected function get_search_box_placeholder() {
- return $this->translate( 'Search' );
+ return esc_html__( 'Search', 'action-scheduler' );
}
}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_Abstract_QueueRunner.php b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_QueueRunner.php
similarity index 83%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_Abstract_QueueRunner.php
rename to includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_QueueRunner.php
index e34fb87..7cfb3df 100755
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_Abstract_QueueRunner.php
+++ b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_QueueRunner.php
@@ -44,28 +44,30 @@ abstract class ActionScheduler_Abstract_QueueRunner extends ActionScheduler_Abst
* 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 ) {
+ public function process_action( $action_id, $context = '' ) {
try {
- do_action( 'action_scheduler_before_execute', $action_id );
+ 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 );
+ do_action( 'action_scheduler_execution_ignored', $action_id, $context );
return;
}
$action = $this->store->fetch_action( $action_id );
$this->store->log_execution( $action_id );
$action->execute();
- do_action( 'action_scheduler_after_execute', $action_id, $action );
+ do_action( 'action_scheduler_after_execute', $action_id, $action, $context );
$this->store->mark_complete( $action_id );
} catch ( Exception $e ) {
$this->store->mark_failure( $action_id );
- do_action( 'action_scheduler_failed_execution', $action_id, $e );
+ do_action( 'action_scheduler_failed_execution', $action_id, $e, $context );
}
- if ( isset( $action ) && is_a( $action, 'ActionScheduler_Action' ) ) {
- $this->schedule_next_instance( $action );
+ if ( isset( $action ) && is_a( $action, 'ActionScheduler_Action' ) && $action->get_schedule()->is_recurring() ) {
+ $this->schedule_next_instance( $action, $action_id );
}
}
@@ -73,13 +75,13 @@ abstract class ActionScheduler_Abstract_QueueRunner extends ActionScheduler_Abst
* 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 ) {
- $schedule = $action->get_schedule();
- $next = $schedule->next( as_get_datetime_object() );
-
- if ( ! is_null( $next ) && $schedule->is_recurring() ) {
- $this->store->save_action( $action, $next );
+ 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 );
}
}
@@ -98,7 +100,16 @@ abstract class ActionScheduler_Abstract_QueueRunner extends ActionScheduler_Abst
* @return int
*/
public function get_allowed_concurrent_batches() {
- return apply_filters( 'action_scheduler_queue_runner_concurrent_batches', 5 );
+ 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();
}
/**
@@ -213,7 +224,9 @@ abstract class ActionScheduler_Abstract_QueueRunner extends ActionScheduler_Abst
* 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();
+ abstract public function run( $context = '' );
}
diff --git a/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_RecurringSchedule.php b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_RecurringSchedule.php
new file mode 100755
index 0000000..131d475
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_RecurringSchedule.php
@@ -0,0 +1,102 @@
+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();
+ }
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_Schedule.php b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_Schedule.php
new file mode 100755
index 0000000..2631ef5
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_Schedule.php
@@ -0,0 +1,83 @@
+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 );
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_Schema.php b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_Schema.php
new file mode 100755
index 0000000..f02c84d
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Abstract_Schema.php
@@ -0,0 +1,133 @@
+tables as $table ) {
+ $wpdb->tables[] = $table;
+ $name = $this->get_full_table_name( $table );
+ $wpdb->$table = $name;
+ }
+
+ // create the tables
+ if ( $this->schema_update_required() ) {
+ 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;
+ }
+}
\ No newline at end of file
diff --git a/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Lock.php b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Lock.php
new file mode 100755
index 0000000..86e8528
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Lock.php
@@ -0,0 +1,62 @@
+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;
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Logger.php b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Logger.php
new file mode 100755
index 0000000..f200195
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Logger.php
@@ -0,0 +1,176 @@
+hook_stored_action();
+ add_action( 'action_scheduler_canceled_action', array( $this, 'log_canceled_action' ), 10, 1 );
+ add_action( 'action_scheduler_before_execute', array( $this, 'log_started_action' ), 10, 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, __( 'action ignored', 'action-scheduler' ) );
+ }
+
+ /**
+ * @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 );
+ }
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Store.php b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Store.php
new file mode 100755
index 0000000..252b701
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_Store.php
@@ -0,0 +1,345 @@
+', '>=', '<', '<=', '=') ) ) {
+ 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,
+ * 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 ) {
+ if ( strlen( json_encode( $action->get_args() ) ) > self::$max_index_length ) {
+ throw new InvalidArgumentException( __( 'ActionScheduler_Action::$args too long. To ensure the args column can be indexed, action args should not be more than 191 characters when encoded as JSON.', 'action-scheduler' ) );
+ }
+ }
+
+ /**
+ * 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;
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_TimezoneHelper.php b/includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_TimezoneHelper.php
similarity index 100%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_TimezoneHelper.php
rename to includes/libraries/action-scheduler/classes/abstracts/ActionScheduler_TimezoneHelper.php
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_Action.php b/includes/libraries/action-scheduler/classes/actions/ActionScheduler_Action.php
similarity index 100%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_Action.php
rename to includes/libraries/action-scheduler/classes/actions/ActionScheduler_Action.php
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_CanceledAction.php b/includes/libraries/action-scheduler/classes/actions/ActionScheduler_CanceledAction.php
similarity index 86%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_CanceledAction.php
rename to includes/libraries/action-scheduler/classes/actions/ActionScheduler_CanceledAction.php
index b1db531..8bbc5d1 100755
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_CanceledAction.php
+++ b/includes/libraries/action-scheduler/classes/actions/ActionScheduler_CanceledAction.php
@@ -16,6 +16,8 @@ class ActionScheduler_CanceledAction extends ActionScheduler_FinishedAction {
*/
public function __construct( $hook, array $args = array(), ActionScheduler_Schedule $schedule = null, $group = '' ) {
parent::__construct( $hook, $args, $schedule, $group );
- $this->set_schedule( new ActionScheduler_NullSchedule() );
+ if ( is_null( $schedule ) ) {
+ $this->set_schedule( new ActionScheduler_NullSchedule() );
+ }
}
}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_FinishedAction.php b/includes/libraries/action-scheduler/classes/actions/ActionScheduler_FinishedAction.php
similarity index 100%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_FinishedAction.php
rename to includes/libraries/action-scheduler/classes/actions/ActionScheduler_FinishedAction.php
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_NullAction.php b/includes/libraries/action-scheduler/classes/actions/ActionScheduler_NullAction.php
similarity index 100%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_NullAction.php
rename to includes/libraries/action-scheduler/classes/actions/ActionScheduler_NullAction.php
diff --git a/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_DBLogger.php b/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_DBLogger.php
new file mode 100755
index 0000000..d21e869
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_DBLogger.php
@@ -0,0 +1,146 @@
+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 );
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_DBStore.php b/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_DBStore.php
new file mode 100755
index 0000000..2fd1ae7
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_DBStore.php
@@ -0,0 +1,803 @@
+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 ),
+ 'args' => json_encode( $action->get_args() ),
+ 'schedule' => serialize( $action->get_schedule() ),
+ 'group_id' => $this->get_group_id( $action->get_group() ),
+ ];
+ $wpdb->insert( $wpdb->actionscheduler_actions, $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 );
+ }
+ }
+
+ /**
+ * 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();
+ }
+
+ 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[] = json_encode( $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[] = json_encode( $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.args LIKE %s";
+ for( $i = 0; $i < 2; $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 ) {
+ switch ( $query['orderby'] ) {
+ case 'hook':
+ $orderby = 'a.hook';
+ break;
+ case 'group':
+ $orderby = 'g.slug';
+ break;
+ case 'modified':
+ $orderby = 'a.last_attempt_gmt';
+ break;
+ case 'date':
+ default:
+ $orderby = 'a.scheduled_date_gmt';
+ break;
+ }
+ if ( strtoupper( $query[ 'order' ] ) == 'ASC' ) {
+ $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' ];
+ }
+ }
+
+ 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_actions( $claim_id, $max_actions, $before_date, $hooks, $group );
+ $action_ids = $this->find_actions_by_claim_id( $claim_id );
+
+ return new ActionScheduler_ActionClaim( $claim_id, $action_ids );
+ }
+
+ /**
+ * 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.
+ *
+ * @param string $claim_id Claim ID.
+ *
+ * @return int[]
+ */
+ public function find_actions_by_claim_id( $claim_id ) {
+ /** @var \wpdb $wpdb */
+ global $wpdb;
+
+ $sql = "SELECT action_id FROM {$wpdb->actionscheduler_actions} WHERE claim_id=%d";
+ $sql = $wpdb->prepare( $sql, $claim_id );
+
+ $action_ids = $wpdb->get_col( $sql );
+
+ return array_map( 'intval', $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;
+ }
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_HybridStore.php b/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_HybridStore.php
new file mode 100755
index 0000000..bf68af3
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_HybridStore.php
@@ -0,0 +1,380 @@
+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;
+ $wpdb->insert(
+ $wpdb->{ActionScheduler_StoreSchema::ACTIONS_TABLE},
+ [
+ 'action_id' => $this->demarkation_id,
+ 'hook' => '',
+ 'status' => '',
+ ]
+ );
+ $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.
+ */
+ 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 ) {
+ if ( $action_id < $this->demarkation_id ) {
+ return $this->secondary_store->fetch_action( $action_id );
+ } else {
+ return $this->primary_store->fetch_action( $action_id );
+ }
+ }
+
+ /**
+ * Cancel an existing action whether migrated or not.
+ *
+ * @param int $action_id Action ID.
+ */
+ public function cancel_action( $action_id ) {
+ if ( $action_id < $this->demarkation_id ) {
+ $this->secondary_store->cancel_action( $action_id );
+ } else {
+ $this->primary_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 ) {
+ if ( $action_id < $this->demarkation_id ) {
+ $this->secondary_store->delete_action( $action_id );
+ } else {
+ $this->primary_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 ) {
+ if ( $action_id < $this->demarkation_id ) {
+ return $this->secondary_store->get_date( $action_id );
+ } else {
+ return $this->primary_store->get_date( $action_id );
+ }
+ }
+
+ /**
+ * Mark an existing action as failed whether migrated or not.
+ *
+ * @param int $action_id Action ID.
+ */
+ public function mark_failure( $action_id ) {
+ if ( $action_id < $this->demarkation_id ) {
+ $this->secondary_store->mark_failure( $action_id );
+ } else {
+ $this->primary_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 ) {
+ if ( $action_id < $this->demarkation_id ) {
+ $this->secondary_store->log_execution( $action_id );
+ } else {
+ $this->primary_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 ) {
+ if ( $action_id < $this->demarkation_id ) {
+ $this->secondary_store->mark_complete( $action_id );
+ } else {
+ $this->primary_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 ) {
+ if ( $action_id < $this->demarkation_id ) {
+ return $this->secondary_store->get_status( $action_id );
+ } else {
+ return $this->primary_store->get_status( $action_id );
+ }
+ }
+
+
+ /* * * * * * * * * * * * * * * * * * * * * * * * * * *
+ * 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 );
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_wpCommentLogger.php b/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_wpCommentLogger.php
similarity index 100%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_wpCommentLogger.php
rename to includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_wpCommentLogger.php
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_wpPostStore.php b/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore.php
similarity index 90%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_wpPostStore.php
rename to includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore.php
index 59ee651..807ec10 100755
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_wpPostStore.php
+++ b/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore.php
@@ -7,13 +7,11 @@ 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';
/** @var DateTimeZone */
protected $local_timezone = NULL;
- /** @var int */
- private static $max_index_length = 191;
-
public function save_action( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ){
try {
$this->validate_action( $action );
@@ -43,7 +41,20 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
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 );
@@ -81,7 +92,7 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
* action's slug, being probably unique is good enough.
*
* For more backstory on this issue, see:
- * - https://github.com/Prospress/action-scheduler/issues/44 and
+ * - https://github.com/woocommerce/action-scheduler/issues/44 and
* - https://core.trac.wordpress.org/ticket/21112
*
* @param string $override_slug Short-circuit return value.
@@ -115,7 +126,15 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
if ( empty($post) || $post->post_type != self::POST_TYPE ) {
return $this->get_null_action();
}
- return $this->make_action_from_post($post);
+
+ 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 ) {
@@ -131,13 +150,13 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
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 );
- if ( empty( $schedule ) || ! is_a( $schedule, 'ActionScheduler_Schedule' ) ) {
- $schedule = new ActionScheduler_NullSchedule();
- }
+ $this->validate_schedule( $schedule, $post->ID );
+
$group = wp_get_object_terms( $post->ID, self::GROUP_TAXONOMY, array('fields' => 'names') );
$group = empty( $group ) ? '' : reset($group);
@@ -286,15 +305,16 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
$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'] ) {
+ 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";
-
- if ( ! empty( $query['group'] ) ) {
- $sql .= " AND t.slug=%s";
- $sql_params[] = $query['group'];
- }
+ $sql .= " AND t.slug=%s";
+ $sql_params[] = $query['group'];
}
$sql .= " WHERE post_type=%s";
$sql_params[] = self::POST_TYPE;
@@ -448,7 +468,8 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
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);
+
+ wp_delete_post( $action_id, TRUE );
}
/**
@@ -664,6 +685,7 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
$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() ) );
}
}
@@ -678,6 +700,7 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
$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 ) );
}
}
@@ -689,6 +712,7 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
$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 ) );
}
}
@@ -737,7 +761,12 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
$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) ) {
@@ -756,6 +785,43 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
}
}
+ /**
+ * 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 ) ) {
+ $found_action = $wpdb->get_var(
+ $wpdb->prepare(
+ "SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND CHAR_LENGTH(post_content) > 191 LIMIT 1",
+ 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.
*
@@ -766,8 +832,11 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
* @param ActionScheduler_Action $action
*/
protected function validate_action( ActionScheduler_Action $action ) {
- if ( strlen( json_encode( $action->get_args() ) ) > self::$max_index_length ) {
- _doing_it_wrong( 'ActionScheduler_Action::$args', sprintf( 'To ensure the action args column can be indexed, action args should not be more than %d characters when encoded as JSON. Support for strings longer than this will be removed in a future version.', self::$max_index_length ), '2.1.0' );
+ 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' );
}
}
@@ -775,6 +844,8 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
* @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();
@@ -784,24 +855,4 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
$taxonomy_registrar = new ActionScheduler_wpPostStore_TaxonomyRegistrar();
$taxonomy_registrar->register();
}
-
- /**
- * 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.
- */
- private 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 );
- }
- }
}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_wpPostStore_PostStatusRegistrar.php b/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore_PostStatusRegistrar.php
similarity index 80%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_wpPostStore_PostStatusRegistrar.php
rename to includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore_PostStatusRegistrar.php
index a85b154..246bc34 100755
--- a/includes/libraries/action-scheduler/classes/ActionScheduler_wpPostStore_PostStatusRegistrar.php
+++ b/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore_PostStatusRegistrar.php
@@ -33,8 +33,9 @@ class ActionScheduler_wpPostStore_PostStatusRegistrar {
*/
protected function post_status_failed_labels() {
$labels = array(
- 'label' => _x( 'Failed', 'post' ),
- 'label_count' => _n_noop( 'Failed
(%s) ', 'Failed
(%s) ' ),
+ 'label' => _x( 'Failed', 'post', 'action-scheduler' ),
+ /* translators: %s: count */
+ 'label_count' => _n_noop( 'Failed
(%s) ', 'Failed
(%s) ', 'action-scheduler' ),
);
return apply_filters( 'action_scheduler_post_status_failed_labels', $labels );
@@ -47,11 +48,11 @@ class ActionScheduler_wpPostStore_PostStatusRegistrar {
*/
protected function post_status_running_labels() {
$labels = array(
- 'label' => _x( 'In-Progress', 'post' ),
- 'label_count' => _n_noop( 'In-Progress
(%s) ', 'In-Progress
(%s) ' ),
+ 'label' => _x( 'In-Progress', 'post', 'action-scheduler' ),
+ /* translators: %s: count */
+ 'label_count' => _n_noop( 'In-Progress
(%s) ', 'In-Progress
(%s) ', 'action-scheduler' ),
);
return apply_filters( 'action_scheduler_post_status_running_labels', $labels );
}
}
-
\ No newline at end of file
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_wpPostStore_PostTypeRegistrar.php b/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore_PostTypeRegistrar.php
similarity index 100%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_wpPostStore_PostTypeRegistrar.php
rename to includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore_PostTypeRegistrar.php
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_wpPostStore_TaxonomyRegistrar.php b/includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore_TaxonomyRegistrar.php
similarity index 100%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_wpPostStore_TaxonomyRegistrar.php
rename to includes/libraries/action-scheduler/classes/data-stores/ActionScheduler_wpPostStore_TaxonomyRegistrar.php
diff --git a/includes/libraries/action-scheduler/classes/migration/ActionMigrator.php b/includes/libraries/action-scheduler/classes/migration/ActionMigrator.php
new file mode 100755
index 0000000..c77d083
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/migration/ActionMigrator.php
@@ -0,0 +1,109 @@
+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;
+ }
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/migration/ActionScheduler_DBStoreMigrator.php b/includes/libraries/action-scheduler/classes/migration/ActionScheduler_DBStoreMigrator.php
new file mode 100755
index 0000000..41c21da
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/migration/ActionScheduler_DBStoreMigrator.php
@@ -0,0 +1,47 @@
+ $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 );
+ }
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/migration/BatchFetcher.php b/includes/libraries/action-scheduler/classes/migration/BatchFetcher.php
new file mode 100755
index 0000000..4872801
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/migration/BatchFetcher.php
@@ -0,0 +1,86 @@
+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 );
+ }
+ }
+}
\ No newline at end of file
diff --git a/includes/libraries/action-scheduler/classes/migration/Config.php b/includes/libraries/action-scheduler/classes/migration/Config.php
new file mode 100755
index 0000000..50f41ff
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/migration/Config.php
@@ -0,0 +1,168 @@
+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;
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/migration/Controller.php b/includes/libraries/action-scheduler/classes/migration/Controller.php
new file mode 100755
index 0000000..39b5a4a
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/migration/Controller.php
@@ -0,0 +1,206 @@
+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( '
', __( '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( 'shutdown', array( $this, 'schedule_migration' ), 0, 0 );
+
+ // 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;
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/migration/DryRun_ActionMigrator.php b/includes/libraries/action-scheduler/classes/migration/DryRun_ActionMigrator.php
new file mode 100755
index 0000000..ffc21c2
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/migration/DryRun_ActionMigrator.php
@@ -0,0 +1,28 @@
+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() );
+ }
+ }
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/migration/Runner.php b/includes/libraries/action-scheduler/classes/migration/Runner.php
new file mode 100755
index 0000000..867c5de
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/migration/Runner.php
@@ -0,0 +1,136 @@
+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();
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/migration/Scheduler.php b/includes/libraries/action-scheduler/classes/migration/Scheduler.php
new file mode 100755
index 0000000..da3e5b8
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/migration/Scheduler.php
@@ -0,0 +1,128 @@
+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();
+ }
+
+ 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 );
+ }
+
+}
diff --git a/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_CanceledSchedule.php b/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_CanceledSchedule.php
new file mode 100755
index 0000000..840e482
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_CanceledSchedule.php
@@ -0,0 +1,57 @@
+__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();
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_CronSchedule.php b/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_CronSchedule.php
new file mode 100755
index 0000000..7859307
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_CronSchedule.php
@@ -0,0 +1,102 @@
+__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();
+ }
+}
+
diff --git a/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_IntervalSchedule.php b/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_IntervalSchedule.php
new file mode 100755
index 0000000..11a591e
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_IntervalSchedule.php
@@ -0,0 +1,81 @@
+__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();
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_NullSchedule.php b/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_NullSchedule.php
new file mode 100755
index 0000000..0ca9f7c
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_NullSchedule.php
@@ -0,0 +1,28 @@
+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;
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/ActionScheduler_Schedule.php b/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_Schedule.php
similarity index 100%
rename from includes/libraries/action-scheduler/classes/ActionScheduler_Schedule.php
rename to includes/libraries/action-scheduler/classes/schedules/ActionScheduler_Schedule.php
diff --git a/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_SimpleSchedule.php b/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_SimpleSchedule.php
new file mode 100755
index 0000000..454174c
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/schedules/ActionScheduler_SimpleSchedule.php
@@ -0,0 +1,71 @@
+__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();
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/schema/ActionScheduler_LoggerSchema.php b/includes/libraries/action-scheduler/classes/schema/ActionScheduler_LoggerSchema.php
new file mode 100755
index 0000000..d19ae3f
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/schema/ActionScheduler_LoggerSchema.php
@@ -0,0 +1,48 @@
+tables = [
+ self::LOG_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::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 '';
+ }
+ }
+}
diff --git a/includes/libraries/action-scheduler/classes/schema/ActionScheduler_StoreSchema.php b/includes/libraries/action-scheduler/classes/schema/ActionScheduler_StoreSchema.php
new file mode 100755
index 0000000..b4a47f7
--- /dev/null
+++ b/includes/libraries/action-scheduler/classes/schema/ActionScheduler_StoreSchema.php
@@ -0,0 +1,82 @@
+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',
+ 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 '';
+ }
+ }
+}
diff --git a/includes/libraries/action-scheduler/deprecated/ActionScheduler_Schedule_Deprecated.php b/includes/libraries/action-scheduler/deprecated/ActionScheduler_Schedule_Deprecated.php
new file mode 100755
index 0000000..9873a5f
--- /dev/null
+++ b/includes/libraries/action-scheduler/deprecated/ActionScheduler_Schedule_Deprecated.php
@@ -0,0 +1,29 @@
+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;
+ }
+}
diff --git a/includes/libraries/action-scheduler/deprecated/ActionScheduler_Store_Deprecated.php b/includes/libraries/action-scheduler/deprecated/ActionScheduler_Store_Deprecated.php
new file mode 100755
index 0000000..002dc75
--- /dev/null
+++ b/includes/libraries/action-scheduler/deprecated/ActionScheduler_Store_Deprecated.php
@@ -0,0 +1,49 @@
+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();
+ }
+}
diff --git a/includes/libraries/action-scheduler/functions.php b/includes/libraries/action-scheduler/functions.php
index 2f27d7e..19bfdb9 100755
--- a/includes/libraries/action-scheduler/functions.php
+++ b/includes/libraries/action-scheduler/functions.php
@@ -4,6 +4,18 @@
* General API functions for scheduling actions
*/
+/**
+ * Enqueue an action to run one time, as soon as possible
+ *
+ * @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 action ID.
+ */
+function as_enqueue_async_action( $hook, $args = array(), $group = '' ) {
+ return ActionScheduler::factory()->async( $hook, $args, $group );
+}
+
/**
* Schedule an action to run one time
*
@@ -36,7 +48,9 @@ function as_schedule_recurring_action( $timestamp, $interval_in_seconds, $hook,
/**
* Schedule an action that recurs on a cron-like schedule.
*
- * @param int $timestamp The schedule will start on or after this time
+ * @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 string $schedule A cron-link schedule string
* @see http://en.wikipedia.org/wiki/Cron
* * * * * * *
@@ -99,17 +113,35 @@ function as_unschedule_action( $hook, $args = array(), $group = '' ) {
* @param string $group
*/
function as_unschedule_all_actions( $hook, $args = array(), $group = '' ) {
+ if ( empty( $args ) ) {
+ if ( ! empty( $hook ) && empty( $group ) ) {
+ ActionScheduler_Store::instance()->cancel_actions_by_hook( $hook );
+ return;
+ }
+ if ( ! empty( $group ) && empty( $hook ) ) {
+ ActionScheduler_Store::instance()->cancel_actions_by_group( $group );
+ return;
+ }
+ }
do {
$unscheduled_action = as_unschedule_action( $hook, $args, $group );
} while ( ! empty( $unscheduled_action ) );
}
/**
+ * Check if there is an existing action in the queue with a given hook, args and group combination.
+ *
+ * An action in the queue could be pending, in-progress or aysnc. If the is pending for a time in
+ * future, its scheduled date will be returned as a timestamp. If it is currently being run, or an
+ * async action sitting in the queue waiting to be processed, in which case boolean true will be
+ * returned. Or there may be no async, in-progress or pending action for this hook, in which case,
+ * boolean false will be the return value.
+ *
* @param string $hook
* @param array $args
* @param string $group
*
- * @return int|bool The timestamp for the next occurrence, or false if nothing was found
+ * @return int|bool The timestamp for the next occurrence of a pending scheduled action, true for an async or in-progress action or false if there is no matching action.
*/
function as_next_scheduled_action( $hook, $args = NULL, $group = '' ) {
$params = array();
@@ -119,14 +151,24 @@ function as_next_scheduled_action( $hook, $args = NULL, $group = '' ) {
if ( !empty($group) ) {
$params['group'] = $group;
}
+
+ $params['status'] = ActionScheduler_Store::STATUS_RUNNING;
+ $job_id = ActionScheduler::store()->find_action( $hook, $params );
+ if ( ! empty( $job_id ) ) {
+ return true;
+ }
+
+ $params['status'] = ActionScheduler_Store::STATUS_PENDING;
$job_id = ActionScheduler::store()->find_action( $hook, $params );
if ( empty($job_id) ) {
return false;
}
$job = ActionScheduler::store()->fetch_action( $job_id );
- $next = $job->get_schedule()->next();
- if ( $next ) {
- return (int)($next->format('U'));
+ $scheduled_date = $job->get_schedule()->get_date();
+ if ( $scheduled_date ) {
+ return (int) $scheduled_date->format( 'U' );
+ } elseif ( NULL === $scheduled_date ) { // pending async action with NullSchedule
+ return true;
}
return false;
}
diff --git a/includes/libraries/action-scheduler/lib/WP_Async_Request.php b/includes/libraries/action-scheduler/lib/WP_Async_Request.php
new file mode 100755
index 0000000..d7dea1c
--- /dev/null
+++ b/includes/libraries/action-scheduler/lib/WP_Async_Request.php
@@ -0,0 +1,170 @@
+identifier = $this->prefix . '_' . $this->action;
+
+ add_action( 'wp_ajax_' . $this->identifier, array( $this, 'maybe_handle' ) );
+ add_action( 'wp_ajax_nopriv_' . $this->identifier, array( $this, 'maybe_handle' ) );
+ }
+
+ /**
+ * Set data used during the request
+ *
+ * @param array $data Data.
+ *
+ * @return $this
+ */
+ public function data( $data ) {
+ $this->data = $data;
+
+ return $this;
+ }
+
+ /**
+ * Dispatch the async request
+ *
+ * @return array|WP_Error
+ */
+ public function dispatch() {
+ $url = add_query_arg( $this->get_query_args(), $this->get_query_url() );
+ $args = $this->get_post_args();
+
+ return wp_remote_post( esc_url_raw( $url ), $args );
+ }
+
+ /**
+ * Get query args
+ *
+ * @return array
+ */
+ protected function get_query_args() {
+ if ( property_exists( $this, 'query_args' ) ) {
+ return $this->query_args;
+ }
+
+ return array(
+ 'action' => $this->identifier,
+ 'nonce' => wp_create_nonce( $this->identifier ),
+ );
+ }
+
+ /**
+ * Get query URL
+ *
+ * @return string
+ */
+ protected function get_query_url() {
+ if ( property_exists( $this, 'query_url' ) ) {
+ return $this->query_url;
+ }
+
+ return admin_url( 'admin-ajax.php' );
+ }
+
+ /**
+ * Get post args
+ *
+ * @return array
+ */
+ protected function get_post_args() {
+ if ( property_exists( $this, 'post_args' ) ) {
+ return $this->post_args;
+ }
+
+ return array(
+ 'timeout' => 0.01,
+ 'blocking' => false,
+ 'body' => $this->data,
+ 'cookies' => $_COOKIE,
+ 'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
+ );
+ }
+
+ /**
+ * Maybe handle
+ *
+ * Check for correct nonce and pass to handler.
+ */
+ public function maybe_handle() {
+ // Don't lock up other requests while processing
+ session_write_close();
+
+ check_ajax_referer( $this->identifier, 'nonce' );
+
+ $this->handle();
+
+ wp_die();
+ }
+
+ /**
+ * Handle
+ *
+ * Override this method to perform any actions required
+ * during the async request.
+ */
+ abstract protected function handle();
+
+ }
+}
diff --git a/includes/payment-retry/class-wcs-retry-database-store.php b/includes/payment-retry/class-wcs-retry-database-store.php
index 91899dc..0f9f48d 100755
--- a/includes/payment-retry/class-wcs-retry-database-store.php
+++ b/includes/payment-retry/class-wcs-retry-database-store.php
@@ -155,6 +155,13 @@ class WCS_Retry_Database_Store extends WCS_Retry_Store {
'limit' => -1,
) );
+ // Map the internal properties to the database column names.
+ if ( strtolower( $args['orderby'] ) === 'id' ) {
+ $args['orderby'] = 'retry_id';
+ } elseif ( strtolower( $args['orderby'] ) === 'date' ) {
+ $args['orderby'] = 'date_gmt';
+ }
+
$where = ' WHERE 1=1';
if ( 'any' !== $args['status'] ) {
@@ -173,7 +180,7 @@ class WCS_Retry_Database_Store extends WCS_Retry_Store {
$where .= $date_query->get_sql();
}
- $orderby = $wpdb->prepare( ' ORDER BY %s %s', $args['orderby'], $args['order'] );
+ $orderby = sprintf( ' ORDER BY %s', sanitize_sql_orderby( "{$args['orderby']} {$args['order']}" ) );
$limit = ( $args['limit'] > 0 ) ? $wpdb->prepare( ' LIMIT %d', $args['limit'] ) : '';
$raw_retries = $wpdb->get_results( "SELECT * FROM {$this->get_full_table_name()} $where $orderby $limit" );
diff --git a/includes/upgrades/class-wcs-repair-line-item-has-trial-meta.php b/includes/upgrades/class-wcs-repair-line-item-has-trial-meta.php
index 36249f9..f6a0fe7 100755
--- a/includes/upgrades/class-wcs-repair-line-item-has-trial-meta.php
+++ b/includes/upgrades/class-wcs-repair-line-item-has-trial-meta.php
@@ -11,7 +11,7 @@
* All line items on subscriptions with _trial_period meta, that were purchased in the parent order must have had a free trial because subscriptions are grouped in the cart by trial period and length.
* For more details @see https://github.com/Prospress/woocommerce-subscriptions/pull/3239
*
- * @author Automattic
+ * @author WooCommerce
* @category Admin
* @package WooCommerce Subscriptions/Admin/Upgrades
* @version 2.6.0
diff --git a/includes/upgrades/class-wcs-upgrade-notice-manager.php b/includes/upgrades/class-wcs-upgrade-notice-manager.php
index 4cf082c..c4e33a7 100755
--- a/includes/upgrades/class-wcs-upgrade-notice-manager.php
+++ b/includes/upgrades/class-wcs-upgrade-notice-manager.php
@@ -19,7 +19,7 @@ class WCS_Upgrade_Notice_Manager {
*
* @var string
*/
- protected static $version = '2.6.0';
+ protected static $version = '3.0.0';
/**
* The number of times the notice will be displayed before being dismissed automatically.
@@ -77,24 +77,19 @@ class WCS_Upgrade_Notice_Manager {
return;
}
- $version = _x( '2.6', 'plugin version number used in admin notice', 'woocommerce-subscriptions' );
+ $version = _x( '3.0', 'plugin version number used in admin notice', 'woocommerce-subscriptions' );
$dismiss_url = wp_nonce_url( add_query_arg( 'dismiss_upgrade_notice', self::$version ), 'dismiss_upgrade_notice', '_wcsnonce' );
$notice = new WCS_Admin_Notice( 'notice notice-info', array(), $dismiss_url );
$features = array(
array(
- 'title' => __( 'Improved experience for customers who renew their subscriptions early', 'woocommerce-subscriptions' ),
- 'description' => sprintf( __( 'Allow customers to renew early from their %sMy Account > Subscription%s page without going through the checkout.', 'woocommerce-subscriptions' ), '
', ' ' ),
+ 'title' => __( 'Improved scheduled action data storage', 'woocommerce-subscriptions' ),
+ 'description' => __( 'Scheduled action data, which was previously stored in the WordPress post tables, has been moved to a custom database table. Amongst other benefits, this will greatly improve the performance of processing scheduled actions such as subscription payments.', 'woocommerce-subscriptions' ),
),
array(
- 'title' => __( 'Improved subscription switching proration calculations', 'woocommerce-subscriptions' ),
- 'description' => __( "We've made improvements to the code which calculates the upgrade costs when a customer switches their subscription. This has enabled us to fix a number of complicated switching scenarios.", 'woocommerce-subscriptions' ),
- ),
- array(
- 'title' => __( 'View subscriptions and orders contributing to reports', 'woocommerce-subscriptions' ),
+ 'title' => __( 'Increased processing rate for scheduled payments', 'woocommerce-subscriptions' ),
'description' => sprintf(
- __( 'Want to view which specific orders and subscriptions are contributing to subscription-related reports? You can now do just that by clicking on the %1$s link while viewing %2$ssubscription reports%3$s.', 'woocommerce-subscriptions' ),
- '
',
- '
', ' '
+ __( 'Previous versions of Subscriptions relied on %sWP Cron%s to process subscription payments and other scheduled events. In 3.0, these events will now run on admin request with loopback support. This will significantly increase the throughput of payment processing.', 'woocommerce-subscriptions' ),
+ '
', ' '
),
),
);
@@ -108,7 +103,7 @@ class WCS_Upgrade_Notice_Manager {
$notice->set_actions( array(
array(
'name' => __( 'Learn more', 'woocommerce-subscriptions' ),
- 'url' => 'https://docs.woocommerce.com/document/subscriptions/whats-new-in-subscriptions-2-6/',
+ 'url' => 'https://docs.woocommerce.com/document/subscriptions/whats-new-in-subscriptions-3-0/',
),
) );
diff --git a/includes/upgrades/templates/update-welcome-notice.php b/includes/upgrades/templates/update-welcome-notice.php
index 1c1357a..4ac1617 100755
--- a/includes/upgrades/templates/update-welcome-notice.php
+++ b/includes/upgrades/templates/update-welcome-notice.php
@@ -2,7 +2,7 @@
tags ?>
- ', '' ) ); ?>
+ ', '' ) ); ?>
@@ -13,4 +13,4 @@
-
+
diff --git a/includes/wcs-cart-functions.php b/includes/wcs-cart-functions.php
index 128b2ff..7f3bba5 100755
--- a/includes/wcs-cart-functions.php
+++ b/includes/wcs-cart-functions.php
@@ -19,10 +19,21 @@ if ( ! defined( 'ABSPATH' ) ) {
* Display a recurring cart's subtotal
*
* @access public
+ * @param WC_Cart $cart The cart do print the subtotal html for.
* @return string
*/
function wcs_cart_totals_subtotal_html( $cart ) {
- echo wp_kses_post( wcs_cart_price_string( $cart->get_cart_subtotal(), $cart ) );
+ $subtotal_html = wcs_cart_price_string( wc_price( $cart->get_displayed_subtotal() ), $cart );
+
+ if ( $cart->get_subtotal_tax() > 0 ) {
+ if ( $cart->display_prices_including_tax() && ! wc_prices_include_tax() ) {
+ $subtotal_html .= '
' . WC()->countries->inc_tax_or_vat() . ' ';
+ } elseif ( ! $cart->display_prices_including_tax() && wc_prices_include_tax() ) {
+ $subtotal_html .= '
' . WC()->countries->ex_tax_or_vat() . ' ';
+ }
+ }
+
+ echo wp_kses_post( $subtotal_html );
}
/**
@@ -258,13 +269,13 @@ function wcs_cart_totals_coupon_html( $coupon, $cart ) {
}
/**
- * Get recurring total html including inc tax if needed
+ * Gets recurring total html including inc tax if needed.
*
- * @access public
- * @return void
+ * @param WC_Cart The cart to display the total for.
*/
function wcs_cart_totals_order_total_html( $cart ) {
- $value = '
' . $cart->get_total() . ' ';
+ $order_total_html = '
' . $cart->get_total() . ' ';
+ $tax_total_html = '';
// If prices are tax inclusive, show taxes here
if ( wc_tax_enabled() && $cart->tax_display_cart == 'incl' ) {
@@ -280,14 +291,14 @@ function wcs_cart_totals_order_total_html( $cart ) {
if ( ! empty( $tax_string_array ) ) {
// translators: placeholder is price string, denotes tax included in cart/order total
- $value .= '
' . sprintf( _x( '(Includes %s)', 'includes tax', 'woocommerce-subscriptions' ), implode( ', ', $tax_string_array ) ) . ' ';
+ $tax_total_html = '
' . sprintf( _x( '(includes %s)', 'includes tax', 'woocommerce-subscriptions' ), implode( ', ', $tax_string_array ) ) . ' ';
}
}
// Apply WooCommerce core filter
- $value = apply_filters( 'woocommerce_cart_totals_order_total_html', $value );
+ $order_total_html = apply_filters( 'woocommerce_cart_totals_order_total_html', $order_total_html );
- echo wp_kses_post( apply_filters( 'wcs_cart_totals_order_total_html', wcs_cart_price_string( $value, $cart ), $cart ) );
+ echo wp_kses_post( apply_filters( 'wcs_cart_totals_order_total_html', wcs_cart_price_string( $order_total_html, $cart ) . $tax_total_html, $cart ) );
}
/**
diff --git a/includes/wcs-order-functions.php b/includes/wcs-order-functions.php
index e596b16..7d6c2cb 100755
--- a/includes/wcs-order-functions.php
+++ b/includes/wcs-order-functions.php
@@ -796,7 +796,10 @@ function wcs_copy_order_item( $from_item, &$to_item ) {
) );
break;
case 'tax':
- /** @var WC_Order_Item_Tax $from_item */
+ /**
+ * @var WC_Order_Item_Tax $from_item
+ * @var WC_Order_Item_Tax $to_item
+ */
$to_item->set_props( array(
'rate_id' => $from_item->get_rate_id(),
'label' => $from_item->get_label(),
@@ -804,6 +807,12 @@ function wcs_copy_order_item( $from_item, &$to_item ) {
'tax_total' => $from_item->get_tax_total(),
'shipping_tax_total' => $from_item->get_shipping_tax_total(),
) );
+
+ // WC 3.7.0+ Compatibility.
+ if ( is_callable( array( $from_item, 'get_rate_percent' ) ) ) {
+ $to_item->set_rate_percent( $from_item->get_rate_percent() );
+ }
+
break;
case 'fee':
/** @var WC_Order_Item_Fee $from_item */
diff --git a/includes/wcs-user-functions.php b/includes/wcs-user-functions.php
index d2bb476..a4b2098 100755
--- a/includes/wcs-user-functions.php
+++ b/includes/wcs-user-functions.php
@@ -419,6 +419,16 @@ function wcs_user_has_capability( $allcaps, $caps, $args ) {
}
}
break;
+ case 'toggle_shop_subscription_auto_renewal' :
+ $user_id = $args[1];
+ $subscription = wcs_get_subscription( $args[2] );
+
+ if ( $subscription && $user_id === $subscription->get_user_id() ) {
+ $allcaps['toggle_shop_subscription_auto_renewal'] = true;
+ } else {
+ unset( $allcaps['toggle_shop_subscription_auto_renewal'] );
+ }
+ break;
}
}
return $allcaps;
diff --git a/languages/woocommerce-subscriptions.pot b/languages/woocommerce-subscriptions.pot
index c9dde51..004cca0 100755
--- a/languages/woocommerce-subscriptions.pot
+++ b/languages/woocommerce-subscriptions.pot
@@ -1,15 +1,15 @@
-# Copyright (C) 2019 Automattic
+# Copyright (C) 2020 WooCommerce
# This file is distributed under the same license as the WooCommerce Subscriptions package.
msgid ""
msgstr ""
-"Project-Id-Version: WooCommerce Subscriptions 2.6.5\n"
+"Project-Id-Version: WooCommerce Subscriptions 3.0.1\n"
"Report-Msgid-Bugs-To: "
"https://github.com/Prospress/woocommerce-subscriptions/issues\n"
-"POT-Creation-Date: 2019-11-14 05:46:49+00:00\n"
+"POT-Creation-Date: 2020-01-17 01:52:41+00:00\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
-"PO-Revision-Date: 2019-MO-DA HO:MI+ZONE\n"
+"PO-Revision-Date: 2020-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME
\n"
"Language-Team: Prospress Translations \n"
"X-Generator: grunt-wp-i18n 0.5.4\n"
@@ -205,21 +205,21 @@ msgid ""
"Subscriptions unless it is the only available option for your country."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:919
+#: includes/admin/class-wc-subscriptions-admin.php:925
msgid "Active subscriber?"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:962
+#: includes/admin/class-wc-subscriptions-admin.php:968
msgid "Manage Subscriptions"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:966
+#: includes/admin/class-wc-subscriptions-admin.php:972
#: woocommerce-subscriptions.php:265
msgid "Search Subscriptions"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:986
-#: includes/admin/class-wc-subscriptions-admin.php:1138
+#: includes/admin/class-wc-subscriptions-admin.php:992
+#: includes/admin/class-wc-subscriptions-admin.php:1144
#: includes/admin/class-wcs-admin-reports.php:46
#: includes/admin/class-wcs-admin-system-status.php:56
#: includes/admin/reports/class-wcs-report-subscription-events-by-date.php:796
@@ -230,25 +230,25 @@ msgstr ""
msgid "Subscriptions"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1178
+#: includes/admin/class-wc-subscriptions-admin.php:1184
msgid "Button Text"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1185
+#: includes/admin/class-wc-subscriptions-admin.php:1191
msgid "Add to Cart Button Text"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1186
+#: includes/admin/class-wc-subscriptions-admin.php:1192
msgid ""
"A product displays a button with the text \"Add to cart\". By default, a "
"subscription changes this to \"Sign up now\". You can customise the button "
"text for subscriptions here."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1190
-#: includes/admin/class-wc-subscriptions-admin.php:1193
-#: includes/admin/class-wc-subscriptions-admin.php:1202
-#: includes/admin/class-wc-subscriptions-admin.php:1205
+#: includes/admin/class-wc-subscriptions-admin.php:1196
+#: includes/admin/class-wc-subscriptions-admin.php:1199
+#: includes/admin/class-wc-subscriptions-admin.php:1208
+#: includes/admin/class-wc-subscriptions-admin.php:1211
#: includes/class-wc-product-subscription-variation.php:98
#: includes/class-wc-product-subscription.php:72
#: includes/class-wc-product-variable-subscription.php:73
@@ -257,11 +257,11 @@ msgstr ""
msgid "Sign up now"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1197
+#: includes/admin/class-wc-subscriptions-admin.php:1203
msgid "Place Order Button Text"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1198
+#: includes/admin/class-wc-subscriptions-admin.php:1204
msgid ""
"Use this field to customise the text displayed on the checkout button when "
"an order contains a subscription. Normally the checkout submission button "
@@ -269,11 +269,11 @@ msgid ""
"changed to \"Sign up now\"."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1211
+#: includes/admin/class-wc-subscriptions-admin.php:1217
msgid "Roles"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1214
+#: includes/admin/class-wc-subscriptions-admin.php:1220
#. translators: placeholders are tags
msgid ""
"Choose the default roles to assign to active and inactive subscribers. For "
@@ -282,46 +282,46 @@ msgid ""
"allocated these roles to prevent locking out administrators."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1219
+#: includes/admin/class-wc-subscriptions-admin.php:1225
msgid "Subscriber Default Role"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1220
+#: includes/admin/class-wc-subscriptions-admin.php:1226
msgid ""
"When a subscription is activated, either manually or after a successful "
"purchase, new users will be assigned this role."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1231
+#: includes/admin/class-wc-subscriptions-admin.php:1237
msgid "Inactive Subscriber Role"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1232
+#: includes/admin/class-wc-subscriptions-admin.php:1238
msgid ""
"If a subscriber's subscription is manually cancelled or expires, she will "
"be assigned this role."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1252
+#: includes/admin/class-wc-subscriptions-admin.php:1258
msgid "Manual Renewal Payments"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1253
+#: includes/admin/class-wc-subscriptions-admin.php:1259
msgid "Accept Manual Renewals"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1258
+#: includes/admin/class-wc-subscriptions-admin.php:1264
#. translators: placeholders are opening and closing link tags
msgid ""
"With manual renewals, a customer's subscription is put on-hold until they "
"login and pay to renew it. %sLearn more%s."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1264
+#: includes/admin/class-wc-subscriptions-admin.php:1270
msgid "Turn off Automatic Payments"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1269
+#: includes/admin/class-wc-subscriptions-admin.php:1275
#. translators: placeholders are opening and closing link tags
msgid ""
"If you don't want new subscription purchases to automatically charge "
@@ -330,11 +330,11 @@ msgid ""
"more%s."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1284
+#: includes/admin/class-wc-subscriptions-admin.php:1290
msgid "Customer Suspensions"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1291
+#: includes/admin/class-wc-subscriptions-admin.php:1297
msgid ""
"Set a maximum number of times a customer can suspend their account for each "
"billing period. For example, for a value of 3 and a subscription billed "
@@ -344,29 +344,29 @@ msgid ""
"this to 0 to turn off the customer suspension feature completely."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1295
+#: includes/admin/class-wc-subscriptions-admin.php:1301
msgid "Mixed Checkout"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1296
+#: includes/admin/class-wc-subscriptions-admin.php:1302
msgid "Allow multiple subscriptions and products to be purchased simultaneously."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1300
+#: includes/admin/class-wc-subscriptions-admin.php:1306
msgid ""
"Allow a subscription product to be purchased with other products and "
"subscriptions in the same transaction."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1304
+#: includes/admin/class-wc-subscriptions-admin.php:1310
msgid "$0 Initial Checkout"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1305
+#: includes/admin/class-wc-subscriptions-admin.php:1311
msgid "Allow $0 initial checkout without a payment method."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1309
+#: includes/admin/class-wc-subscriptions-admin.php:1315
msgid ""
"Allow a subscription product with a $0 initial payment to be purchased "
"without providing a payment method. The customer will be required to "
@@ -374,16 +374,16 @@ msgid ""
"subscription active."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1313
+#: includes/admin/class-wc-subscriptions-admin.php:1319
#: includes/upgrades/templates/wcs-about-2-0.php:108
msgid "Drip Downloadable Content"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1314
+#: includes/admin/class-wc-subscriptions-admin.php:1320
msgid "Enable dripping for downloadable content on subscription products."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1318
+#: includes/admin/class-wc-subscriptions-admin.php:1324
msgid ""
"Enabling this grants access to new downloadable files added to a product "
"only after the next renewal is processed.%sBy default, access to new "
@@ -391,7 +391,7 @@ msgid ""
"customer that has an active subscription with that product."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1354
+#: includes/admin/class-wc-subscriptions-admin.php:1360
#. translators: $1-$2: opening and closing tags, $3-$4: opening and
#. closing tags
msgid ""
@@ -399,84 +399,84 @@ msgid ""
"start selling subscriptions!%4$s"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1359
+#: includes/admin/class-wc-subscriptions-admin.php:1365
msgid "Add a Subscription Product"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1360
+#: includes/admin/class-wc-subscriptions-admin.php:1366
#: includes/upgrades/templates/wcs-about-2-0.php:35
#: includes/upgrades/templates/wcs-about.php:34
#: woocommerce-subscriptions.php:1114
msgid "Settings"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1443
+#: includes/admin/class-wc-subscriptions-admin.php:1449
#. translators: placeholder is a number
msgid "We can't find a subscription with ID #%d. Perhaps it was deleted?"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1487
+#: includes/admin/class-wc-subscriptions-admin.php:1493
#. translators: Placeholders are opening and closing link tags.
msgid ""
"We weren't able to locate the set of report results you requested. Please "
"regenerate the link from the %sSubscription Reports screen%s."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1541
+#: includes/admin/class-wc-subscriptions-admin.php:1547
msgid "We can't find a paid subscription order for this user."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1573
-#: includes/admin/class-wc-subscriptions-admin.php:1578
+#: includes/admin/class-wc-subscriptions-admin.php:1579
+#: includes/admin/class-wc-subscriptions-admin.php:1584
#. translators: placeholders are opening link tag, ID of sub, and closing link
#. tag
msgid "Showing orders for %sSubscription %s%s"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1602
+#: includes/admin/class-wc-subscriptions-admin.php:1608
#. translators: number of 1$: days, 2$: weeks, 3$: months, 4$: years
msgid "The trial period can not exceed: %1s, %2s, %3s or %4s."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1607
+#: includes/admin/class-wc-subscriptions-admin.php:1613
#. translators: placeholder is a time period (e.g. "4 weeks")
msgid "The trial period can not exceed %s."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1670
-#: includes/admin/class-wc-subscriptions-admin.php:1737
+#: includes/admin/class-wc-subscriptions-admin.php:1676
+#: includes/admin/class-wc-subscriptions-admin.php:1743
#: includes/admin/class-wcs-admin-system-status.php:95
#: includes/admin/reports/class-wcs-report-cache-manager.php:331
msgid "Yes"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1670
+#: includes/admin/class-wc-subscriptions-admin.php:1676
#: includes/admin/class-wcs-admin-system-status.php:95
#: includes/admin/reports/class-wcs-report-cache-manager.php:331
msgid "No"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1706
+#: includes/admin/class-wc-subscriptions-admin.php:1712
msgid "Automatic Recurring Payments"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1737
+#: includes/admin/class-wc-subscriptions-admin.php:1743
msgid ""
"Supports automatic renewal payments with the WooCommerce Subscriptions "
"extension."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1832
+#: includes/admin/class-wc-subscriptions-admin.php:1838
msgid "Subscription items can no longer be edited."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1836
+#: includes/admin/class-wc-subscriptions-admin.php:1842
msgid ""
"This subscription is no longer editable because the payment gateway does "
"not allow modification of recurring amounts."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1855
+#: includes/admin/class-wc-subscriptions-admin.php:1861
#. translators: $1-2: opening and closing tags of a link that takes to Woo
#. marketplace / Stripe product page
msgid ""
@@ -485,18 +485,18 @@ msgid ""
"the %1$sfree Stripe extension%2$s."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1860
+#: includes/admin/class-wc-subscriptions-admin.php:1866
msgid "Recurring Payments"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1868
+#: includes/admin/class-wc-subscriptions-admin.php:1874
#. translators: placeholders are opening and closing link tags
msgid ""
"Payment gateways which don't support automatic recurring payments can be "
"used to process %smanual subscription renewal payments%s."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1875
+#: includes/admin/class-wc-subscriptions-admin.php:1881
#. translators: $1-$2: opening and closing tags. Link to documents->payment
#. gateways, 3$-4$: opening and closing tags. Link to WooCommerce extensions
#. shop page
@@ -505,7 +505,7 @@ msgid ""
"the official %3$sWooCommerce Marketplace%4$s."
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1977
+#: includes/admin/class-wc-subscriptions-admin.php:1983
msgid "Note that purchasing a subscription still requires an account."
msgstr ""
@@ -787,7 +787,7 @@ msgid "%1$s (#%2$s – %3$s)"
msgstr ""
#: includes/admin/class-wcs-admin-post-types.php:1149
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:84
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:85
msgid "Search for a customer…"
msgstr ""
@@ -815,8 +815,7 @@ msgstr ""
msgid "Failed Payment Retries"
msgstr ""
-#: includes/admin/class-wcs-admin-reports.php:104
-#: includes/admin/reports/class-wcs-report-cache-manager.php:277
+#. Author of the plugin/theme
msgid "WooCommerce"
msgstr ""
@@ -857,103 +856,108 @@ msgstr ""
msgid "version %1$s is out of date. The core version is %2$s"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:54
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:52
+msgid "General"
+msgstr ""
+
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:55
msgid "Customer:"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:63
-msgid "View other subscriptions"
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:64
+msgid "View other subscriptions →"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:68
-msgid "Profile"
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:69
+msgid "Profile →"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:92
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:93
msgid "Subscription status:"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:109
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:110
msgid "Parent order: "
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:111
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:112
msgid "#%1$s"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:117
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:118
msgid "Parent order:"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:123
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:124
msgid "Select an order…"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:133
-msgid "Billing Details"
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:134
+msgid "Billing"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:134
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:222
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:135
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:225
#: includes/payment-retry/class-wcs-retry-post-store.php:38
msgid "Edit"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:135
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:137
msgid "Load billing address"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:142
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:144
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:231
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:233
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:145
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:147
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:236
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:238
msgid "Address"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:144
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:147
msgid "No billing address set."
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:164
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:167
#: includes/class-wcs-change-payment-method-admin.php:38
#: includes/class-wcs-change-payment-method-admin.php:51
msgid "Payment Method"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:205
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:208
msgid "Customer change payment method page →"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:207
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:210
msgid "Customer add payment method page →"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:221
-msgid "Shipping Details"
-msgstr ""
-
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:223
-msgid "Copy from billing"
-msgstr ""
-
#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:224
+#: includes/wcs-cart-functions.php:114
+msgid "Shipping"
+msgstr ""
+
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:227
msgid "Load shipping address"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:233
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:228
+msgid "Copy billing address"
+msgstr ""
+
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:238
msgid "No shipping address set."
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:255
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:285
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:260
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:290
msgid "Customer Provided Note"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:286
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:291
msgid "Customer's notes about the order"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:391
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:396
#. translators: placeholder is error message from the payment gateway or
#. subscriptions when updating the status
msgid "Error updating some information: %s"
@@ -1780,7 +1784,7 @@ msgid "Error during subscription status transition."
msgstr ""
#: includes/class-wc-subscription.php:1183
-#: includes/class-wc-subscriptions-manager.php:2281
+#: includes/class-wc-subscriptions-manager.php:2277
#. translators: placeholder is human time diff (e.g. "3 weeks")
msgid "In %s"
msgstr ""
@@ -1920,7 +1924,7 @@ msgid ""
"can not be purchased at the same time."
msgstr ""
-#: includes/class-wc-subscriptions-cart-validator.php:110
+#: includes/class-wc-subscriptions-cart-validator.php:108
msgid ""
"Your cart has been emptied of subscription products. Products and "
"subscriptions cannot be purchased at the same time."
@@ -1945,37 +1949,23 @@ msgstr ""
msgid "now"
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:179
-#: templates/emails/plain/email-order-details.php:19
-#. translators: placeholder is the subscription order number wrapped in
-#. tags
-msgid "Subscription Number: %s"
-msgstr ""
-
-#: includes/class-wc-subscriptions-change-payment-gateway.php:185
-#. translators: placeholder is the subscription's next payment date (either
-#. human readable or normal date) wrapped in tags
-msgid "Next Payment Date: %s"
-msgstr ""
-
-#: includes/class-wc-subscriptions-change-payment-gateway.php:191
-#. translators: placeholder is the formatted total to be paid for the
-#. subscription wrapped in tags
-msgid "Total: %s"
-msgstr ""
-
-#: includes/class-wc-subscriptions-change-payment-gateway.php:198
-#. translators: placeholder is the display name of the payment method
-msgid "Payment Method: %s"
-msgstr ""
-
-#: includes/class-wc-subscriptions-change-payment-gateway.php:210
+#: includes/class-wc-subscriptions-change-payment-gateway.php:181
msgid ""
"Sorry, this subscription change payment method request is invalid and "
"cannot be processed."
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:242
+#: includes/class-wc-subscriptions-change-payment-gateway.php:201
+#. translators: placeholder is next payment's date
+msgid " Next payment is due %s."
+msgstr ""
+
+#: includes/class-wc-subscriptions-change-payment-gateway.php:207
+#. translators: placeholder is either empty or "Next payment is due..."
+msgid "Choose a new payment method.%s"
+msgstr ""
+
+#: includes/class-wc-subscriptions-change-payment-gateway.php:243
#: includes/early-renewal/class-wcs-early-renewal-modal-handler.php:97
msgid "There was an error with your request. Please try again."
msgstr ""
@@ -1985,7 +1975,7 @@ msgstr ""
msgid "Invalid Subscription."
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:250
+#: includes/class-wc-subscriptions-change-payment-gateway.php:249
#: includes/class-wcs-cart-resubscribe.php:78
#: includes/class-wcs-cart-resubscribe.php:129
#: includes/class-wcs-user-change-status-handler.php:103
@@ -1993,39 +1983,29 @@ msgstr ""
msgid "That doesn't appear to be one of your subscriptions."
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:254
+#: includes/class-wc-subscriptions-change-payment-gateway.php:252
#: includes/class-wcs-query.php:253
msgid "The payment method can not be changed for that subscription."
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:260
-#. translators: placeholder is next payment's date
-msgid " Next payment is due %s."
-msgstr ""
-
-#: includes/class-wc-subscriptions-change-payment-gateway.php:266
-#. translators: placeholder is either empty or "Next payment is due..."
-msgid "Choose a new payment method.%s"
-msgstr ""
-
-#: includes/class-wc-subscriptions-change-payment-gateway.php:295
+#: includes/class-wc-subscriptions-change-payment-gateway.php:255
msgid "Invalid order."
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:381
+#: includes/class-wc-subscriptions-change-payment-gateway.php:336
msgid "Payment method updated."
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:381
+#: includes/class-wc-subscriptions-change-payment-gateway.php:336
msgid "Payment method added."
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:421
-#: includes/class-wc-subscriptions-change-payment-gateway.php:423
+#: includes/class-wc-subscriptions-change-payment-gateway.php:376
+#: includes/class-wc-subscriptions-change-payment-gateway.php:378
msgid "Payment method updated for all your current subscriptions."
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:832
+#: includes/class-wc-subscriptions-change-payment-gateway.php:787
msgid ""
"Please log in to your account below to choose a new payment method for your "
"subscription."
@@ -2166,91 +2146,91 @@ msgstr ""
msgid "Error: Unable to create renewal order with note \"%s\""
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:137
+#: includes/class-wc-subscriptions-manager.php:133
msgid "Manual renewal order awaiting customer payment."
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:169
+#: includes/class-wc-subscriptions-manager.php:165
#: includes/gateways/class-wc-subscriptions-payment-gateways.php:213
msgid "Subscription doesn't exist in scheduled action: %d"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:306
+#: includes/class-wc-subscriptions-manager.php:302
#. translators: $1: order number, $2: error message
msgid "Failed to activate subscription status for order #%1$s: %2$s"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:334
+#: includes/class-wc-subscriptions-manager.php:330
#. translators: $1: order number, $2: error message
msgid "Failed to update subscription status after order #%1$s was put on-hold: %2$s"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:362
+#: includes/class-wc-subscriptions-manager.php:358
#. translators: $1: order number, $2: error message
msgid "Failed to cancel subscription after order #%1$s was cancelled: %2$s"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:390
+#: includes/class-wc-subscriptions-manager.php:386
#. translators: $1: order number, $2: error message
msgid "Failed to set subscription as expired for order #%1$s: %2$s"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:416
+#: includes/class-wc-subscriptions-manager.php:412
msgid "Subscription sign up failed."
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:426
+#: includes/class-wc-subscriptions-manager.php:422
#. translators: $1: order number, $2: error message
msgid "Failed to process failed payment on subscription for order #%1$s: %2$s"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:495
+#: includes/class-wc-subscriptions-manager.php:491
msgid "Error: Unable to create subscription. Please try again."
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:514
+#: includes/class-wc-subscriptions-manager.php:510
msgid "Error: Unable to add product to created subscription. Please try again."
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:559
+#: includes/class-wc-subscriptions-manager.php:555
msgid "Pending subscription created."
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:1821
+#: includes/class-wc-subscriptions-manager.php:1817
#. translators: all fields are full html nodes: 1$: month input, 2$: day input,
#. 3$: year input, 4$: hour input, 5$: minute input. Change the order if you'd
#. like
msgid "%1$s%2$s, %3$s @ %4$s : %5$s"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:1825
+#: includes/class-wc-subscriptions-manager.php:1821
#. translators: all fields are full html nodes: 1$: month input, 2$: day input,
#. 3$: year input. Change the order if you'd like
msgid "%1$s%2$s, %3$s"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:1830
+#: includes/class-wc-subscriptions-manager.php:1826
msgid "Change"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:2163
+#: includes/class-wc-subscriptions-manager.php:2159
#. translators: placeholder is subscription ID
msgid "Failed sign-up for subscription %s."
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:2254
+#: includes/class-wc-subscriptions-manager.php:2250
msgid "Invalid security token, please reload the page and try again."
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:2258
+#: includes/class-wc-subscriptions-manager.php:2254
msgid "Only store managers can edit payment dates."
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:2262
+#: includes/class-wc-subscriptions-manager.php:2258
msgid "Please enter all date fields."
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:2287
+#: includes/class-wc-subscriptions-manager.php:2283
msgid "Date Changed"
msgstr ""
@@ -2419,7 +2399,7 @@ msgid "Choose a new subscription."
msgstr ""
#: includes/class-wc-subscriptions-switcher.php:230
-#: includes/class-wc-subscriptions-switcher.php:1246
+#: includes/class-wc-subscriptions-switcher.php:1249
msgid ""
"Your cart contained an invalid subscription switch request. It has been "
"removed."
@@ -2499,8 +2479,8 @@ msgid ""
msgstr ""
#: includes/class-wc-subscriptions-switcher.php:444
-#: includes/class-wc-subscriptions-switcher.php:536
-#: includes/class-wc-subscriptions-switcher.php:2561
+#: includes/class-wc-subscriptions-switcher.php:539
+#: includes/class-wc-subscriptions-switcher.php:2564
msgid "Upgrade or Downgrade"
msgstr ""
@@ -2508,45 +2488,45 @@ msgstr ""
msgid "Allow Switching"
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1105
+#: includes/class-wc-subscriptions-switcher.php:1108
msgid "Switch order cancelled due to a new switch order being created #%s."
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1193
+#: includes/class-wc-subscriptions-switcher.php:1196
msgid "Switch Order"
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1208
+#: includes/class-wc-subscriptions-switcher.php:1211
msgid "Switched Subscription"
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1374
+#: includes/class-wc-subscriptions-switcher.php:1377
msgid "You can only switch to a subscription product."
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1380
+#: includes/class-wc-subscriptions-switcher.php:1383
msgid "We can not find your old subscription item."
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1402
+#: includes/class-wc-subscriptions-switcher.php:1405
msgid "You can not switch to the same subscription."
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1449
+#: includes/class-wc-subscriptions-switcher.php:1452
msgid ""
"You can not switch this subscription. It appears you do not own the "
"subscription."
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1490
+#: includes/class-wc-subscriptions-switcher.php:1493
msgid "There was an error locating the switch details."
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1963
+#: includes/class-wc-subscriptions-switcher.php:1966
msgid "The original subscription item being switched cannot be found."
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1965
+#: includes/class-wc-subscriptions-switcher.php:1968
msgid "The item on the switch order cannot be found."
msgstr ""
@@ -2749,7 +2729,7 @@ msgid "Ignore this error"
msgstr ""
#: includes/class-wcs-failed-scheduled-action-manager.php:139
-#: includes/upgrades/class-wcs-upgrade-notice-manager.php:110
+#: includes/upgrades/class-wcs-upgrade-notice-manager.php:105
msgid "Learn more"
msgstr ""
@@ -2776,15 +2756,15 @@ msgstr ""
msgid "Limit to one of any status"
msgstr ""
-#: includes/class-wcs-my-account-auto-renew-toggle.php:135
+#: includes/class-wcs-my-account-auto-renew-toggle.php:153
msgid "Auto Renewal Toggle"
msgstr ""
-#: includes/class-wcs-my-account-auto-renew-toggle.php:136
+#: includes/class-wcs-my-account-auto-renew-toggle.php:154
msgid "Display the auto renewal toggle"
msgstr ""
-#: includes/class-wcs-my-account-auto-renew-toggle.php:137
+#: includes/class-wcs-my-account-auto-renew-toggle.php:155
msgid ""
"Allow customers to turn on and off automatic renewals from their View "
"Subscription page."
@@ -3181,6 +3161,24 @@ msgid ""
"download your files"
msgstr ""
+#: includes/emails/class-wcs-email-customer-on-hold-renewal-order.php:23
+msgid "On-hold Renewal Order"
+msgstr ""
+
+#: includes/emails/class-wcs-email-customer-on-hold-renewal-order.php:24
+msgid ""
+"This is an order notification sent to customers containing order details "
+"after a renewal order is placed on-hold."
+msgstr ""
+
+#: includes/emails/class-wcs-email-customer-on-hold-renewal-order.php:25
+msgid "Your {blogname} renewal order has been received!"
+msgstr ""
+
+#: includes/emails/class-wcs-email-customer-on-hold-renewal-order.php:26
+msgid "Thank you for your renewal order"
+msgstr ""
+
#: includes/emails/class-wcs-email-customer-payment-retry.php:24
msgid "Customer Payment Retry"
msgstr ""
@@ -3880,38 +3878,30 @@ msgid "Subscription end date in the past"
msgstr ""
#: includes/upgrades/class-wcs-upgrade-notice-manager.php:85
-msgid "Improved experience for customers who renew their subscriptions early"
+msgid "Improved scheduled action data storage"
msgstr ""
#: includes/upgrades/class-wcs-upgrade-notice-manager.php:86
msgid ""
-"Allow customers to renew early from their %sMy Account > Subscription%s "
-"page without going through the checkout."
+"Scheduled action data, which was previously stored in the WordPress post "
+"tables, has been moved to a custom database table. Amongst other benefits, "
+"this will greatly improve the performance of processing scheduled actions "
+"such as subscription payments."
msgstr ""
#: includes/upgrades/class-wcs-upgrade-notice-manager.php:89
-msgid "Improved subscription switching proration calculations"
+msgid "Increased processing rate for scheduled payments"
msgstr ""
-#: includes/upgrades/class-wcs-upgrade-notice-manager.php:90
+#: includes/upgrades/class-wcs-upgrade-notice-manager.php:91
msgid ""
-"We've made improvements to the code which calculates the upgrade costs when "
-"a customer switches their subscription. This has enabled us to fix a number "
-"of complicated switching scenarios."
+"Previous versions of Subscriptions relied on %sWP Cron%s to process "
+"subscription payments and other scheduled events. In 3.0, these events will "
+"now run on admin request with loopback support. This will significantly "
+"increase the throughput of payment processing."
msgstr ""
-#: includes/upgrades/class-wcs-upgrade-notice-manager.php:93
-msgid "View subscriptions and orders contributing to reports"
-msgstr ""
-
-#: includes/upgrades/class-wcs-upgrade-notice-manager.php:95
-msgid ""
-"Want to view which specific orders and subscriptions are contributing to "
-"subscription-related reports? You can now do just that by clicking on the "
-"%1$s link while viewing %2$ssubscription reports%3$s."
-msgstr ""
-
-#: includes/upgrades/class-wcs-upgrade-notice-manager.php:103
+#: includes/upgrades/class-wcs-upgrade-notice-manager.php:98
#. translators: placeholder is Subscription version string ('2.3')
msgid "Welcome to WooCommerce Subscriptions %s!"
msgstr ""
@@ -3927,8 +3917,8 @@ msgstr ""
#. translators: placeholder $1 is the Subscription version string ('2.3'), $2-3
#. are opening and closing tags
msgid ""
-"Version %1$s brings some great new features requested by store managers "
-"just like you (and possibly even by %2$syou%3$s)."
+"Version %1$s brings some new improvements requested by store managers just "
+"like you (and possibly even by %2$syou%3$s)."
msgstr ""
#: includes/upgrades/templates/update-welcome-notice.php:6
@@ -3943,7 +3933,7 @@ msgstr ""
#: includes/upgrades/templates/update-welcome-notice.php:16
#. translators: placeholder is Subscription version string ('2.3')
-msgid "Want to know more about Subscriptions %s and these new features?"
+msgid "Want to know more about Subscriptions %s?"
msgstr ""
#: includes/upgrades/templates/wcs-about-2-0.php:20
@@ -4559,25 +4549,19 @@ msgstr ""
msgid "There was an error with the update. Please refresh the page and try again."
msgstr ""
-#: includes/wcs-cart-functions.php:83 includes/wcs-cart-functions.php:84
+#: includes/wcs-cart-functions.php:94 includes/wcs-cart-functions.php:95
msgid "Shipping via %s"
msgstr ""
-#: includes/wcs-cart-functions.php:103
-msgid "Shipping"
-msgid_plural "Shipping %d"
-msgstr[0] ""
-msgstr[1] ""
-
-#: includes/wcs-cart-functions.php:217
+#: includes/wcs-cart-functions.php:228
msgid "[Remove]"
msgstr ""
-#: includes/wcs-cart-functions.php:247
+#: includes/wcs-cart-functions.php:258
msgid "Free shipping coupon"
msgstr ""
-#: includes/wcs-cart-functions.php:352
+#: includes/wcs-cart-functions.php:363
#. translators: placeholder is a date
msgid "First renewal: %s"
msgstr ""
@@ -4798,7 +4782,7 @@ msgstr ""
msgid "Shipping Tax:"
msgstr ""
-#: templates/admin/html-failed-scheduled-action-notice.php:15
+#: templates/admin/html-failed-scheduled-action-notice.php:21
msgid ""
"An error has occurred while processing a recent subscription related event. "
"For steps on how to fix the affected subscription and to learn more about "
@@ -4810,13 +4794,13 @@ msgid_plural ""
msgstr[0] ""
msgstr[1] ""
-#: templates/admin/html-failed-scheduled-action-notice.php:25
+#: templates/admin/html-failed-scheduled-action-notice.php:31
msgid "Affected event:"
msgid_plural "Affected events:"
msgstr[0] ""
msgstr[1] ""
-#: templates/admin/html-failed-scheduled-action-notice.php:32
+#: templates/admin/html-failed-scheduled-action-notice.php:38
#. translators: $1 the log file name $2 and $3 are opening and closing link
#. tags, respectively.
msgid ""
@@ -4872,6 +4856,30 @@ msgstr ""
msgid "Recurring total"
msgstr ""
+#: templates/checkout/subscription-receipt.php:18
+#: templates/emails/plain/email-order-details.php:19
+#. translators: placeholder is the subscription order number wrapped in
+#. tags
+msgid "Subscription Number: %s"
+msgstr ""
+
+#: templates/checkout/subscription-receipt.php:24
+#. translators: placeholder is the subscription's next payment date (either
+#. human readable or normal date) wrapped in tags
+msgid "Next Payment Date: %s"
+msgstr ""
+
+#: templates/checkout/subscription-receipt.php:30
+#. translators: placeholder is the formatted total to be paid for the
+#. subscription wrapped in tags
+msgid "Total: %s"
+msgstr ""
+
+#: templates/checkout/subscription-receipt.php:37
+#. translators: placeholder is the display name of the payment method
+msgid "Payment Method: %s"
+msgstr ""
+
#: templates/emails/admin-new-switch-order.php:20
msgid "Switch Order Details"
msgstr ""
@@ -4902,11 +4910,13 @@ msgstr ""
#: templates/emails/customer-completed-renewal-order.php:17
#: templates/emails/customer-completed-switch-order.php:17
+#: templates/emails/customer-on-hold-renewal-order.php:17
#: templates/emails/customer-payment-retry.php:16
#: templates/emails/customer-processing-renewal-order.php:17
#: templates/emails/customer-renewal-invoice.php:16
#: templates/emails/plain/customer-completed-renewal-order.php:16
#: templates/emails/plain/customer-completed-switch-order.php:16
+#: templates/emails/plain/customer-on-hold-renewal-order.php:16
#: templates/emails/plain/customer-payment-retry.php:16
#: templates/emails/plain/customer-processing-renewal-order.php:16
#: templates/emails/plain/customer-renewal-invoice.php:16
@@ -4926,6 +4936,13 @@ msgid ""
"subscription details are shown below for your reference:"
msgstr ""
+#: templates/emails/customer-on-hold-renewal-order.php:18
+#: templates/emails/plain/customer-on-hold-renewal-order.php:17
+msgid ""
+"Thanks for your renewal order. It’s on-hold until we confirm that payment "
+"has been received. In the meantime, here’s a reminder of your order:"
+msgstr ""
+
#: templates/emails/customer-processing-renewal-order.php:19
#: templates/emails/plain/customer-processing-renewal-order.php:18
#. translators: %s: Order number
@@ -4939,6 +4956,10 @@ msgstr ""
msgid "Pay Now »"
msgstr ""
+#: templates/emails/email-order-details.php:61
+msgid "Note:"
+msgstr ""
+
#: templates/emails/expired-subscription.php:16
#: templates/emails/plain/expired-subscription.php:16
#. translators: $1: customer's billing first name and last name
@@ -5283,10 +5304,6 @@ msgid ""
"Store."
msgstr ""
-#. Author of the plugin/theme
-msgid "Automattic"
-msgstr ""
-
#. Author URI of the plugin/theme
msgid "https://woocommerce.com/"
msgstr ""
@@ -5336,17 +5353,17 @@ msgid ""
"sign-up fee and free trial.%4$s"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1245
+#: includes/admin/class-wc-subscriptions-admin.php:1251
msgctxt "option section heading"
msgid "Renewals"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1277
+#: includes/admin/class-wc-subscriptions-admin.php:1283
msgctxt "options section heading"
msgid "Miscellaneous"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1285
+#: includes/admin/class-wc-subscriptions-admin.php:1291
msgctxt "there's a number immediately in front of this text"
msgid "suspensions per billing period."
msgstr ""
@@ -5356,25 +5373,25 @@ msgctxt "there's a number immediately in front of this text"
msgid "days prior to Renewal Day"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1669
+#: includes/admin/class-wc-subscriptions-admin.php:1675
#: includes/admin/class-wcs-admin-system-status.php:93
msgctxt "label that indicates whether debugging is turned on for the plugin"
msgid "WCS_DEBUG"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1675
+#: includes/admin/class-wc-subscriptions-admin.php:1681
#: includes/admin/class-wcs-admin-system-status.php:107
msgctxt "Live or Staging, Label on WooCommerce -> System Status page"
msgid "Subscriptions Mode"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1676
+#: includes/admin/class-wc-subscriptions-admin.php:1682
#: includes/admin/class-wcs-admin-system-status.php:109
msgctxt "refers to staging site"
msgid "Staging"
msgstr ""
-#: includes/admin/class-wc-subscriptions-admin.php:1676
+#: includes/admin/class-wc-subscriptions-admin.php:1682
#: includes/admin/class-wcs-admin-system-status.php:109
msgctxt "refers to live site"
msgid "Live"
@@ -5402,7 +5419,7 @@ msgstr ""
#: includes/admin/class-wcs-admin-post-types.php:260
#: includes/admin/class-wcs-admin-post-types.php:473
-#: includes/class-wc-subscriptions-manager.php:1831
+#: includes/class-wc-subscriptions-manager.php:1827
#: includes/wcs-user-functions.php:349
#: templates/myaccount/related-orders.php:78
msgctxt "an action on a subscription"
@@ -5548,7 +5565,7 @@ msgctxt "edit subscription header"
msgid "Subscription #%s details"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:168
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:171
#: includes/class-wcs-change-payment-method-admin.php:52
msgctxt ""
"The gateway ID displayed on the Edit Subscriptions screen when editing "
@@ -5556,7 +5573,7 @@ msgctxt ""
msgid "Gateway ID: [%s]"
msgstr ""
-#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:377
+#: includes/admin/meta-boxes/class-wcs-meta-box-subscription-data.php:382
msgctxt "subscription note after linking to a parent order"
msgid "Subscription linked to parent order %s via admin."
msgstr ""
@@ -5574,7 +5591,7 @@ msgid "#%s"
msgstr ""
#: includes/class-wc-subscriptions-addresses.php:206
-#: includes/class-wc-subscriptions-change-payment-gateway.php:776
+#: includes/class-wc-subscriptions-change-payment-gateway.php:731
#: includes/class-wcs-query.php:110
msgctxt "hash before order number"
msgid "Subscription #%s"
@@ -5702,38 +5719,38 @@ msgctxt "change billing or shipping address"
msgid "Change %s address"
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:318
+#: includes/class-wc-subscriptions-change-payment-gateway.php:273
msgctxt "label on button, imperative"
msgid "Change payment"
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:320
+#: includes/class-wc-subscriptions-change-payment-gateway.php:275
msgctxt "label on button, imperative"
msgid "Add payment"
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:570
+#: includes/class-wc-subscriptions-change-payment-gateway.php:525
msgctxt "%1$s: old payment title, %2$s: new payment title"
msgid ""
"Payment method changed from \"%1$s\" to \"%2$s\" by the subscriber from "
"their account page."
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:745
-#: includes/class-wc-subscriptions-change-payment-gateway.php:782
+#: includes/class-wc-subscriptions-change-payment-gateway.php:700
+#: includes/class-wc-subscriptions-change-payment-gateway.php:737
msgctxt "the page title of the change payment method form"
msgid "Change payment method"
msgstr ""
-#: includes/class-wc-subscriptions-change-payment-gateway.php:747
-#: includes/class-wc-subscriptions-change-payment-gateway.php:787
+#: includes/class-wc-subscriptions-change-payment-gateway.php:702
+#: includes/class-wc-subscriptions-change-payment-gateway.php:742
msgctxt "the page title of the add payment method form"
msgid "Add payment method"
msgstr ""
#: includes/class-wc-subscriptions-manager.php:87
-#: includes/class-wc-subscriptions-manager.php:1895
-#: includes/class-wc-subscriptions-manager.php:1913
+#: includes/class-wc-subscriptions-manager.php:1891
+#: includes/class-wc-subscriptions-manager.php:1909
msgctxt "used in order note as reason for why subscription status changed"
msgid "Subscription renewal payment due:"
msgstr ""
@@ -5749,37 +5766,37 @@ msgctxt "used in order note as reason for why subscription status changed"
msgid "Customer requested to renew early:"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:1042 wcs-functions.php:233
+#: includes/class-wc-subscriptions-manager.php:1038 wcs-functions.php:233
msgctxt "Subscription status"
msgid "Active"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:1045 wcs-functions.php:235
+#: includes/class-wc-subscriptions-manager.php:1041 wcs-functions.php:235
msgctxt "Subscription status"
msgid "Cancelled"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:1048 wcs-functions.php:237
+#: includes/class-wc-subscriptions-manager.php:1044 wcs-functions.php:237
msgctxt "Subscription status"
msgid "Expired"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:1051 wcs-functions.php:232
+#: includes/class-wc-subscriptions-manager.php:1047 wcs-functions.php:232
msgctxt "Subscription status"
msgid "Pending"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:1054
+#: includes/class-wc-subscriptions-manager.php:1050
msgctxt "Subscription status"
msgid "Failed"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:1058
+#: includes/class-wc-subscriptions-manager.php:1054
msgctxt "Subscription status"
msgid "On-hold"
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:2702 wcs-functions.php:236
+#: includes/class-wc-subscriptions-switcher.php:2705 wcs-functions.php:236
msgctxt "Subscription status"
msgid "Switched"
msgstr ""
@@ -5794,7 +5811,7 @@ msgctxt "Subscription status"
msgid "Pending Cancellation"
msgstr ""
-#: includes/class-wc-subscriptions-manager.php:1808
+#: includes/class-wc-subscriptions-manager.php:1804
#. translators: 1$: month number (e.g. "01"), 2$: month abbreviation (e.g.
#. "Jan")
msgctxt "used in a select box"
@@ -5904,35 +5921,35 @@ msgctxt "when to allow switching"
msgid "Between Grouped Subscriptions"
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1851
+#: includes/class-wc-subscriptions-switcher.php:1854
msgctxt "a switch type"
msgid "Downgrade"
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1854
+#: includes/class-wc-subscriptions-switcher.php:1857
msgctxt "a switch type"
msgid "Upgrade"
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1857
+#: includes/class-wc-subscriptions-switcher.php:1860
msgctxt "a switch type"
msgid "Crossgrade"
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1862
+#: includes/class-wc-subscriptions-switcher.php:1865
#. translators: %1: product subtotal, %2: HTML span tag, %3: direction
#. (upgrade, downgrade, crossgrade), %4: closing HTML span tag
msgctxt "product subtotal string"
msgid "%1$s %2$s(%3$s)%4$s"
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1987
+#: includes/class-wc-subscriptions-switcher.php:1990
#. translators: 1$: old item, 2$: new item when switching
msgctxt "used in order notes"
msgid "Customer switched from: %1$s to %2$s."
msgstr ""
-#: includes/class-wc-subscriptions-switcher.php:1989
+#: includes/class-wc-subscriptions-switcher.php:1992
msgctxt "used in order notes"
msgid "Customer added %s."
msgstr ""
@@ -6303,7 +6320,7 @@ msgstr ""
#: includes/upgrades/class-wcs-upgrade-notice-manager.php:80
msgctxt "plugin version number used in admin notice"
-msgid "2.6"
+msgid "3.0"
msgstr ""
#: includes/upgrades/templates/wcs-about-2-0.php:36
@@ -6347,16 +6364,16 @@ msgctxt "text on submit button"
msgid "Update Database"
msgstr ""
-#: includes/wcs-cart-functions.php:192
+#: includes/wcs-cart-functions.php:203
msgctxt "shipping method price"
msgid "Free"
msgstr ""
-#: includes/wcs-cart-functions.php:283
+#: includes/wcs-cart-functions.php:294
#. translators: placeholder is price string, denotes tax included in cart/order
#. total
msgctxt "includes tax"
-msgid "(Includes %s)"
+msgid "(includes %s)"
msgstr ""
#: includes/wcs-formatting-functions.php:39
@@ -6537,14 +6554,14 @@ msgid ""
msgstr ""
#: templates/checkout/form-change-payment-method.php:20
-#: templates/emails/email-order-details.php:34
+#: templates/emails/email-order-details.php:36
#: templates/myaccount/subscription-totals-table.php:21
msgctxt "table headings in notification email"
msgid "Product"
msgstr ""
#: templates/checkout/form-change-payment-method.php:21
-#: templates/emails/email-order-details.php:35
+#: templates/emails/email-order-details.php:37
msgctxt "table headings in notification email"
msgid "Quantity"
msgstr ""
@@ -6555,7 +6572,7 @@ msgid "Totals"
msgstr ""
#: templates/emails/cancelled-subscription.php:22
-#: templates/emails/email-order-details.php:36
+#: templates/emails/email-order-details.php:38
#: templates/emails/expired-subscription.php:22
#: templates/emails/on-hold-subscription.php:22
msgctxt "table headings in notification email"
@@ -6679,14 +6696,14 @@ msgid ""
"renewal from your account page: %1$s"
msgstr ""
-#: templates/emails/email-order-details.php:22
+#: templates/emails/email-order-details.php:24
#. translators: $1-$2: opening and closing tags $3: order's order number
#. $4: date of order in element
msgctxt "Used in email notification"
msgid "%1$sOrder #%3$s%2$s (%4$s)"
msgstr ""
-#: templates/emails/email-order-details.php:25
+#: templates/emails/email-order-details.php:27
#. translators: $1-$3: opening and closing tags $2: subscription's order
#. number
msgctxt "Used in email notification"
diff --git a/templates/admin/html-failed-scheduled-action-notice.php b/templates/admin/html-failed-scheduled-action-notice.php
index a4252d9..af4d808 100755
--- a/templates/admin/html-failed-scheduled-action-notice.php
+++ b/templates/admin/html-failed-scheduled-action-notice.php
@@ -9,6 +9,12 @@
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
+// Get the log file URL depending on the log handler (file or database).
+$url = admin_url( sprintf( 'admin.php?page=wc-status&tab=logs&log_file=%s-%s-log', 'failed-scheduled-actions', sanitize_file_name( wp_hash( 'failed-scheduled-actions' ) ) ) );
+
+if ( defined( 'WC_LOG_HANDLER' ) && 'WC_Log_Handler_DB' === WC_LOG_HANDLER ) {
+ $url = admin_url( sprintf( 'admin.php?page=wc-status&tab=logs&source=%s', 'failed-scheduled-actions' ) );
+}
?>
array( 'href' => array() ) ) ); ?>
failed-scheduled-actions',
- '',
+ ' ',
' '
);?>
diff --git a/templates/checkout/subscription-receipt.php b/templates/checkout/subscription-receipt.php
new file mode 100755
index 0000000..7e6a6cc
--- /dev/null
+++ b/templates/checkout/subscription-receipt.php
@@ -0,0 +1,45 @@
+
+
+
+ tags
+ echo wp_kses( sprintf( esc_html__( 'Subscription Number: %s', 'woocommerce-subscriptions' ), '' . esc_html( $subscription->get_order_number() ) . ' ' ), array( 'strong' => true ) );
+ ?>
+
+
+ tags
+ echo wp_kses( sprintf( esc_html__( 'Next Payment Date: %s', 'woocommerce-subscriptions' ), '' . esc_html( $subscription->get_date_to_display( 'next_payment' ) ) . ' ' ), array( 'strong' => true ) );
+ ?>
+
+
+ tags
+ echo wp_kses_post( sprintf( esc_html__( 'Total: %s', 'woocommerce-subscriptions' ), '' . $subscription->get_formatted_order_total() . ' ' ) );
+ ?>
+
+ get_payment_method_title() ) : ?>
+
+ ' . esc_html( $subscription->get_payment_method_to_display() ) . ' ' ), array( 'strong' => true ) );
+ ?>
+
+
+
+
+get_payment_method(), $subscription->get_id() ); ?>
+
+
diff --git a/templates/emails/customer-on-hold-renewal-order.php b/templates/emails/customer-on-hold-renewal-order.php
new file mode 100755
index 0000000..c2623e9
--- /dev/null
+++ b/templates/emails/customer-on-hold-renewal-order.php
@@ -0,0 +1,49 @@
+
+
+
+get_billing_first_name() ) ); ?>
+
+
+id ) {
@@ -31,9 +33,9 @@ if ( 'cancelled_subscription' != $email->id ) {
-
-
-
+
+
+
@@ -47,12 +49,20 @@ if ( 'cancelled_subscription' != $email->id ) {
$i++;
?>
-
-
+
+
get_customer_note() ) {
+ ?>
+
+
+ get_customer_note() ) ); ?>
+
+
diff --git a/templates/emails/plain/customer-on-hold-renewal-order.php b/templates/emails/plain/customer-on-hold-renewal-order.php
new file mode 100755
index 0000000..6c64a95
--- /dev/null
+++ b/templates/emails/plain/customer-on-hold-renewal-order.php
@@ -0,0 +1,50 @@
+get_billing_first_name() ) ) . "\n\n";
+echo esc_html__( 'Thanks for your renewal order. It’s on-hold until we confirm that payment has been received. In the meantime, here’s a reminder of your order:', 'woocommerce-subscriptions' ) . "\n\n";
+
+/*
+ * @hooked WC_Emails::order_details() Shows the order details table.
+ * @hooked WC_Structured_Data::generate_order_data() Generates structured data.
+ * @hooked WC_Structured_Data::output_structured_data() Outputs structured data.
+ * @since 2.5.0
+ */
+do_action( 'woocommerce_subscriptions_email_order_details', $order, $sent_to_admin, $plain_text, $email );
+
+echo "\n----------------------------------------\n\n";
+
+/*
+ * @hooked WC_Emails::order_meta() Shows order meta data.
+ */
+do_action( 'woocommerce_email_order_meta', $order, $sent_to_admin, $plain_text, $email );
+
+/*
+ * @hooked WC_Emails::customer_details() Shows customer details
+ * @hooked WC_Emails::email_address() Shows email address
+ */
+do_action( 'woocommerce_email_customer_details', $order, $sent_to_admin, $plain_text, $email );
+
+echo "\n\n----------------------------------------\n\n";
+
+/**
+ * Show user-defined additional content - this is set in each email's settings.
+ */
+if ( $additional_content ) {
+ echo esc_html( wp_strip_all_tags( wptexturize( $additional_content ) ) );
+ echo "\n\n----------------------------------------\n\n";
+}
+
+echo wp_kses_post( apply_filters( 'woocommerce_email_footer_text', get_option( 'woocommerce_email_footer_text' ) ) );
diff --git a/templates/myaccount/subscription-details.php b/templates/myaccount/subscription-details.php
index fd3b90f..b6d0fc8 100755
--- a/templates/myaccount/subscription-details.php
+++ b/templates/myaccount/subscription-details.php
@@ -37,7 +37,7 @@ if ( ! defined( 'ABSPATH' ) ) {
-
+
diff --git a/woocommerce-subscriptions.php b/woocommerce-subscriptions.php
index ba7700c..a7814d6 100755
--- a/woocommerce-subscriptions.php
+++ b/woocommerce-subscriptions.php
@@ -3,12 +3,12 @@
* Plugin Name: WooCommerce Subscriptions
* Plugin URI: https://www.woocommerce.com/products/woocommerce-subscriptions/
* Description: Sell products and services with recurring payments in your WooCommerce Store.
- * Author: Automattic
+ * Author: WooCommerce
* Author URI: https://woocommerce.com/
- * Version: 2.6.5
+ * Version: 3.0.1
*
* WC requires at least: 3.0.9
- * WC tested up to: 3.8
+ * WC tested up to: 3.9
* Woo: 27147:6115e6d7e297b623a169fdcf5728b224
*
* Copyright 2019 WooCommerce
@@ -27,7 +27,7 @@
* along with this program. If not, see .
*
* @package WooCommerce Subscriptions
- * @author Automattic.
+ * @author WooCommerce.
* @since 1.0
*/
@@ -118,7 +118,7 @@ class WC_Subscriptions {
public static $plugin_file = __FILE__;
- public static $version = '2.6.5';
+ public static $version = '3.0.1';
public static $wc_minimum_supported_version = '3.0';
@@ -377,7 +377,7 @@ class WC_Subscriptions {
'ajax_url' => esc_url( WC()->ajax_url() ),
'subscription_id' => $subscription->get_id(),
'add_payment_method_msg' => __( 'To enable automatic renewals for this subscription, you will first need to add a payment method.', 'woocommerce-subscriptions' ) . "\n\n" . __( 'Would you like to add a payment method now?', 'woocommerce-subscriptions' ),
- 'auto_renew_nonce' => wp_create_nonce( "toggle-auto-renew-{$subscription->get_id()}" ),
+ 'auto_renew_nonce' => WCS_My_Account_Auto_Renew_Toggle::can_user_toggle_auto_renewal( $subscription ) ? wp_create_nonce( "toggle-auto-renew-{$subscription->get_id()}" ) : false,
'add_payment_method_url' => esc_url( $subscription->get_change_payment_method_url() ),
'has_payment_gateway' => $subscription->has_payment_gateway() && wc_get_payment_gateway_by_order( $subscription )->supports( 'subscriptions' ),
);