This commit is contained in:
Prospress Inc
2020-02-27 13:22:28 +01:00
committed by Remco Tolsma
parent d554039476
commit 9bcb1fc839
109 changed files with 6423 additions and 1367 deletions

View File

@@ -0,0 +1,49 @@
/*
* Pre WC 3.3 support for order status admin styles.
*/
.order-status {
display: -webkit-inline-box;
display: -webkit-inline-flex;
display: -ms-inline-flexbox;
display: inline-flex;
line-height: 2.5em;
color: #777;
background: #e5e5e5;
border-radius: 4px;
border-bottom: 1px solid rgba(0,0,0,.05);
margin: -.25em 0;
cursor: inherit !important;
white-space: nowrap;
max-width: 100%;
}
.order-status.status-completed {
background: #c8d7e1;
color: #2e4453;
}
.order-status.status-on-hold {
background: #f8dda7;
color: #94660c;
}
.order-status.status-failed {
background: #eba3a3;
color: #761919;
}
.order-status.status-processing {
background: #c6e1c6;
color: #5b841b;
}
.order-status.status-trash {
background: #eba3a3;
color: #761919;
}
.order-status > span {
margin: 0 1em;
overflow: hidden;
text-overflow: ellipsis;
}

View File

@@ -17,68 +17,31 @@
/* Subscriptions Admin Page */ /* Subscriptions Admin Page */
.post-type-shop_subscription .tablenav input, .post-type-shop_subscription .tablenav input,
.post-type-shop_subscription .tablenav select { .post-type-shop_subscription .tablenav select {
line-height: 32px;
height: 32px; height: 32px;
} }
.post-type-shop_subscription .tablenav .select2-container { .post-type-shop_subscription .tablenav .select2-container {
width: 200px !important; width: 240px !important;
font-size: 14px; font-size: 14px;
vertical-align: middle; vertical-align: middle;
margin: 1px 6px 4px 1px; margin: 1px 6px 4px 1px;
} }
.post-type-shop_subscription .tablenav .select2-selection--single {
height: 32px;
}
.post-type-shop_subscription .tablenav .select2-selection__rendered {
line-height: 29px;
}
.post-type-shop_subscription .tablenav .select2-selection__arrow {
height: 30px;
}
.post-type-shop_subscription .wp-list-table {
margin-top: 1em;
}
.post-type-shop_subscription .widefat .column-status, .post-type-shop_subscription .widefat .column-status,
.post-type-shop_subscription .widefat .column-order_id,
.post-type-shop_subscription .widefat .column-order_title { .post-type-shop_subscription .widefat .column-order_title {
width: 142px; width: 160px;
text-align: left; text-align: left;
} }
.widefat .type-shop_subscription td.column-status {
padding: 6px 7px;
}
.widefat .type-shop_subscription .column-status mark {
display:block;
text-align: center;
white-space: nowrap;
padding: 0 2px;
background: #999;
border: 1px solid #999;
-webkit-box-shadow:inset 0 0 2px 1px rgba(255,255,255,0.5);
-webkit-border-radius:4px;
-moz-border-radius:4px;
-o-border-radius:4px;
border-radius:4px;
margin: 0;
font-size:9px;
text-transform: uppercase;
color:#fff;
font-weight: bold;
text-shadow:0 1px 0 rgba(0,0,0,0.3);
}
.widefat .type-shop_subscription .column-status mark.active {
background-color: #339933;
border-color: #339933;
}
.widefat .type-shop_subscription .column-status mark.expired {
background-color: #A0658B;
border-color: #A0658B;
}
.widefat .type-shop_subscription .column-status mark.on-hold {
background-color: #E66F00;
border-color: #E66F00;
}
.widefat .type-shop_subscription .column-status mark.failed {
background-color: red;
border-color: red;
}
.widefat .type-shop_subscription .column-status mark.cancelled {
background-color: #ccc;
border-color: #ccc;
}
.widefat .type-shop_subscription .column-status mark.processing {
background-color: #2184c2;
border-color: #2184c2;
}
/* Product List table */ /* Product List table */
table.wp-list-table span.product-type.variable-subscription { table.wp-list-table span.product-type.variable-subscription {
background-position: -48px 0; background-position: -48px 0;
@@ -192,11 +155,6 @@ a.close-subscriptions-search {
margin: 0; margin: 0;
} }
.subscription_pricing ._subscription_price_field input[type=text],
.subscription_pricing ._subscription_trial_length_field input[type=text] {
padding: 4px;
}
#woocommerce-product-data .wc-metaboxes-wrapper .wc-metabox table td p._subscription_trial_period_field select { #woocommerce-product-data .wc-metaboxes-wrapper .wc-metabox table td p._subscription_trial_period_field select {
margin-left: 5px; margin-left: 5px;
} }
@@ -234,7 +192,6 @@ a.close-subscriptions-search {
.wc-metaboxes-wrapper .wc_input_subscription_payment_sync_day, .wc-metaboxes-wrapper .wc_input_subscription_payment_sync_day,
.wc-metaboxes-wrapper .wc_input_subscription_payment_sync_month { .wc-metaboxes-wrapper .wc_input_subscription_payment_sync_month {
padding: 4px 6px; padding: 4px 6px;
height: 31px;
} }
.variable_subscription_trial .form-row input[type=text], .variable_subscription_trial .form-row input[type=text],
@@ -242,27 +199,27 @@ a.close-subscriptions-search {
.variable_subscription_trial .form-row select, .variable_subscription_trial .form-row select,
.variable_subscription_pricing .form-row select { .variable_subscription_pricing .form-row select {
margin: 2px 0 0; margin: 2px 0 0;
padding: 6px; padding: 5px;
} }
/* Variation Pricing Fields in WooCommerce 2.3+ */ /* Variation Pricing Fields in WooCommerce 2.3+ */
.variable_subscription_pricing_2_3 .wc_input_subscription_price, #variable_product_options .variable_subscription_pricing_2_3 .wc_input_subscription_price,
.variable_subscription_pricing_2_3 .wc_input_subscription_period_interval { #variable_product_options .variable_subscription_pricing_2_3 .wc_input_subscription_period_interval {
max-width: 33%; max-width: 33%;
float: left; float: left;
} }
.variable_subscription_pricing_2_3 .wc_input_subscription_price { .variable_subscription_pricing_2_3 .wc_input_subscription_price {
clear: left; clear: left;
} }
.variable_subscription_pricing_2_3 .wc_input_subscription_period { #variable_product_options .variable_subscription_pricing_2_3 .wc_input_subscription_period {
max-width: 34%; max-width: 34%;
float: right; float: right;
} }
.variable_subscription_pricing_2_3.variable_subscription_trial p.form-row { .variable_subscription_pricing_2_3.variable_subscription_trial p.form-row {
margin-bottom: 0; margin-bottom: 0;
} }
.variable_subscription_pricing_2_3 .wc_input_subscription_trial_period, #variable_product_options .variable_subscription_pricing_2_3 .wc_input_subscription_trial_period,
.variable_subscription_pricing_2_3 .wc_input_subscription_trial_length { #variable_product_options .variable_subscription_pricing_2_3 .wc_input_subscription_trial_length {
max-width: 50%; max-width: 50%;
} }
.variable_subscription_pricing_2_3 .wc_input_subscription_trial_period { .variable_subscription_pricing_2_3 .wc_input_subscription_trial_period {
@@ -272,27 +229,27 @@ a.close-subscriptions-search {
.variable_subscription_pricing_2_3 .variable_subscription_trial_sign_up { .variable_subscription_pricing_2_3 .variable_subscription_trial_sign_up {
clear: both; clear: both;
} }
.variable_subscription_pricing_2_3 .wc_input_subscription_payment_sync_day { #variable_product_options .variable_subscription_pricing_2_3 .wc_input_subscription_payment_sync_day {
max-width: 13%; max-width: 13%;
float: right; float: right;
} }
.variable_subscription_pricing_2_3 .wc_input_subscription_payment_sync_month { #variable_product_options .variable_subscription_pricing_2_3 .wc_input_subscription_payment_sync_month {
max-width: 86%; max-width: 86%;
} }
@media screen and (max-width: 1190px) { @media screen and (max-width: 1190px) {
.variable_subscription_pricing_2_3 p._subscription_price_field, #variable_product_options .variable_subscription_pricing_2_3 p._subscription_price_field,
.variable_subscription_pricing_2_3 p._subscription_length_field { #variable_product_options .variable_subscription_pricing_2_3 p._subscription_length_field {
width: 100%; width: 100%;
} }
.variable_subscription_pricing_2_3 p._subscription_price_field { #variable_product_options .variable_subscription_pricing_2_3 p._subscription_price_field {
width: 100%; width: 100%;
margin-bottom: 0; margin-bottom: 0;
} }
.variable_subscription_pricing_2_3 .wc_input_subscription_payment_sync_day { #variable_product_options .variable_subscription_pricing_2_3 .wc_input_subscription_payment_sync_day {
max-width: 20%; max-width: 20%;
float: right; float: right;
} }
.variable_subscription_pricing_2_3 .wc_input_subscription_payment_sync_month { #variable_product_options .variable_subscription_pricing_2_3 .wc_input_subscription_payment_sync_month {
max-width: 78%; max-width: 78%;
} }
} }
@@ -567,12 +524,13 @@ table.wp-list-table .subscription_renewal_order:after {
table.wp-list-table .subscription_renewal_order{ table.wp-list-table .subscription_renewal_order{
margin: 0; margin: 0;
} }
}
@media only screen and (max-width: 782px) {
table.wp-list-table .column-subscription_relationship { table.wp-list-table .column-subscription_relationship {
text-align: inherit; text-align: inherit;
} }
#variable_product_options select {
height: auto;
line-height: 2;
}
} }
/* WooCommerce Payment Methods Settings page */ /* WooCommerce Payment Methods Settings page */
@@ -667,3 +625,15 @@ span.product-type.variable-subscription:before {
font-family: dashicons; font-family: dashicons;
content: "\f504"; content: "\f504";
} }
.subscription-status.status-active {
background: #c6e1c6;
color: #5b841b;
}
.subscription-status.status-expired {
background: #bd94af;
color: #724663;
}
.subscription-status.status-pending-cancel {
background: #bfbfbf;
color: #737373;
}

View File

@@ -43,15 +43,26 @@
border-right: 1px solid #ececec; border-right: 1px solid #ececec;
} }
@media (max-width: 1685px) and (min-width: 1485px), #woocommerce_dashboard_status .wc_status_list li.renewal-count a,
#woocommerce_dashboard_status .wc_status_list li.renewal-revenue a,
#woocommerce_dashboard_status .wc_status_list li.signup-count a,
#woocommerce_dashboard_status .wc_status_list li.signup-revenue a,
#woocommerce_dashboard_status .wc_status_list li.cancel-count a {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
@media (max-width: 1706px) and (min-width: 1485px),
(max-width: 2193px) and (min-width: 1936px), (max-width: 2193px) and (min-width: 1936px),
(max-width: 1179px) and (min-width: 1052px), (max-width: 1200px) and (min-width: 1052px),
(max-width: 960px) { (max-width: 960px) {
#woocommerce_dashboard_status .wc_status_list li.renewal-count, #woocommerce_dashboard_status .wc_status_list li.renewal-count,
#woocommerce_dashboard_status .wc_status_list li.renewal-revenue, #woocommerce_dashboard_status .wc_status_list li.renewal-revenue,
#woocommerce_dashboard_status .wc_status_list li.signup-count, #woocommerce_dashboard_status .wc_status_list li.signup-count,
#woocommerce_dashboard_status .wc_status_list li.signup-revenue, #woocommerce_dashboard_status .wc_status_list li.signup-revenue,
#woocommerce_dashboard_status .wc_status_list li.cancel-count { #woocommerce_dashboard_status .wc_status_list li.cancel-count {
width: 100% border-right: none;
width: 100%;
} }
} }

View File

@@ -21,7 +21,10 @@ jQuery(document).ready(function($){
} }
}); });
// Make sure date pickers are in the future // Make sure start date picker is in the past
$( '.woocommerce-subscriptions.date-picker#start' ).datepicker( 'option','maxDate',moment().toDate());
// Make sure other date pickers are in the future
$( '.woocommerce-subscriptions.date-picker:not(#start)' ).datepicker( 'option','minDate',moment().add(1,'hours').toDate()); $( '.woocommerce-subscriptions.date-picker:not(#start)' ).datepicker( 'option','minDate',moment().add(1,'hours').toDate());
// Validate date when hour/minute inputs change // Validate date when hour/minute inputs change
@@ -58,6 +61,18 @@ jQuery(document).ready(function($){
seconds: one_hour_from_now.format( 'ss' ) seconds: one_hour_from_now.format( 'ss' )
}); });
// Make sure start date is before now.
if ( 'start' == date_type ) {
if ( false === chosen_date.isBefore( time_now ) ) {
alert( wcs_admin_meta_boxes.i18n_start_date_notice );
$date_input.val( time_now.year() + '-' + ( zeroise( time_now.months() + 1 ) ) + '-' + ( time_now.format( 'DD' ) ) );
$hour_input.val( time_now.format( 'HH' ) );
$minute_input.val( time_now.format( 'mm' ) );
}
}
// Make sure trial end and next payment are after start date // Make sure trial end and next payment are after start date
if ( ( 'trial_end' == date_type || 'next_payment' == date_type ) && '' != $( '#start_timestamp_utc' ).val() ) { if ( ( 'trial_end' == date_type || 'next_payment' == date_type ) && '' != $( '#start_timestamp_utc' ).val() ) {
var change_date = false, var change_date = false,

View File

@@ -123,8 +123,13 @@ jQuery( document ).ready( function( $ ) {
}); });
} }
// Don't display the modal for manual subscriptions, they will need to renew via the checkout. // Don't display the early renewal modal for manual subscriptions, they will need to renew via the checkout.
function shouldShowEarlyRenewalModal() { function shouldShowEarlyRenewalModal( event ) {
// We're only interested in requests to show the early renewal modal.
if ( '.subscription_renewal_early' !== $( event.modal ).data( 'modal-trigger' ) ) {
return;
}
return $paymentMethod.data( 'is_manual' ) === 'no'; return $paymentMethod.data( 'is_manual' ) === 'no';
}; };

View File

@@ -1,5 +1,33 @@
*** WooCommerce Subscriptions Changelog *** *** WooCommerce Subscriptions Changelog ***
2020.01.17 - version 3.0.1
* Fix: Support multiple modals on the customer's view subscription page. Fixes an issue where preventing the early renewal modal being displayed was preventing all modals on the page from being displayed. PR#3571
* Fix: Silence PHP warning in events by date report caused by empty set of data. PR#3577
* Fix: [WC3.7] Copy the rate percent meta to tax line items during renewal meta copy. PR#3578
* Fix: Introduce a user permissions check for the auto-renewal toggle. PR#3579
* Fix: Update Action Scheduler library to 3.0.1. This release includes a database tables schema version bump. PR#3593
2020.01.06 - version 3.0.0
* New: Update Action Scheduler to 3.0.
* New: Apply WC styling to subscription statuses, subscription related order and retry meta table statuses. PR#3467, PR#3506
* New: Introduce new Renewal Order On-hold Emails. PR#3475
* Fix: Display gateway specific errors on the subscription change payment method page. PR#3278
* Fix: Order the results from WCS_Retry_Manager::store()->get_retries() correctly according to the orderby arg. Previously this function would always return results ordered by ascending ID. PR#3498
* Fix: Send customer Renewal Order Processing Emails on the correct status transitions. PR#3475
* Fix: Only update the subscription status once when processing $0 renewals orders. Fixes race condition caused by updating two instances of the same order. PR#3531
* Fix: Adjust admin CSS and data metabox for recent changes in WP and WC. PR#3540
* Fix: Fix admin notice error link for failed scheduled action when using WC_Log_Handler_DB. PR#3544
* Fix: Correctly calculate inclusive line item taxes when paying for manual renewal orders. PR#3545
* Fix: Add customer note details to renewal order email templates. PR#3536
* Fix: Validate the subscription start date during admin manual subscription creation. PR#3556
* Fix: Only display the WC Subscriptions activation notice on sites without a subscription product. PR#3558
* Fix: [WC 3.9] Ensure WCS_Retry_Manager::check_order_statuses_for_payment() has default value for the $order parameter. PR3565
* Fix: [WP 5.3] Fix variable subscription product admin field CSS. PR#3564
* Tweak: [WooCommerce dashboard widget] tweak media screen size breakpoints to avoid misalignment issues. PR#3553
* Tweak: Use product object rather than ID when validating mixed checkout setting. Improves compatibility with plugins like Mix and Match and Product Bundles. PR#3551
* Tweak: Display the cart and checkout recurring totals included taxes in a more readable way. PR#3546
* Dev: Allow 3rd party developers using the 'woocommerce_subscriptions_allow_switching_options' filter to add tooltip content. PR#3542
2019.11.14 - version 2.6.5 2019.11.14 - version 2.6.5
* Fix: Account for prorated switch sign up fees in multi-switches. PR#3519 * Fix: Account for prorated switch sign up fees in multi-switches. PR#3519
* Fix: Tooltip content displayed on WooCommerce > Subscriptions administration screen. * Fix: Tooltip content displayed on WooCommerce > Subscriptions administration screen.

View File

@@ -4,7 +4,7 @@
* *
* Provide APIs for a repair script to find objects which need repairing, schedule a separate background process for each object using Action Scheduler, and then in that background process update data for that object. * Provide APIs for a repair script to find objects which need repairing, schedule a separate background process for each object using Action Scheduler, and then in that background process update data for that object.
* *
* @author Automattic * @author WooCommerce
* @category Admin * @category Admin
* @package WooCommerce Subscriptions/Admin/Upgrades * @package WooCommerce Subscriptions/Admin/Upgrades
* @since 2.6.0 * @since 2.6.0

View File

@@ -889,9 +889,12 @@ class WC_Subscriptions_Admin {
$woocommerce_plugin_dir_file = self::get_woocommerce_plugin_dir_file(); $woocommerce_plugin_dir_file = self::get_woocommerce_plugin_dir_file();
if ( ! empty( $woocommerce_plugin_dir_file ) ) { // check if subscription products exist in the store
$subscription_product = wc_get_products( array( 'type' => array( 'subscription', 'variable-subscription' ), 'limit' => 1, 'return' => 'ids' ) );
wp_enqueue_style( 'woocommerce-activation', plugins_url( '/assets/css/activation.css', self::get_woocommerce_plugin_dir_file() ), array(), WC_Subscriptions::$version ); if ( ! empty( $woocommerce_plugin_dir_file ) && 0 == count( $subscription_product ) ) {
wp_enqueue_style( 'woocommerce-activation', plugins_url( '/assets/css/activation.css', $woocommerce_plugin_dir_file ), array(), WC_Subscriptions::$version );
if ( ! isset( $_GET['page'] ) || 'wcs-about' != $_GET['page'] ) { if ( ! isset( $_GET['page'] ) || 'wcs-about' != $_GET['page'] ) {
add_action( 'admin_notices', __CLASS__ . '::admin_installed_notice' ); add_action( 'admin_notices', __CLASS__ . '::admin_installed_notice' );
@@ -905,6 +908,9 @@ class WC_Subscriptions_Admin {
wp_enqueue_style( 'woocommerce_subscriptions_admin', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/css/admin.css', array( 'woocommerce_admin_styles' ), WC_Subscriptions::$version ); wp_enqueue_style( 'woocommerce_subscriptions_admin', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/css/admin.css', array( 'woocommerce_admin_styles' ), WC_Subscriptions::$version );
} }
if ( in_array( $screen->id, array( 'shop_order', 'edit-shop_subscription', 'shop_subscription' ) ) && WC_Subscriptions::is_woocommerce_pre( '3.3' ) ) {
wp_enqueue_style( 'wc_subscriptions_statuses_admin', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/css/admin-order-statuses.css', array( 'woocommerce_admin_styles' ), WC_Subscriptions::$version );
}
} }
/** /**

View File

@@ -450,7 +450,7 @@ class WCS_Admin_Post_Types {
switch ( $column ) { switch ( $column ) {
case 'status' : case 'status' :
// The status label // The status label
$column_content = sprintf( '<mark class="%s tips" data-tip="%s">%s</mark>', sanitize_title( $the_subscription->get_status() ), wcs_get_subscription_status_name( $the_subscription->get_status() ), wcs_get_subscription_status_name( $the_subscription->get_status() ) ); $column_content = sprintf( '<mark class="subscription-status order-status status-%1$s %1$s tips" data-tip="%2$s"><span>%3$s</span></mark>', sanitize_title( $the_subscription->get_status() ), wcs_get_subscription_status_name( $the_subscription->get_status() ), wcs_get_subscription_status_name( $the_subscription->get_status() ) );
$post_type_object = get_post_type_object( $post->post_type ); $post_type_object = get_post_type_object( $post->post_type );

View File

@@ -7,7 +7,7 @@
* @author Prospress * @author Prospress
* @category Admin * @category Admin
* @package WooCommerce Subscriptions/Admin/Meta Boxes * @package WooCommerce Subscriptions/Admin/Meta Boxes
* @version 2.0 * @version 3.0.0
*/ */
if ( ! defined( 'ABSPATH' ) ) { if ( ! defined( 'ABSPATH' ) ) {
@@ -49,6 +49,7 @@ class WCS_Meta_Box_Subscription_Data extends WC_Meta_Box_Order_Data {
<div class="order_data_column_container"> <div class="order_data_column_container">
<div class="order_data_column"> <div class="order_data_column">
<h3><?php esc_html_e( 'General', 'woocommerce-subscriptions' ); ?></h3>
<p class="form-field form-field-wide wc-customer-user"> <p class="form-field form-field-wide wc-customer-user">
<label for="customer_user"><?php esc_html_e( 'Customer:', 'woocommerce-subscriptions' ) ?> <?php <label for="customer_user"><?php esc_html_e( 'Customer:', 'woocommerce-subscriptions' ) ?> <?php
@@ -58,14 +59,14 @@ class WCS_Meta_Box_Subscription_Data extends WC_Meta_Box_Order_Data {
'post_type' => 'shop_subscription', 'post_type' => 'shop_subscription',
'_customer_user' => absint( $subscription->get_user_id() ), '_customer_user' => absint( $subscription->get_user_id() ),
); );
printf( '<a href="%s">%s &rarr;</a>', printf( '<a href="%s">%s</a>',
esc_url( add_query_arg( $args, admin_url( 'edit.php' ) ) ), esc_url( add_query_arg( $args, admin_url( 'edit.php' ) ) ),
esc_html__( 'View other subscriptions', 'woocommerce-subscriptions' ) esc_html__( 'View other subscriptions &rarr;', 'woocommerce-subscriptions' )
); );
printf( printf(
'<a href="%s">%s</a>', '<a href="%s">%s</a>',
esc_url( add_query_arg( 'user_id', $subscription->get_user_id(), admin_url( 'user-edit.php' ) ) ), esc_url( add_query_arg( 'user_id', $subscription->get_user_id(), admin_url( 'user-edit.php' ) ) ),
esc_html__( 'Profile', 'woocommerce-subscriptions' ) esc_html__( 'Profile &rarr;', 'woocommerce-subscriptions' )
); );
} }
?></label> ?></label>
@@ -90,7 +91,7 @@ class WCS_Meta_Box_Subscription_Data extends WC_Meta_Box_Order_Data {
<p class="form-field form-field-wide"> <p class="form-field form-field-wide">
<label for="order_status"><?php esc_html_e( 'Subscription status:', 'woocommerce-subscriptions' ); ?></label> <label for="order_status"><?php esc_html_e( 'Subscription status:', 'woocommerce-subscriptions' ); ?></label>
<select id="order_status" name="order_status"> <select id="order_status" name="order_status" class="wc-enhanced-select">
<?php <?php
$statuses = wcs_get_subscription_statuses(); $statuses = wcs_get_subscription_statuses();
foreach ( $statuses as $status => $status_name ) { foreach ( $statuses as $status => $status_name ) {
@@ -130,9 +131,11 @@ class WCS_Meta_Box_Subscription_Data extends WC_Meta_Box_Order_Data {
</div> </div>
<div class="order_data_column"> <div class="order_data_column">
<h3> <h3>
<?php esc_html_e( 'Billing Details', 'woocommerce-subscriptions' ); ?> <?php esc_html_e( 'Billing', 'woocommerce-subscriptions' ); ?>
<a href="#" class="edit_address"><?php esc_html_e( 'Edit', 'woocommerce-subscriptions' ); ?></a> <a href="#" class="edit_address"><?php esc_html_e( 'Edit', 'woocommerce-subscriptions' ); ?></a>
<a href="#" class="tips load_customer_billing" data-tip="<?php esc_attr_e( 'Load billing address', 'woocommerce-subscriptions' ); ?>" style="display:none;"><?php esc_html_e( 'Load billing address', 'woocommerce-subscriptions' ); ?></a> <span>
<a href="#" class="load_customer_billing" style="display:none;"><?php esc_html_e( 'Load billing address', 'woocommerce-subscriptions' ); ?></a>
</span>
</h3> </h3>
<?php <?php
// Display values // Display values
@@ -218,10 +221,12 @@ class WCS_Meta_Box_Subscription_Data extends WC_Meta_Box_Order_Data {
<div class="order_data_column"> <div class="order_data_column">
<h3> <h3>
<?php esc_html_e( 'Shipping Details', 'woocommerce-subscriptions' ); ?> <?php esc_html_e( 'Shipping', 'woocommerce-subscriptions' ); ?>
<a href="#" class="edit_address"><?php esc_html_e( 'Edit', 'woocommerce-subscriptions' ); ?></a> <a href="#" class="edit_address"><?php esc_html_e( 'Edit', 'woocommerce-subscriptions' ); ?></a>
<a href="#" class="tips billing-same-as-shipping" data-tip="<?php esc_attr_e( 'Copy from billing', 'woocommerce-subscriptions' ); ?>" style="display:none;"><?php esc_html_e( 'Copy from billing', 'woocommerce-subscriptions' ); ?></a> <span>
<a href="#" class="tips load_customer_shipping" data-tip="<?php esc_attr_e( 'Load shipping address', 'woocommerce-subscriptions' ); ?>" style="display:none;"><?php esc_html_e( 'Load shipping address', 'woocommerce-subscriptions' ); ?></a> <a href="#" class="load_customer_shipping" style="display:none;"><?php esc_html_e( 'Load shipping address', 'woocommerce-subscriptions' ); ?></a>
<a href="#" class="billing-same-as-shipping" style="display:none;"><?php esc_html_e( 'Copy billing address', 'woocommerce-subscriptions' ); ?></a>
</span>
</h3> </h3>
<?php <?php
// Display values // Display values

View File

@@ -38,11 +38,19 @@ $order_post = wcs_get_objects_property( $order, 'post' );
</td> </td>
<td> <td>
<?php <?php
$classes = array(
'order-status',
sanitize_html_class( 'status-' . $order->get_status() ),
);
if ( wcs_is_subscription( $order ) ) { 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 { } else {
echo esc_html( wc_get_order_status_name( $order->get_status( 'view' ) ) ); $status_name = wc_get_order_status_name( $order->get_status() );
} }
printf( '<mark class="%s"><span>%s</span></mark>', esc_attr( implode( ' ', $classes ) ), esc_html( $status_name ) );
?> ?>
</td> </td>
<td> <td>

View File

@@ -53,12 +53,22 @@ if ( ! defined( 'ABSPATH' ) ) {
<td> <td>
<?php echo esc_html( ucwords( $retry->get_status() ) ); ?> <?php echo esc_html( ucwords( $retry->get_status() ) ); ?>
</td> </td>
<?php
foreach ( array( 'order', 'subscription' ) as $object_type ) :
$status = $rule->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;
?>
<td> <td>
<?php echo esc_html( ucwords( $rule->get_status_to_apply( 'order' ) ) ); ?> <mark class="<?php echo esc_attr( implode( ' ', $css_classes ) ); ?>"><span><?php echo esc_html( $status_name ); ?></span></mark>
</td>
<td>
<?php echo esc_html( ucwords( $rule->get_status_to_apply( 'subscription' ) ) ); ?>
</td> </td>
<?php endforeach; ?>
<td> <td>
<?php $email_class = $rule->get_email_template(); ?> <?php $email_class = $rule->get_email_template(); ?>
<?php if ( ! empty( $email_class ) && class_exists( $email_class ) ) : ?> <?php if ( ! empty( $email_class ) && class_exists( $email_class ) ) : ?>

View File

@@ -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. // 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( $legend[] = array(
'title' => sprintf( __( '%2$s %1$s current subscriptions', 'woocommerce-subscriptions' ), '<strong> <span class="woocommerce-subscriptions-count count">' . $this->report_data->total_subscriptions_at_period_end . '</strong> </a>', 'title' => sprintf( __( '%2$s %1$s current subscriptions', 'woocommerce-subscriptions' ), '<strong> <span class="woocommerce-subscriptions-count count">' . $this->report_data->total_subscriptions_at_period_end . '</strong> </a>',

View File

@@ -69,9 +69,9 @@ class WC_Subscriptions_Cart_Validator {
// Redirect to cart page to remove subscription & notify shopper // Redirect to cart page to remove subscription & notify shopper
if ( WC_Subscriptions::is_woocommerce_pre( '3.0.8' ) ) { 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 { } 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 ) { 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 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 // remove the subscriptions from the cart
WC_Subscriptions_Cart::remove_subscriptions_from_cart(); WC_Subscriptions_Cart::remove_subscriptions_from_cart();
@@ -115,9 +113,11 @@ class WC_Subscriptions_Cart_Validator {
} else { } else {
add_filter( 'woocommerce_add_to_cart_fragments', array( 'WC_Subscriptions', 'redirect_ajax_add_to_cart' ) ); add_filter( 'woocommerce_add_to_cart_fragments', array( 'WC_Subscriptions', 'redirect_ajax_add_to_cart' ) );
} }
break; break;
} }
} }
return $cart; return $cart;
} }

View File

@@ -12,11 +12,12 @@ class WC_Subscriptions_Change_Payment_Gateway {
public static $is_request_to_change_payment = false; public static $is_request_to_change_payment = false;
private static $woocommerce_messages = array(); /**
* An internal cache of WooCommerce customer notices.
private static $woocommerce_errors = array(); *
* @var array
private static $original_order_dates = array(); */
private static $notices = array();
/** /**
* Bootstraps the class and hooks required actions & filters. * 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' ); add_action( 'woocommerce_loaded', __CLASS__ . '::attach_dependant_hooks' );
// Keep a record of any messages or errors that should be displayed // 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 // Hijack the default pay shortcode
add_action( 'after_woocommerce_pay', __CLASS__ . '::maybe_replace_pay_shortcode', 100 ); 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 * @since 2.3.6
*/ */
public static function store_pay_shortcode_messages() { public static function store_pay_shortcode_messages() {
if ( wc_notice_count( 'notice' ) > 0 ) { self::$notices = wc_get_notices();
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' );
}
} }
/** /**
@@ -144,23 +138,35 @@ class WC_Subscriptions_Change_Payment_Gateway {
global $wp; global $wp;
$valid_request = false; $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. // 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'] ) ) ) { 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();
do_action( 'before_woocommerce_pay' ); // Because we've cleared the buffer, we need to re-include the opening container div.
echo '<div class="woocommerce">';
$subscription_key = isset( $_GET['key'] ) ? wc_clean( $_GET['key'] ) : ''; // 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 = wcs_get_subscription( absint( $wp->query_vars['order-pay'] ) );
$subscription_key = isset( $_GET['key'] ) ? wc_clean( $_GET['key'] ) : '';
do_action( 'before_woocommerce_pay' );
/** /**
* wcs_before_replace_pay_shortcode * wcs_before_replace_pay_shortcode
* *
* Action that allows payment methods to modify the subscription object so, for example, * 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 * @since 2.4.0
* *
@@ -168,93 +174,28 @@ class WC_Subscriptions_Change_Payment_Gateway {
*/ */
do_action( 'wcs_before_replace_pay_shortcode', $subscription ); do_action( 'wcs_before_replace_pay_shortcode', $subscription );
if ( $subscription->get_id() == absint( $wp->query_vars['order-pay'] ) && $subscription->get_order_key() == $subscription_key ) { if ( $subscription && $subscription->get_id() === absint( $wp->query_vars['order-pay'] ) && $subscription->get_order_key() === $subscription_key ) {
WCS_Template_Loader::get_subscription_receipt_template( $subscription );
?>
<div class="woocommerce">
<ul class="order_details">
<li class="order">
<?php
// translators: placeholder is the subscription order number wrapped in <strong> tags
echo wp_kses( sprintf( esc_html__( 'Subscription Number: %s', 'woocommerce-subscriptions' ), '<strong>' . esc_html( $subscription->get_order_number() ) . '</strong>' ), array( 'strong' => true ) );
?>
</li>
<li class="date">
<?php
// translators: placeholder is the subscription's next payment date (either human readable or normal date) wrapped in <strong> tags
echo wp_kses( sprintf( esc_html__( 'Next Payment Date: %s', 'woocommerce-subscriptions' ), '<strong>' . esc_html( $subscription->get_date_to_display( 'next_payment' ) ) . '</strong>' ), array( 'strong' => true ) );
?>
</li>
<li class="total">
<?php
// translators: placeholder is the formatted total to be paid for the subscription wrapped in <strong> tags
echo wp_kses_post( sprintf( esc_html__( 'Total: %s', 'woocommerce-subscriptions' ), '<strong>' . $subscription->get_formatted_order_total() . '</strong>' ) );
?>
</li>
<?php if ( $subscription->get_payment_method_title() ) : ?>
<li class="method">
<?php
// translators: placeholder is the display name of the payment method
echo wp_kses( sprintf( esc_html__( 'Payment Method: %s', 'woocommerce-subscriptions' ), '<strong>' . esc_html( $subscription->get_payment_method_to_display() ) . '</strong>' ), array( 'strong' => true ) );
?>
</li>
<?php endif; ?>
</ul>
<?php do_action( 'woocommerce_receipt_' . $subscription->get_payment_method(), $subscription->get_id() ); ?>
<div class="clear"></div>
<?php
} else { } 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 { } 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 ) {
do_action( 'before_woocommerce_pay' ); foreach ( $notices as $notice ) {
wc_add_notice( $notice, $notice_type );
echo '<div class="woocommerce">';
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'] ) ); $subscription = wcs_get_subscription( absint( $_GET['change_payment_method'] ) );
$valid_request = self::validate_change_payment_request( $subscription );
if ( wp_verify_nonce( $_GET['_wpnonce'] ) === false ) { // WC display notices on this hook so trigger it after all notices have been added,
do_action( 'before_woocommerce_pay' );
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 ) { if ( $subscription->get_time( 'next_payment' ) > 0 ) {
// translators: placeholder is next payment's date // 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' ) ); $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..." // 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_notice( sprintf( __( 'Choose a new payment method.%s', 'woocommerce-subscriptions' ), $next_payment_string ), 'notice' );
wc_print_notices();
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(); if ( $subscription_address ) {
$subscription_billing_state = $subscription->get_billing_state(); WC()->customer->{"set_billing_$address_property"}( $subscription_address );
$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_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/' ); 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' );
}
} }
} }
@@ -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. * Add a "Change Payment Method" button to the "My Subscriptions" table.
* *
@@ -697,8 +652,8 @@ class WC_Subscriptions_Change_Payment_Gateway {
return false; return false;
} }
// If there's no recurring payment, there's no need to add or update the payment method. // 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() == 0 ) { if ( $subscription->get_total( 'edit' ) == 0 ) {
return false; return false;
} }

View File

@@ -40,6 +40,7 @@ class WC_Subscriptions_Email {
$email_classes['WCS_Email_New_Switch_Order'] = new WCS_Email_New_Switch_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_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_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_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_Customer_Renewal_Invoice'] = new WCS_Email_Customer_Renewal_Invoice();
$email_classes['WCS_Email_Cancelled_Subscription'] = new WCS_Email_Cancelled_Subscription(); $email_classes['WCS_Email_Cancelled_Subscription'] = new WCS_Email_Cancelled_Subscription();
@@ -67,13 +68,26 @@ class WC_Subscriptions_Email {
add_action( 'woocommerce_subscriptions_switch_completed', __CLASS__ . '::send_switch_order_email', 10 ); add_action( 'woocommerce_subscriptions_switch_completed', __CLASS__ . '::send_switch_order_email', 10 );
$order_email_actions = array( $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_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_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', '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_generated_manual_renewal_order',
'woocommerce_order_status_failed', 'woocommerce_order_status_failed',
); );
@@ -318,7 +332,7 @@ class WC_Subscriptions_Email {
$hook = current_filter(); $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 ); add_action( $hook, array( 'WC_Emails', 'queue_transactional_email' ), $priority, $accepted_args );
} else { } else {
add_action( $hook, array( 'WC_Emails', 'send_transactional_email' ), $priority, $accepted_args ); add_action( $hook, array( 'WC_Emails', 'send_transactional_email' ), $priority, $accepted_args );

View File

@@ -125,11 +125,7 @@ class WC_Subscriptions_Manager {
} }
if ( 0 == $renewal_order->get_total() ) { if ( 0 == $renewal_order->get_total() ) {
$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.
$renewal_order->payment_complete();
$subscription->update_status( 'active' ); // don't call payment_complete() because technically, no payment was received
} else { } else {
if ( $subscription->is_manual() ) { if ( $subscription->is_manual() ) {

View File

@@ -509,7 +509,10 @@ class WC_Subscriptions_Switcher {
$name = WC_Subscriptions_Admin::$option_prefix . '_allow_switching_' . $option['id']; $name = WC_Subscriptions_Admin::$option_prefix . '_allow_switching_' . $option['id'];
$value = get_option( $name, 'no' ); $value = get_option( $name, 'no' );
echo sprintf( '<label><input%s type="checkbox" name="%s" value="1"/> %s</label>', checked( $value, 'yes', false ), esc_attr( $name ), esc_html( $label ) ); echo '<label>';
echo sprintf( '<input%s type="checkbox" name="%s" value="1"/> %s', checked( $value, 'yes', false ), esc_attr( $name ), esc_html( $label ) );
echo isset( $option['desc_tip'] ) ? wcs_help_tip( $option['desc_tip'], true ) : '';
echo '</label>';
} }
?> ?>
</div> </div>

View File

@@ -423,7 +423,7 @@ class WCS_Cart_Renewal {
$price = $item_to_renew['line_subtotal']; $price = $item_to_renew['line_subtotal'];
if ( $_product->is_taxable() && $subscription->get_prices_include_tax() ) { 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'] ); $_product->set_price( $price / $item_to_renew['qty'] );

View File

@@ -6,7 +6,7 @@
* *
* @package WooCommerce Subscriptions * @package WooCommerce Subscriptions
* @category Class * @category Class
* @author Automattic * @author WooCommerce
* @since 2.6.0 * @since 2.6.0
*/ */

View File

@@ -62,6 +62,24 @@ class WCS_My_Account_Auto_Renew_Toggle {
return true; 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 * Disable auto renewal of subscription
* *
@@ -78,7 +96,7 @@ class WCS_My_Account_Auto_Renew_Toggle {
$subscription = wcs_get_subscription( $subscription_id ); $subscription = wcs_get_subscription( $subscription_id );
if ( $subscription ) { if ( $subscription && self::can_user_toggle_auto_renewal( $subscription ) ) {
$subscription->set_requires_manual_renewal( true ); $subscription->set_requires_manual_renewal( true );
$subscription->save(); $subscription->save();
@@ -102,7 +120,7 @@ class WCS_My_Account_Auto_Renew_Toggle {
$subscription = wcs_get_subscription( $subscription_id ); $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->set_requires_manual_renewal( false );
$subscription->save(); $subscription->save();

View File

@@ -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 * Adds any extra status that may be needed for a given order to check if it may
* need payment * need payment
* *
* @param Array $statuses * @param array $statuses
* @param WC_Order $order * @param WC_Order $order
* @return array * @return array
* @since 2.2.1 * @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' ) ); $last_retry = self::store()->get_last_retry_for_order( wcs_get_objects_property( $order, 'id' ) );
if ( $last_retry ) { if ( $last_retry ) {

View File

@@ -174,7 +174,7 @@ class WCS_Switch_Totals_Calculator {
/** /**
* Allow third-parties to filter the switch item and its properties. * 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 WCS_Switch_Cart_Item $switch_item The switch item.
* @param array $cart_item The item in the cart the switch item was created for. * @param array $cart_item The item in the cart the switch item was created for.

View File

@@ -88,4 +88,15 @@ class WCS_Template_Loader {
add_action( 'woocommerce_order_item_meta_end', 'WC_Subscriptions_Switcher::print_switch_link', 10, 3 ); 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/' );
}
} }

View File

@@ -0,0 +1,105 @@
<?php
defined( 'ABSPATH' ) || exit; // Exit if accessed directly.
/**
* Customer On Hold Renewal Order Email.
*
* Order On Hold emails are sent to the customer when the renewal order is marked on-hold and usually indicates that the order is awaiting payment confirmation.
*
* @class WCS_Email_On-hold_Renewal_Order
* @version 3.0.0
* @package WooCommerce_Subscriptions/Includes/Emails
* @author WooCommerce.
* @extends WC_Email_Customer_On_Hold_Order
*/
class WCS_Email_Customer_On_Hold_Renewal_Order extends WC_Email_Customer_On_Hold_Order {
/**
* Constructor.
*/
public function __construct() {
$this->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
);
}
}

View File

@@ -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_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_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_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 // 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(); WC_Email::__construct();

View File

@@ -34,7 +34,9 @@ class WCS_Email_Processing_Renewal_Order extends WC_Email_Customer_Processing_Or
// Triggers for this email // Triggers for this email
add_action( 'woocommerce_order_status_pending_to_processing_renewal_notification', array( $this, 'trigger' ) ); 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 // We want all the parent's methods, with none of its properties, so call its parent's constructor
WC_Email::__construct(); WC_Email::__construct();

View File

@@ -3,12 +3,12 @@
* Plugin Name: Action Scheduler * Plugin Name: Action Scheduler
* Plugin URI: https://actionscheduler.org * Plugin URI: https://actionscheduler.org
* Description: A robust scheduling library for use in WordPress plugins. * Description: A robust scheduling library for use in WordPress plugins.
* Author: Prospress * Author: Automattic
* Author URI: http://prospress.com/ * Author URI: https://automattic.com/
* Version: 2.2.4 * Version: 3.0.1
* License: GPLv3 * 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 * 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 * it under the terms of the GNU General Public License as published by
@@ -21,27 +21,33 @@
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
* *
*/ */
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' ) ) { if ( ! class_exists( 'ActionScheduler_Versions' ) ) {
require_once( 'classes/ActionScheduler_Versions.php' ); require_once( 'classes/ActionScheduler_Versions.php' );
add_action( 'plugins_loaded', array( 'ActionScheduler_Versions', 'initialize_latest_version' ), 1, 0 ); 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 = 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() { function action_scheduler_initialize_3_dot_0_dot_1() {
require_once( 'classes/ActionScheduler.php' ); require_once( 'classes/abstracts/ActionScheduler.php' );
ActionScheduler::init( __FILE__ ); 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();
}
} }

View File

@@ -1,133 +0,0 @@
<?php
/**
* Class ActionScheduler
* @codeCoverageIgnore
*/
abstract class ActionScheduler {
private static $plugin_file = '';
/** @var ActionScheduler_ActionFactory */
private static $factory = NULL;
public static function factory() {
if ( !isset(self::$factory) ) {
self::$factory = new ActionScheduler_ActionFactory();
}
return self::$factory;
}
public static function store() {
return ActionScheduler_Store::instance();
}
public static function logger() {
return ActionScheduler_Logger::instance();
}
public static function runner() {
return ActionScheduler_QueueRunner::instance();
}
public static function admin_view() {
return ActionScheduler_AdminView::instance();
}
/**
* Get the absolute system path to the plugin directory, or a file therein
* @static
* @param string $path
* @return string
*/
public static function plugin_path( $path ) {
$base = dirname(self::$plugin_file);
if ( $path ) {
return trailingslashit($base).$path;
} else {
return untrailingslashit($base);
}
}
/**
* Get the absolute URL to the plugin directory, or a file therein
* @static
* @param string $path
* @return string
*/
public static function plugin_url( $path ) {
return plugins_url($path, self::$plugin_file);
}
public static function autoload( $class ) {
$d = DIRECTORY_SEPARATOR;
if ( 'Deprecated' === substr( $class, -10 ) ) {
$dir = self::plugin_path('deprecated'.$d);
} elseif ( strpos( $class, 'ActionScheduler' ) === 0 ) {
$dir = self::plugin_path('classes'.$d);
} elseif ( strpos( $class, 'CronExpression' ) === 0 ) {
$dir = self::plugin_path('lib'.$d.'cron-expression'.$d);
} else {
return;
}
if ( file_exists( "{$dir}{$class}.php" ) ) {
include( "{$dir}{$class}.php" );
return;
}
}
/**
* Initialize the plugin
*
* @static
* @param string $plugin_file
*/
public static function init( $plugin_file ) {
self::$plugin_file = $plugin_file;
spl_autoload_register( array( __CLASS__, 'autoload' ) );
/**
* Fires in the early stages of Action Scheduler init hook.
*/
do_action( 'action_scheduler_pre_init' );
$store = self::store();
add_action( 'init', array( $store, 'init' ), 1, 0 );
$logger = self::logger();
add_action( 'init', array( $logger, 'init' ), 1, 0 );
$runner = self::runner();
add_action( 'init', array( $runner, 'init' ), 1, 0 );
$admin_view = self::admin_view();
add_action( 'init', array( $admin_view, 'init' ), 0, 0 ); // run before $store::init()
require_once( self::plugin_path('functions.php') );
if ( apply_filters( 'action_scheduler_load_deprecated_functions', true ) ) {
require_once( self::plugin_path('deprecated/functions.php') );
}
if ( defined( 'WP_CLI' ) && WP_CLI ) {
WP_CLI::add_command( 'action-scheduler', 'ActionScheduler_WPCLI_Scheduler_command' );
}
}
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 );
}
}

View File

@@ -22,6 +22,9 @@ class ActionScheduler_ActionFactory {
break; break;
case ActionScheduler_Store::STATUS_CANCELED : case ActionScheduler_Store::STATUS_CANCELED :
$action_class = 'ActionScheduler_CanceledAction'; $action_class = 'ActionScheduler_CanceledAction';
if ( ! is_null( $schedule ) && ! is_a( $schedule, 'ActionScheduler_CanceledSchedule' ) ) {
$schedule = new ActionScheduler_CanceledSchedule( $schedule->get_date() );
}
break; break;
default : default :
$action_class = 'ActionScheduler_FinishedAction'; $action_class = 'ActionScheduler_FinishedAction';
@@ -44,6 +47,28 @@ class ActionScheduler_ActionFactory {
return apply_filters( 'action_scheduler_stored_action_instance', $action, $hook, $args, $schedule, $group ); return apply_filters( 'action_scheduler_stored_action_instance', $action, $hook, $args, $schedule, $group );
} }
/**
* Enqueue an action to run one time, as soon as possible (rather a specific scheduled time).
*
* This method creates a new action with the NULLSchedule. This schedule maps to a MySQL datetime string of
* 0000-00-00 00:00:00. This is done to create a psuedo "async action" type that is fully backward compatible.
* Existing queries to claim actions claim by date, meaning actions scheduled for 0000-00-00 00:00:00 will
* always be claimed prior to actions scheduled for a specific date. This makes sure that any async action is
* given priority in queue processing. This has the added advantage of making sure async actions can be
* claimed by both the existing WP Cron and WP CLI runners, as well as a new async request runner.
*
* @param string $hook The hook to trigger when this action runs
* @param array $args Args to pass when the hook is triggered
* @param string $group A group to put the action in
*
* @return 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 string $hook The hook to trigger when this action runs
* @param array $args Args to pass when the hook is triggered * @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 string $hook The hook to trigger when this action runs
* @param array $args Args to pass when the hook is triggered * @param array $args Args to pass when the hook is triggered
* @param int $first Unix timestamp for the first run * @param int $first Unix timestamp for the first run
@@ -78,27 +105,68 @@ class ActionScheduler_ActionFactory {
return $this->store( $action ); 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 string $hook The hook to trigger when this action runs
* @param array $args Args to pass when the hook is triggered * @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 int $schedule A cron definition string
* @param string $group A group to put the action in * @param string $group A group to put the action in
* *
* @return string The ID of the stored action * @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) ) { 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 ); $cron = CronExpression::factory( $schedule );
$schedule = new ActionScheduler_CronSchedule( $date, $cron ); $schedule = new ActionScheduler_CronSchedule( $date, $cron );
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group ); $action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
return $this->store( $action ); 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 * @param ActionScheduler_Action $action
* *

View File

@@ -8,8 +8,10 @@ class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {
private static $admin_view = NULL; private static $admin_view = NULL;
private static $screen_id = 'tools_page_action-scheduler';
/** /**
* @return ActionScheduler_QueueRunner * @return ActionScheduler_AdminView
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public static function instance() { 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( '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. * System Status page, and for sites where WooCommerce isn't active.
*/ */
public function register_menu() { public function register_menu() {
add_submenu_page( $hook_suffix = add_submenu_page(
'tools.php', 'tools.php',
__( 'Scheduled Actions', 'action-scheduler' ), __( 'Scheduled Actions', 'action-scheduler' ),
__( 'Scheduled Actions', 'action-scheduler' ), __( 'Scheduled Actions', 'action-scheduler' ),
@@ -71,6 +75,15 @@ class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {
'action-scheduler', 'action-scheduler',
array( $this, 'render_admin_ui' ) 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 = new ActionScheduler_ListTable( ActionScheduler::store(), ActionScheduler::logger(), ActionScheduler::runner() );
$table->display_page(); $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' =>
'<h2>' . __( 'About Action Scheduler', 'action-scheduler' ) . '</h2>' .
'<p>' .
__( 'Action Scheduler is a scalable, traceable job queue for background processing large sets of actions. Action Scheduler works by triggering an action hook to run at some time in the future. Scheduled actions can also be scheduled to run on a recurring schedule.', 'action-scheduler' ) .
'</p>',
)
);
$screen->add_help_tab(
array(
'id' => 'action_scheduler_columns',
'title' => __( 'Columns', 'action-scheduler' ),
'content' =>
'<h2>' . __( 'Scheduled Action Columns', 'action-scheduler' ) . '</h2>' .
'<ul>' .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Hook', 'action-scheduler' ), __( 'Name of the action hook that will be triggered.', 'action-scheduler' ) ) .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Status', 'action-scheduler' ), __( 'Action statuses are Pending, Complete, Canceled, Failed', 'action-scheduler' ) ) .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Arguments', 'action-scheduler' ), __( 'Optional data array passed to the action hook.', 'action-scheduler' ) ) .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Group', 'action-scheduler' ), __( 'Optional action group.', 'action-scheduler' ) ) .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Recurrence', 'action-scheduler' ), __( 'The action\'s schedule frequency.', 'action-scheduler' ) ) .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Scheduled', 'action-scheduler' ), __( 'The date/time the action is/was scheduled to run.', 'action-scheduler' ) ) .
sprintf( '<li><strong>%1$s</strong>: %2$s</li>', __( 'Log', 'action-scheduler' ), __( 'Activity log for the action.', 'action-scheduler' ) ) .
'</ul>',
)
);
}
} }

View File

@@ -0,0 +1,96 @@
<?php
/**
* ActionScheduler_AsyncRequest_QueueRunner
*/
defined( 'ABSPATH' ) || exit;
/**
* ActionScheduler_AsyncRequest_QueueRunner class.
*/
class ActionScheduler_AsyncRequest_QueueRunner extends WP_Async_Request {
/**
* Data store for querying actions
*
* @var ActionScheduler_Store
* @access protected
*/
protected $store;
/**
* Prefix for ajax hooks
*
* @var string
* @access protected
*/
protected $prefix = 'as';
/**
* Action for ajax hooks
*
* @var string
* @access protected
*/
protected $action = 'async_request_queue_runner';
/**
* Initiate new async request
*/
public function __construct( ActionScheduler_Store $store ) {
parent::__construct();
$this->store = $store;
}
/**
* Handle async requests
*
* Run a queue, and maybe dispatch another async request to run another queue
* if there are still pending actions after completing a queue in this request.
*/
protected function handle() {
do_action( 'action_scheduler_run_queue', 'Async Request' ); // run a queue in the same way as WP Cron, but declare the Async Request context
$sleep_seconds = $this->get_sleep_seconds();
if ( $sleep_seconds ) {
sleep( $sleep_seconds );
}
$this->maybe_dispatch();
}
/**
* If the async request runner is needed and allowed to run, dispatch a request.
*/
public function maybe_dispatch() {
if ( ! $this->allow() ) {
return;
}
$this->dispatch();
}
/**
* 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 );
}
}

View File

@@ -1,57 +0,0 @@
<?php
/**
* Class ActionScheduler_CronSchedule
*/
class ActionScheduler_CronSchedule implements ActionScheduler_Schedule {
/** @var DateTime */
private $start = NULL;
private $start_timestamp = 0;
/** @var CronExpression */
private $cron = NULL;
public function __construct( DateTime $start, CronExpression $cron ) {
$this->start = $start;
$this->cron = $cron;
}
/**
* @param DateTime $after
* @return DateTime|null
*/
public function next( DateTime $after = NULL ) {
$after = empty($after) ? clone $this->start : clone $after;
return $this->cron->getNextRunDate($after, 0, false);
}
/**
* @return bool
*/
public function is_recurring() {
return true;
}
/**
* @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);
}
}

View File

@@ -0,0 +1,177 @@
<?php
use Action_Scheduler\Migration\Controller;
/**
* Class ActionScheduler_DataController
*
* The main plugin/initialization class for the data stores.
*
* Responsible for hooking everything up with WordPress.
*
* @package Action_Scheduler
*
* @since 3.0.0
*/
class ActionScheduler_DataController {
/** Action data store class name. */
const DATASTORE_CLASS = 'ActionScheduler_DBStore';
/** Logger data store class name. */
const LOGGER_CLASS = 'ActionScheduler_DBLogger';
/** Migration status option name. */
const STATUS_FLAG = 'action_scheduler_migration_status';
/** Migration status option value. */
const STATUS_COMPLETE = 'complete';
/** Migration minimum required PHP version. */
const MIN_PHP_VERSION = '5.5';
/** @var ActionScheduler_DataController */
private static $instance;
/** @var int */
private static $sleep_time = 0;
/** @var int */
private static $free_ticks = 50;
/**
* Get a flag indicating whether the migration environment dependencies are met.
*
* @return bool
*/
public static function dependencies_met() {
$php_support = version_compare( PHP_VERSION, self::MIN_PHP_VERSION, '>=' );
return $php_support && apply_filters( 'action_scheduler_migration_dependencies_met', true );
}
/**
* Get a flag indicating whether the migration is complete.
*
* @return bool Whether the flag has been set marking the migration as complete
*/
public static function is_migration_complete() {
return get_option( self::STATUS_FLAG ) === self::STATUS_COMPLETE;
}
/**
* Mark the migration as complete.
*/
public static function mark_migration_complete() {
update_option( self::STATUS_FLAG, self::STATUS_COMPLETE );
}
/**
* 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;
}
}

View File

@@ -5,7 +5,7 @@
* *
* Facilitates catching Exceptions unique to Action Scheduler. * Facilitates catching Exceptions unique to Action Scheduler.
* *
* @package Prospress\ActionScheduler * @package ActionScheduler
* @since %VERSION% * @since %VERSION%
*/ */
interface ActionScheduler_Exception {} interface ActionScheduler_Exception {}

View File

@@ -1,60 +0,0 @@
<?php
/**
* Class ActionScheduler_IntervalSchedule
*/
class ActionScheduler_IntervalSchedule implements ActionScheduler_Schedule {
/** @var DateTime */
private $start = NULL;
private $start_timestamp = 0;
private $interval_in_seconds = 0;
public function __construct( DateTime $start, $interval ) {
$this->start = $start;
$this->interval_in_seconds = (int)$interval;
}
/**
* @param DateTime $after
*
* @return DateTime|null
*/
public function next( DateTime $after = NULL ) {
$after = empty($after) ? as_get_datetime_object('@0') : clone $after;
if ( $after > $this->start ) {
$after->modify('+'.$this->interval_in_seconds.' seconds');
return $after;
}
return clone $this->start;
}
/**
* @return bool
*/
public function is_recurring() {
return true;
}
/**
* @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);
}
}

View File

@@ -5,10 +5,27 @@
* *
* Used for identifying actions that are invalid in some way. * Used for identifying actions that are invalid in some way.
* *
* @package Prospress\ActionScheduler * @package ActionScheduler
*/ */
class ActionScheduler_InvalidActionException extends \InvalidArgumentException implements ActionScheduler_Exception { 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. * 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. * @param string $action_id The action ID with bad args.
* @return static * @return static
*/ */
public static function from_decoding_args( $action_id ) { public static function from_decoding_args( $action_id, $args = array() ) {
$message = sprintf( $message = sprintf(
__( 'Action [%s] has invalid arguments. It cannot be JSON decoded to an array.', 'action-scheduler' ), /* translators: 1: action ID 2: arguments */
$action_id __( '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 ); return new static( $message );

View File

@@ -140,30 +140,37 @@ class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
self::$time_periods = array( self::$time_periods = array(
array( array(
'seconds' => YEAR_IN_SECONDS, 'seconds' => YEAR_IN_SECONDS,
/* translators: %s: amount of time */
'names' => _n_noop( '%s year', '%s years', 'action-scheduler' ), 'names' => _n_noop( '%s year', '%s years', 'action-scheduler' ),
), ),
array( array(
'seconds' => MONTH_IN_SECONDS, 'seconds' => MONTH_IN_SECONDS,
/* translators: %s: amount of time */
'names' => _n_noop( '%s month', '%s months', 'action-scheduler' ), 'names' => _n_noop( '%s month', '%s months', 'action-scheduler' ),
), ),
array( array(
'seconds' => WEEK_IN_SECONDS, 'seconds' => WEEK_IN_SECONDS,
/* translators: %s: amount of time */
'names' => _n_noop( '%s week', '%s weeks', 'action-scheduler' ), 'names' => _n_noop( '%s week', '%s weeks', 'action-scheduler' ),
), ),
array( array(
'seconds' => DAY_IN_SECONDS, 'seconds' => DAY_IN_SECONDS,
/* translators: %s: amount of time */
'names' => _n_noop( '%s day', '%s days', 'action-scheduler' ), 'names' => _n_noop( '%s day', '%s days', 'action-scheduler' ),
), ),
array( array(
'seconds' => HOUR_IN_SECONDS, 'seconds' => HOUR_IN_SECONDS,
/* translators: %s: amount of time */
'names' => _n_noop( '%s hour', '%s hours', 'action-scheduler' ), 'names' => _n_noop( '%s hour', '%s hours', 'action-scheduler' ),
), ),
array( array(
'seconds' => MINUTE_IN_SECONDS, 'seconds' => MINUTE_IN_SECONDS,
/* translators: %s: amount of time */
'names' => _n_noop( '%s minute', '%s minutes', 'action-scheduler' ), 'names' => _n_noop( '%s minute', '%s minutes', 'action-scheduler' ),
), ),
array( array(
'seconds' => 1, 'seconds' => 1,
/* translators: %s: amount of time */
'names' => _n_noop( '%s second', '%s seconds', 'action-scheduler' ), 'names' => _n_noop( '%s second', '%s seconds', 'action-scheduler' ),
), ),
); );
@@ -221,14 +228,15 @@ class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
* @return string * @return string
*/ */
protected function get_recurrence( $action ) { protected function get_recurrence( $action ) {
$recurrence = $action->get_schedule(); $schedule = $action->get_schedule();
if ( $recurrence->is_recurring() ) { if ( $schedule->is_recurring() ) {
if ( method_exists( $recurrence, 'interval_in_seconds' ) ) { $recurrence = $schedule->get_recurrence();
return sprintf( __( 'Every %s', 'action-scheduler' ), self::human_interval( $recurrence->interval_in_seconds() ) );
}
if ( method_exists( $recurrence, 'get_recurrence' ) ) { if ( is_numeric( $recurrence ) ) {
return sprintf( __( 'Cron %s', 'action-scheduler' ), $recurrence->get_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() { 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( $this->admin_notices[] = array(
'class' => 'updated', '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. <a href="%s">View actions in-progress &raquo;</a>', 'action-scheduler' ), esc_url( $in_progress_url ) );
} else {
/* translators: %d: seconds */
$async_request_message = sprintf( __( 'The next queue will begin processing in approximately %d seconds.', 'action-scheduler' ), $async_request_lock_expiration - time() );
}
$this->admin_notices[] = array(
'class' => 'notice notice-info',
'message' => $async_request_message,
); );
} }
@@ -333,18 +363,22 @@ class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
$class = 'updated'; $class = 'updated';
switch ( $notification['row_action_type'] ) { switch ( $notification['row_action_type'] ) {
case 'run' : case 'run' :
/* translators: %s: action HTML */
$action_message_html = sprintf( __( 'Successfully executed action: %s', 'action-scheduler' ), $action_hook_html ); $action_message_html = sprintf( __( 'Successfully executed action: %s', 'action-scheduler' ), $action_hook_html );
break; break;
case 'cancel' : case 'cancel' :
/* translators: %s: action HTML */
$action_message_html = sprintf( __( 'Successfully canceled action: %s', 'action-scheduler' ), $action_hook_html ); $action_message_html = sprintf( __( 'Successfully canceled action: %s', 'action-scheduler' ), $action_hook_html );
break; break;
default : default :
/* translators: %s: action HTML */
$action_message_html = sprintf( __( 'Successfully processed change for action: %s', 'action-scheduler' ), $action_hook_html ); $action_message_html = sprintf( __( 'Successfully processed change for action: %s', 'action-scheduler' ), $action_hook_html );
break; break;
} }
} else { } else {
$class = 'error'; $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 ); $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 = ''; $schedule_display_string = '';
if ( ! $schedule->next() ) { if ( ! $schedule->get_date() ) {
return $schedule_display_string; 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 .= '<br/>'; $schedule_display_string .= '<br/>';
if ( gmdate( 'U' ) > $next_timestamp ) { if ( gmdate( 'U' ) > $next_timestamp ) {
/* translators: %s: date interval */
$schedule_display_string .= sprintf( __( ' (%s ago)', 'action-scheduler' ), self::human_interval( gmdate( 'U' ) - $next_timestamp ) ); $schedule_display_string .= sprintf( __( ' (%s ago)', 'action-scheduler' ), self::human_interval( gmdate( 'U' ) - $next_timestamp ) );
} else { } else {
/* translators: %s: date interval */
$schedule_display_string .= sprintf( __( ' (%s)', 'action-scheduler' ), self::human_interval( $next_timestamp - gmdate( 'U' ) ) ); $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 { try {
switch ( $row_action_type ) { switch ( $row_action_type ) {
case 'run' : case 'run' :
$this->runner->process_action( $action_id ); $this->runner->process_action( $action_id, 'Admin List Table' );
break; break;
case 'cancel' : case 'cancel' :
$this->store->cancel_action( $action_id ); $this->store->cancel_action( $action_id );
@@ -462,16 +498,6 @@ class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
* {@inheritDoc} * {@inheritDoc}
*/ */
public function prepare_items() { 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(); $this->prepare_column_headers();
$per_page = $this->get_items_per_page( $this->package . '_items_per_page', $this->items_per_page ); $per_page = $this->get_items_per_page( $this->package . '_items_per_page', $this->items_per_page );

View File

@@ -1,98 +0,0 @@
<?php
/**
* Class ActionScheduler_Logger
* @codeCoverageIgnore
*/
abstract class ActionScheduler_Logger {
private static $logger = NULL;
/**
* @return ActionScheduler_Logger
*/
public static function instance() {
if ( empty(self::$logger) ) {
$class = apply_filters('action_scheduler_logger_class', 'ActionScheduler_wpCommentLogger');
self::$logger = new $class();
}
return self::$logger;
}
/**
* @param string $action_id
* @param string $message
* @param DateTime $date
*
* @return string The log entry ID
*/
abstract public function log( $action_id, $message, DateTime $date = NULL );
/**
* @param string $entry_id
*
* @return ActionScheduler_LogEntry
*/
abstract public function get_entry( $entry_id );
/**
* @param string $action_id
*
* @return ActionScheduler_LogEntry[]
*/
abstract public function get_logs( $action_id );
/**
* @codeCoverageIgnore
*/
public function init() {
add_action( 'action_scheduler_stored_action', array( $this, 'log_stored_action' ), 10, 1 );
add_action( 'action_scheduler_canceled_action', array( $this, 'log_canceled_action' ), 10, 1 );
add_action( 'action_scheduler_before_execute', array( $this, 'log_started_action' ), 10, 1 );
add_action( 'action_scheduler_after_execute', array( $this, 'log_completed_action' ), 10, 1 );
add_action( 'action_scheduler_failed_execution', array( $this, 'log_failed_action' ), 10, 2 );
add_action( 'action_scheduler_failed_action', array( $this, 'log_timed_out_action' ), 10, 2 );
add_action( 'action_scheduler_unexpected_shutdown', array( $this, 'log_unexpected_shutdown' ), 10, 2 );
add_action( 'action_scheduler_reset_action', array( $this, 'log_reset_action' ), 10, 1 );
add_action( 'action_scheduler_execution_ignored', array( $this, 'log_ignored_action' ), 10, 1 );
}
public function log_stored_action( $action_id ) {
$this->log( $action_id, __( 'action created', 'action-scheduler' ) );
}
public function log_canceled_action( $action_id ) {
$this->log( $action_id, __( 'action canceled', 'action-scheduler' ) );
}
public function log_started_action( $action_id ) {
$this->log( $action_id, __( 'action started', 'action-scheduler' ) );
}
public function log_completed_action( $action_id ) {
$this->log( $action_id, __( 'action complete', 'action-scheduler' ) );
}
public function log_failed_action( $action_id, Exception $exception ) {
$this->log( $action_id, sprintf( __( 'action failed: %s', 'action-scheduler' ), $exception->getMessage() ) );
}
public function log_timed_out_action( $action_id, $timeout ) {
$this->log( $action_id, sprintf( __( 'action timed out after %s seconds', 'action-scheduler' ), $timeout ) );
}
public function log_unexpected_shutdown( $action_id, $error ) {
if ( ! empty( $error ) ) {
$this->log( $action_id, sprintf( __( 'unexpected shutdown: PHP Fatal error %s in %s on line %s', 'action-scheduler' ), $error['message'], $error['file'], $error['line'] ) );
}
}
public function log_reset_action( $action_id ) {
$this->log( $action_id, __( 'action reset', 'action_scheduler' ) );
}
public function log_ignored_action( $action_id ) {
$this->log( $action_id, __( 'action ignored', 'action-scheduler' ) );
}
}

View File

@@ -1,19 +0,0 @@
<?php
/**
* Class ActionScheduler_NullSchedule
*/
class ActionScheduler_NullSchedule implements ActionScheduler_Schedule {
public function next( DateTime $after = NULL ) {
return NULL;
}
/**
* @return bool
*/
public function is_recurring() {
return false;
}
}

View File

@@ -0,0 +1,49 @@
<?php
/**
* Provide a way to set simple transient locks to block behaviour
* for up-to a given duration.
*
* Class ActionScheduler_OptionLock
* @since 3.0.0
*/
class ActionScheduler_OptionLock extends ActionScheduler_Lock {
/**
* Set a lock using options for a given amount of time (60 seconds by default).
*
* Using an autoloaded option avoids running database queries or other resource intensive tasks
* on frequently triggered hooks, like 'init' or 'shutdown'.
*
* For example, ActionScheduler_QueueRunner->maybe_dispatch_async_request() uses a lock to avoid
* calling ActionScheduler_QueueRunner->has_maximum_concurrent_batches() every time the 'shutdown',
* hook is triggered, because that method calls ActionScheduler_QueueRunner->store->get_claim_count()
* to find the current number of claims in the database.
*
* @param string $lock_type A string to identify different lock types.
* @bool True if lock value has changed, false if not or if set failed.
*/
public function set( $lock_type ) {
return update_option( $this->get_key( $lock_type ), time() + $this->get_duration( $lock_type ) );
}
/**
* If a lock is set, return the timestamp it was set to expiry.
*
* @param string $lock_type A string to identify different lock types.
* @return bool|int False if no lock is set, otherwise the timestamp for when the lock is set to expire.
*/
public function get_expiration( $lock_type ) {
return get_option( $this->get_key( $lock_type ) );
}
/**
* Get the key to use for storing the lock in the transient
*
* @param string $lock_type A string to identify different lock types.
* @return string
*/
protected function get_key( $lock_type ) {
return sprintf( 'action_scheduler_lock_%s', $lock_type );
}
}

View File

@@ -8,6 +8,9 @@ class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
const WP_CRON_SCHEDULE = 'every_minute'; const WP_CRON_SCHEDULE = 'every_minute';
/** @var ActionScheduler_AsyncRequest_QueueRunner */
protected $async_request;
/** @var ActionScheduler_QueueRunner */ /** @var ActionScheduler_QueueRunner */
private static $runner = null; private static $runner = null;
@@ -30,8 +33,14 @@ class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
* @param ActionScheduler_FatalErrorMonitor $monitor * @param ActionScheduler_FatalErrorMonitor $monitor
* @param ActionScheduler_QueueCleaner $cleaner * @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 ); 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' ) ); 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 ); $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_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_memory_limit();
ActionScheduler_Compatibility::raise_time_limit( $this->get_time_limit() ); ActionScheduler_Compatibility::raise_time_limit( $this->get_time_limit() );
do_action( 'action_scheduler_before_process_queue' ); do_action( 'action_scheduler_before_process_queue' );
$this->run_cleanup(); $this->run_cleanup();
$processed_actions = 0; $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 ); $batch_size = apply_filters( 'action_scheduler_queue_runner_batch_size', 25 );
do { 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; $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 } 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; 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); $claim = $this->store->stake_claim($size);
$this->monitor->attach($claim); $this->monitor->attach($claim);
$processed_actions = 0; $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() ) ) ) { if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $claim->get_id() ) ) ) {
break; break;
} }
$this->process_action( $action_id ); $this->process_action( $action_id, $context );
$processed_actions++; $processed_actions++;
if ( $this->batch_limits_exceeded( $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 ) { public function add_wp_cron_schedule( $schedules ) {
$schedules['every_minute'] = array( $schedules['every_minute'] = array(
'interval' => 60, // in seconds 'interval' => 60, // in seconds
'display' => __( 'Every minute' ), 'display' => __( 'Every minute', 'action-scheduler' ),
); );
return $schedules; return $schedules;

View File

@@ -1,44 +0,0 @@
<?php
/**
* Class ActionScheduler_SimpleSchedule
*/
class ActionScheduler_SimpleSchedule implements ActionScheduler_Schedule {
private $date = NULL;
private $timestamp = 0;
public function __construct( DateTime $date ) {
$this->date = clone $date;
}
/**
* @param DateTime $after
*
* @return DateTime|null
*/
public function next( DateTime $after = NULL ) {
$after = empty($after) ? as_get_datetime_object('@0') : $after;
return ( $after > $this->date ) ? NULL : clone $this->date;
}
/**
* @return bool
*/
public function is_recurring() {
return false;
}
/**
* For PHP 5.2 compat, since DateTime objects can't be serialized
* @return array
*/
public function __sleep() {
$this->timestamp = $this->date->getTimestamp();
return array(
'timestamp',
);
}
public function __wakeup() {
$this->date = as_get_datetime_object($this->timestamp);
}
}

View File

@@ -1,212 +0,0 @@
<?php
/**
* Class ActionScheduler_Store
* @codeCoverageIgnore
*/
abstract class ActionScheduler_Store {
const STATUS_COMPLETE = 'complete';
const STATUS_PENDING = 'pending';
const STATUS_RUNNING = 'in-progress';
const STATUS_FAILED = 'failed';
const STATUS_CANCELED = 'canceled';
/** @var ActionScheduler_Store */
private static $store = NULL;
/**
* @param ActionScheduler_Action $action
* @param DateTime $scheduled_date Optional Date of the first instance
* to store. Otherwise uses the first date of the action's
* schedule.
*
* @return string The action ID
*/
abstract public function save_action( ActionScheduler_Action $action, DateTime $scheduled_date = NULL );
/**
* @param string $action_id
*
* @return ActionScheduler_Action
*/
abstract public function fetch_action( $action_id );
/**
* @param string $hook
* @param array $params
* @return string ID of the next action matching the criteria
*/
abstract public function find_action( $hook, $params = array() );
/**
* @param array $query
* @return array The IDs of actions matching the query
*/
abstract public function query_actions( $query = array() );
/**
* Get a count of all actions in the store, grouped by status
*
* @return array
*/
abstract public function action_counts();
/**
* @param string $action_id
*/
abstract public function cancel_action( $action_id );
/**
* @param string $action_id
*/
abstract public function delete_action( $action_id );
/**
* @param string $action_id
*
* @return DateTime The date the action is schedule to run, or the date that it ran.
*/
abstract public function get_date( $action_id );
/**
* @param int $max_actions
* @param DateTime $before_date Claim only actions schedule before the given date. Defaults to now.
* @param array $hooks Claim only actions with a hook or hooks.
* @param string $group Claim only actions in the given group.
*
* @return ActionScheduler_ActionClaim
*/
abstract public function stake_claim( $max_actions = 10, DateTime $before_date = null, $hooks = array(), $group = '' );
/**
* @return int
*/
abstract public function get_claim_count();
/**
* @param ActionScheduler_ActionClaim $claim
*/
abstract public function release_claim( ActionScheduler_ActionClaim $claim );
/**
* @param string $action_id
*/
abstract public function unclaim_action( $action_id );
/**
* @param string $action_id
*/
abstract public function mark_failure( $action_id );
/**
* @param string $action_id
*/
abstract public function log_execution( $action_id );
/**
* @param string $action_id
*/
abstract public function mark_complete( $action_id );
/**
* @param string $action_id
*
* @return string
*/
abstract public function get_status( $action_id );
/**
* @param string $action_id
* @return mixed
*/
abstract public function get_claim_id( $action_id );
/**
* @param string $claim_id
* @return array
*/
abstract public function find_actions_by_claim_id( $claim_id );
/**
* @param string $comparison_operator
* @return string
*/
protected function validate_sql_comparator( $comparison_operator ) {
if ( in_array( $comparison_operator, array('!=', '>', '>=', '<', '<=', '=') ) ) {
return $comparison_operator;
}
return '=';
}
/**
* Get the time MySQL formated date/time string for an action's (next) scheduled date.
*
* @param ActionScheduler_Action $action
* @param DateTime $scheduled_date (optional)
* @return string
*/
protected function get_scheduled_date_string( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
$next = null === $scheduled_date ? $action->get_schedule()->next() : $scheduled_date;
if ( ! $next ) {
throw new InvalidArgumentException( __( 'Invalid schedule. Cannot save action.', 'action-scheduler' ) );
}
$next->setTimezone( new DateTimeZone( 'UTC' ) );
return $next->format( 'Y-m-d H:i:s' );
}
/**
* Get the time MySQL formated date/time string for an action's (next) scheduled date.
*
* @param ActionScheduler_Action $action
* @param DateTime $scheduled_date (optional)
* @return string
*/
protected function get_scheduled_date_string_local( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
$next = null === $scheduled_date ? $action->get_schedule()->next() : $scheduled_date;
if ( ! $next ) {
throw new InvalidArgumentException( __( 'Invalid schedule. Cannot save action.', 'action-scheduler' ) );
}
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();
}
}

View File

@@ -0,0 +1,108 @@
<?php
/**
* Class ActionScheduler_WPCommentCleaner
*
* @since 3.0.0
*/
class ActionScheduler_WPCommentCleaner {
/**
* Post migration hook used to cleanup the WP comment table.
*
* @var string
*/
protected static $cleanup_hook = 'action_scheduler/cleanup_wp_comment_logs';
/**
* An instance of the ActionScheduler_wpCommentLogger class to interact with the comments table.
*
* This instance should only be used as an interface. It should not be initialized.
*
* @var ActionScheduler_wpCommentLogger
*/
protected static $wp_comment_logger = null;
/**
* The key used to store the cached value of whether there are logs in the WP comment table.
*
* @var string
*/
protected static $has_logs_option_key = 'as_has_wp_comment_logs';
/**
* Initialize the class and attach callbacks.
*/
public static function init() {
if ( empty( self::$wp_comment_logger ) ) {
self::$wp_comment_logger = new ActionScheduler_wpCommentLogger();
}
add_action( self::$cleanup_hook, array( __CLASS__, 'delete_all_action_comments' ) );
// While there are orphaned logs left in the comments table, we need to attach the callbacks which filter comment counts.
add_action( 'pre_get_comments', array( self::$wp_comment_logger, 'filter_comment_queries' ), 10, 1 );
add_action( 'wp_count_comments', array( self::$wp_comment_logger, 'filter_comment_count' ), 20, 2 ); // run after WC_Comments::wp_count_comments() to make sure we exclude order notes and action logs
add_action( 'comment_feed_where', array( self::$wp_comment_logger, 'filter_comment_feed' ), 10, 2 );
// Action Scheduler may be displayed as a Tools screen or WooCommerce > Status administration screen
add_action( 'load-tools_page_action-scheduler', array( __CLASS__, '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 <a href="%2$s">Learn more &raquo;</a>', 'action-scheduler' ),
$next_cleanup_message,
'https://github.com/woocommerce/action-scheduler/issues/368'
);
echo '<div class="notice notice-warning"><p>' . wp_kses_post( $notice ) . '</p></div>';
}
}

View File

@@ -129,8 +129,8 @@ class ActionScheduler_wcSystemStatus {
/** /**
* is triggered when invoking inaccessible methods in an object context. * is triggered when invoking inaccessible methods in an object context.
* *
* @param $name string * @param string $name
* @param $arguments array * @param array $arguments
* *
* @return mixed * @return mixed
* @link https://php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods * @link https://php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods

View File

@@ -1,5 +1,7 @@
<?php <?php
use Action_Scheduler\WP_CLI\ProgressBar;
/** /**
* WP CLI Queue runner. * WP CLI Queue runner.
* *
@@ -52,9 +54,7 @@ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRu
$this->add_hooks(); $this->add_hooks();
// Check to make sure there aren't too many concurrent processes running. // Check to make sure there aren't too many concurrent processes running.
$claim_count = $this->store->get_claim_count(); if ( $this->has_maximum_concurrent_batches() ) {
$too_many = $claim_count >= $this->get_allowed_concurrent_batches();
if ( $too_many ) {
if ( $force ) { if ( $force ) {
WP_CLI::warning( __( 'There are too many concurrent batches, but the run is forced to continue.', 'action-scheduler' ) ); WP_CLI::warning( __( 'There are too many concurrent batches, but the run is forced to continue.', 'action-scheduler' ) );
} else { } else {
@@ -88,7 +88,8 @@ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRu
*/ */
protected function setup_progress_bar() { protected function setup_progress_bar() {
$count = count( $this->actions ); $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 ) ), sprintf( _n( 'Running %d action', 'Running %d actions', $count, 'action-scheduler' ), number_format_i18n( $count ) ),
$count $count
); );
@@ -98,9 +99,12 @@ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRu
* Process actions in the queue. * Process actions in the queue.
* *
* @author Jeremy Pry * @author Jeremy Pry
*
* @param string $context Optional runner context. Default 'WP CLI'.
*
* @return int The number of actions processed. * @return int The number of actions processed.
*/ */
public function run() { public function run( $context = 'WP CLI' ) {
do_action( 'action_scheduler_before_process_queue' ); do_action( 'action_scheduler_before_process_queue' );
$this->setup_progress_bar(); $this->setup_progress_bar();
foreach ( $this->actions as $action_id ) { foreach ( $this->actions as $action_id ) {
@@ -110,9 +114,8 @@ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRu
break; break;
} }
$this->process_action( $action_id ); $this->process_action( $action_id, $context );
$this->progress_bar->tick(); $this->progress_bar->tick();
$this->maybe_stop_the_insanity();
} }
$completed = $this->progress_bar->current(); $completed = $this->progress_bar->current();
@@ -148,8 +151,8 @@ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRu
if ( null === $action ) { if ( null === $action ) {
$action = $this->store->fetch_action( $action_id ); $action = $this->store->fetch_action( $action_id );
} }
/* translators: %s refers to the action ID */ /* translators: 1: action ID 2: hook name */
WP_CLI::log( sprintf( __( 'Completed processing action %s with hook: %s', 'action-scheduler' ), $action_id, $action->get_hook() ) ); 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 ) { public function action_failed( $action_id, $exception ) {
WP_CLI::error( 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() ), sprintf( __( 'Error processing action %1$s: %2$s', 'action-scheduler' ), $action_id, $exception->getMessage() ),
false false
); );
@@ -173,35 +176,12 @@ class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRu
* Sleep and help avoid hitting memory limit * Sleep and help avoid hitting memory limit
* *
* @param int $sleep_time Amount of seconds to sleep * @param int $sleep_time Amount of seconds to sleep
* @deprecated 3.0.0
*/ */
protected function stop_the_insanity( $sleep_time = 0 ) { protected function stop_the_insanity( $sleep_time = 0 ) {
if ( 0 < $sleep_time ) { _deprecated_function( 'ActionScheduler_WPCLI_QueueRunner::stop_the_insanity', '3.0.0', 'ActionScheduler_DataController::free_memory' );
WP_CLI::warning( sprintf( 'Stopped the insanity for %d %s', $sleep_time, _n( 'second', 'seconds', $sleep_time ) ) );
sleep( $sleep_time );
}
WP_CLI::warning( __( 'Attempting to reduce used memory...', 'action-scheduler' ) ); ActionScheduler_DataController::free_memory();
/**
* @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
}
} }
/** /**

View File

@@ -1,7 +1,7 @@
<?php <?php
/** /**
* Commands for the Action Scheduler by Prospress. * Commands for Action Scheduler.
*/ */
class ActionScheduler_WPCLI_Scheduler_command extends WP_CLI_Command { class ActionScheduler_WPCLI_Scheduler_command extends WP_CLI_Command {
@@ -25,12 +25,20 @@ class ActionScheduler_WPCLI_Scheduler_command extends WP_CLI_Command {
* [--group=<group>] * [--group=<group>]
* : Only run actions from the specified group. Omitting this option runs actions from all groups. * : Only run actions from the specified group. Omitting this option runs actions from all groups.
* *
* [--free-memory-on=<count>]
* : The number of actions to process between freeing memory. 0 disables freeing memory. Default 50.
*
* [--pause=<seconds>]
* : The number of seconds to pause when freeing memory. Default no pause.
*
* [--force] * [--force]
* : Whether to force execution despite the maximum number of concurrent processes being exceeded. * : Whether to force execution despite the maximum number of concurrent processes being exceeded.
* *
* @param array $args Positional arguments. * @param array $args Positional arguments.
* @param array $assoc_args Keyed arguments. * @param array $assoc_args Keyed arguments.
* @throws \WP_CLI\ExitException When an error occurs. * @throws \WP_CLI\ExitException When an error occurs.
*
* @subcommand run
*/ */
public function run( $args, $assoc_args ) { public function run( $args, $assoc_args ) {
// Handle passed arguments. // 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 = explode( ',', WP_CLI\Utils\get_flag_value( $assoc_args, 'hooks', '' ) );
$hooks = array_filter( array_map( 'trim', $hooks ) ); $hooks = array_filter( array_map( 'trim', $hooks ) );
$group = \WP_CLI\Utils\get_flag_value( $assoc_args, 'group', '' ); $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 ); $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; $batches_completed = 0;
$actions_completed = 0; $actions_completed = 0;
$unlimited = $batches === 0; $unlimited = $batches === 0;
@@ -119,7 +132,7 @@ class ActionScheduler_WPCLI_Scheduler_command extends WP_CLI_Command {
protected function print_error( Exception $e ) { protected function print_error( Exception $e ) {
WP_CLI::error( WP_CLI::error(
sprintf( 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' ), __( 'There was an error running the action scheduler: %s', 'action-scheduler' ),
$e->getMessage() $e->getMessage()
) )

View File

@@ -0,0 +1,148 @@
<?php
namespace Action_Scheduler\WP_CLI;
use Action_Scheduler\Migration\Config;
use Action_Scheduler\Migration\Runner;
use Action_Scheduler\Migration\Scheduler;
use Action_Scheduler\Migration\Controller;
use WP_CLI;
use WP_CLI_Command;
/**
* Class Migration_Command
*
* @package Action_Scheduler\WP_CLI
*
* @since 3.0.0
*
* @codeCoverageIgnore
*/
class Migration_Command extends WP_CLI_Command {
/** @var int */
private $total_processed = 0;
/**
* Register the command with WP-CLI
*/
public function register() {
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command( 'action-scheduler migrate', [ $this, 'migrate' ], [
'shortdesc' => 'Migrates actions to the DB tables store',
'synopsis' => [
[
'type' => 'assoc',
'name' => 'batch-size',
'optional' => true,
'default' => 100,
'description' => 'The number of actions to process in each batch',
],
[
'type' => 'assoc',
'name' => 'free-memory-on',
'optional' => true,
'default' => 50,
'description' => 'The number of actions to process between freeing memory. 0 disables freeing memory',
],
[
'type' => 'assoc',
'name' => 'pause',
'optional' => true,
'default' => 0,
'description' => 'The number of seconds to pause when freeing memory',
],
[
'type' => 'flag',
'name' => 'dry-run',
'optional' => true,
'description' => 'Reports on the actions that would have been migrated, but does not change any data',
],
],
] );
}
/**
* Process the data migration.
*
* @param array $positional_args Required for WP CLI. Not used in migration.
* @param array $assoc_args Optional arguments.
*
* @return void
*/
public function migrate( $positional_args, $assoc_args ) {
$this->init_logging();
$config = $this->get_migration_config( $assoc_args );
$runner = new Runner( $config );
$runner->init_destination();
$batch_size = isset( $assoc_args[ 'batch-size' ] ) ? (int) $assoc_args[ 'batch-size' ] : 100;
$free_on = isset( $assoc_args[ 'free-memory-on' ] ) ? (int) $assoc_args[ 'free-memory-on' ] : 50;
$sleep = isset( $assoc_args[ 'pause' ] ) ? (int) $assoc_args[ 'pause' ] : 0;
\ActionScheduler_DataController::set_free_ticks( $free_on );
\ActionScheduler_DataController::set_sleep_time( $sleep );
do {
$actions_processed = $runner->run( $batch_size );
$this->total_processed += $actions_processed;
} while ( $actions_processed > 0 );
if ( ! $config->get_dry_run() ) {
// let the scheduler know that there's nothing left to do
$scheduler = new Scheduler();
$scheduler->mark_complete();
}
WP_CLI::success( sprintf( '%s complete. %d actions processed.', $config->get_dry_run() ? 'Dry run' : 'Migration', $this->total_processed ) );
}
/**
* Build the config object used to create the Runner
*
* @param array $args Optional arguments.
*
* @return ActionScheduler\Migration\Config
*/
private function get_migration_config( $args ) {
$args = wp_parse_args( $args, [
'dry-run' => false,
] );
$config = Controller::instance()->get_migration_config_object();
$config->set_dry_run( ! empty( $args[ 'dry-run' ] ) );
return $config;
}
/**
* Hook command line logging into migration actions.
*/
private function init_logging() {
add_action( 'action_scheduler/migrate_action_dry_run', function ( $action_id ) {
WP_CLI::debug( sprintf( 'Dry-run: migrated action %d', $action_id ) );
}, 10, 1 );
add_action( 'action_scheduler/no_action_to_migrate', function ( $action_id ) {
WP_CLI::debug( sprintf( 'No action found to migrate for ID %d', $action_id ) );
}, 10, 1 );
add_action( 'action_scheduler/migrate_action_failed', function ( $action_id ) {
WP_CLI::warning( sprintf( 'Failed migrating action with ID %d', $action_id ) );
}, 10, 1 );
add_action( 'action_scheduler/migrate_action_incomplete', function ( $source_id, $destination_id ) {
WP_CLI::warning( sprintf( 'Unable to remove source action with ID %d after migrating to new ID %d', $source_id, $destination_id ) );
}, 10, 2 );
add_action( 'action_scheduler/migrated_action', function ( $source_id, $destination_id ) {
WP_CLI::debug( sprintf( 'Migrated source action with ID %d to new store with ID %d', $source_id, $destination_id ) );
}, 10, 2 );
add_action( 'action_scheduler/migration_batch_starting', function ( $batch ) {
WP_CLI::debug( 'Beginning migration of batch: ' . print_r( $batch, true ) );
}, 10, 1 );
add_action( 'action_scheduler/migration_batch_complete', function ( $batch ) {
WP_CLI::log( sprintf( 'Completed migration of %d actions', count( $batch ) ) );
}, 10, 1 );
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace Action_Scheduler\WP_CLI;
/**
* WP_CLI progress bar for Action Scheduler.
*/
/**
* Class ProgressBar
*
* @package Action_Scheduler\WP_CLI
*
* @since 3.0.0
*
* @codeCoverageIgnore
*/
class ProgressBar {
/** @var integer */
protected $total_ticks;
/** @var integer */
protected $count;
/** @var integer */
protected $interval;
/** @var string */
protected $message;
/** @var \cli\progress\Bar */
protected $progress_bar;
/**
* ProgressBar constructor.
*
* @param string $message Text to display before the progress bar.
* @param integer $count Total number of ticks to be performed.
* @param integer $interval Optional. The interval in milliseconds between updates. Default 100.
*
* @throws Exception When this is not run within WP CLI
*/
public function __construct( $message, $count, $interval = 100 ) {
if ( ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
/* translators: %s php class name */
throw new \Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), __CLASS__ ) );
}
$this->total_ticks = 0;
$this->message = $message;
$this->count = $count;
$this->interval = $interval;
}
/**
* Increment the progress bar ticks.
*/
public function tick() {
if ( null === $this->progress_bar ) {
$this->setup_progress_bar();
}
$this->progress_bar->tick();
$this->total_ticks++;
do_action( 'action_scheduler/progress_tick', $this->total_ticks );
}
/**
* Get the progress bar tick count.
*
* @return int
*/
public function current() {
return $this->progress_bar ? $this->progress_bar->current() : 0;
}
/**
* Finish the current progress bar.
*/
public function finish() {
if ( null !== $this->progress_bar ) {
$this->progress_bar->finish();
}
$this->progress_bar = null;
}
/**
* Set the message used when creating the progress bar.
*
* @param string $message The message to be used when the next progress bar is created.
*/
public function set_message( $message ) {
$this->message = $message;
}
/**
* Set the count for a new progress bar.
*
* @param integer $count The total number of ticks expected to complete.
*/
public function set_count( $count ) {
$this->count = $count;
$this->finish();
}
/**
* Set up the progress bar.
*/
protected function setup_progress_bar() {
$this->progress_bar = \WP_CLI\Utils\make_progress_bar(
$this->message,
$this->count,
$this->interval
);
}
}

View File

@@ -0,0 +1,269 @@
<?php
use Action_Scheduler\WP_CLI\Migration_Command;
use Action_Scheduler\Migration\Controller;
/**
* Class ActionScheduler
* @codeCoverageIgnore
*/
abstract class ActionScheduler {
private static $plugin_file = '';
/** @var ActionScheduler_ActionFactory */
private static $factory = NULL;
public static function factory() {
if ( !isset(self::$factory) ) {
self::$factory = new ActionScheduler_ActionFactory();
}
return self::$factory;
}
public static function store() {
return ActionScheduler_Store::instance();
}
public static function lock() {
return ActionScheduler_Lock::instance();
}
public static function logger() {
return ActionScheduler_Logger::instance();
}
public static function runner() {
return ActionScheduler_QueueRunner::instance();
}
public static function admin_view() {
return ActionScheduler_AdminView::instance();
}
/**
* Get the absolute system path to the plugin directory, or a file therein
* @static
* @param string $path
* @return string
*/
public static function plugin_path( $path ) {
$base = dirname(self::$plugin_file);
if ( $path ) {
return trailingslashit($base).$path;
} else {
return untrailingslashit($base);
}
}
/**
* Get the absolute URL to the plugin directory, or a file therein
* @static
* @param string $path
* @return string
*/
public static function plugin_url( $path ) {
return plugins_url($path, self::$plugin_file);
}
public static function autoload( $class ) {
$d = DIRECTORY_SEPARATOR;
$classes_dir = self::plugin_path( 'classes' . $d );
$separator = strrpos( $class, '\\' );
if ( false !== $separator ) {
if ( 0 !== strpos( $class, 'Action_Scheduler' ) ) {
return;
}
$class = substr( $class, $separator + 1 );
}
if ( 'Deprecated' === substr( $class, -10 ) ) {
$dir = self::plugin_path( 'deprecated' . $d );
} elseif ( self::is_class_abstract( $class ) ) {
$dir = $classes_dir . 'abstracts' . $d;
} elseif ( self::is_class_migration( $class ) ) {
$dir = $classes_dir . 'migration' . $d;
} elseif ( 'Schedule' === substr( $class, -8 ) ) {
$dir = $classes_dir . 'schedules' . $d;
} elseif ( 'Action' === substr( $class, -6 ) ) {
$dir = $classes_dir . 'actions' . $d;
} elseif ( 'Schema' === substr( $class, -6 ) ) {
$dir = $classes_dir . 'schema' . $d;
} elseif ( strpos( $class, 'ActionScheduler' ) === 0 ) {
$segments = explode( '_', $class );
$type = isset( $segments[ 1 ] ) ? $segments[ 1 ] : '';
switch ( $type ) {
case 'WPCLI':
$dir = $classes_dir . 'WP_CLI' . $d;
break;
case 'DBLogger':
case 'DBStore':
case 'HybridStore':
case 'wpPostStore':
case 'wpCommentLogger':
$dir = $classes_dir . 'data-stores' . $d;
break;
default:
$dir = $classes_dir;
break;
}
} elseif ( self::is_class_cli( $class ) ) {
$dir = $classes_dir . 'WP_CLI' . $d;
} elseif ( strpos( $class, 'CronExpression' ) === 0 ) {
$dir = self::plugin_path( 'lib' . $d . 'cron-expression' . $d );
} elseif ( strpos( $class, 'WP_Async_Request' ) === 0 ) {
$dir = self::plugin_path( 'lib' . $d );
} else {
return;
}
if ( file_exists( "{$dir}{$class}.php" ) ) {
include( "{$dir}{$class}.php" );
return;
}
}
/**
* Initialize the plugin
*
* @static
* @param string $plugin_file
*/
public static function init( $plugin_file ) {
self::$plugin_file = $plugin_file;
spl_autoload_register( array( __CLASS__, 'autoload' ) );
/**
* Fires in the early stages of Action Scheduler init hook.
*/
do_action( 'action_scheduler_pre_init' );
require_once( self::plugin_path('functions.php') );
ActionScheduler_DataController::init();
$store = self::store();
add_action( 'init', array( $store, 'init' ), 1, 0 );
$logger = self::logger();
add_action( 'init', array( $logger, 'init' ), 1, 0 );
$runner = self::runner();
add_action( 'init', array( $runner, 'init' ), 1, 0 );
$admin_view = self::admin_view();
add_action( 'init', array( $admin_view, 'init' ), 0, 0 ); // run before $store::init()
if ( apply_filters( 'action_scheduler_load_deprecated_functions', true ) ) {
require_once( self::plugin_path('deprecated/functions.php') );
}
if ( defined( 'WP_CLI' ) && WP_CLI ) {
WP_CLI::add_command( 'action-scheduler', 'ActionScheduler_WPCLI_Scheduler_command' );
if ( ! ActionScheduler_DataController::is_migration_complete() && Controller::instance()->allow_migration() ) {
$command = new Migration_Command();
$command->register();
}
}
/**
* 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 );
}
}

View File

@@ -29,7 +29,7 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
protected $table_name; protected $table_name;
/** /**
* Package name, used in translations * Package name, used to get options from WP_List_Table::get_items_per_page.
*/ */
protected $package; protected $package;
@@ -104,10 +104,12 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
/** /**
* Makes translation easier, it basically just wraps * 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 = '' ) { 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" ); throw new RuntimeException( "The bulk action $action does not have a callback method" );
} }
$actions[ $action ] = $this->translate( $label ); $actions[ $action ] = $label;
} }
return $actions; return $actions;
@@ -199,7 +201,7 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
public function get_columns() { public function get_columns() {
$columns = array_merge( $columns = array_merge(
array( 'cb' => '<input type="checkbox" />' ), array( 'cb' => '<input type="checkbox" />' ),
array_map( array( $this, 'translate' ), $this->columns ) $this->columns
); );
return $columns; return $columns;
@@ -355,7 +357,7 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
$filter = array(); $filter = array();
foreach ( $this->search_by as $column ) { 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 ); return implode( ' OR ', $filter );
} }
@@ -455,14 +457,14 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
foreach ( $options as $value => $label ) { foreach ( $options as $value => $label ) {
echo '<option value="' . esc_attr( $value ) . '" ' . esc_html( $value == $default ? 'selected' : '' ) .'>' echo '<option value="' . esc_attr( $value ) . '" ' . esc_html( $value == $default ? 'selected' : '' ) .'>'
. esc_html( $this->translate( $label ) ) . esc_html( $label )
. '</option>'; . '</option>';
} }
echo '</select>'; echo '</select>';
} }
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 '</div>'; echo '</div>';
} }
@@ -561,7 +563,8 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
protected function display_header() { protected function display_header() {
echo '<h1 class="wp-heading-inline">' . esc_attr( $this->table_header ) . '</h1>'; echo '<h1 class="wp-heading-inline">' . esc_attr( $this->table_header ) . '</h1>';
if ( $this->get_request_search_query() ) { if ( $this->get_request_search_query() ) {
echo '<span class="subtitle">' . esc_attr( $this->translate( sprintf( 'Search results for "%s"', $this->get_request_search_query() ) ) ) . '</span>'; /* translators: %s: search query */
echo '<span class="subtitle">' . esc_attr( sprintf( __( 'Search results for "%s"', 'action-scheduler' ), $this->get_request_search_query() ) ) . '</span>';
} }
echo '<hr class="wp-header-end">'; echo '<hr class="wp-header-end">';
} }
@@ -633,6 +636,21 @@ abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
echo '</form>'; echo '</form>';
} }
/**
* Process any pending actions.
*/
public function process_actions() {
$this->process_bulk_action();
$this->process_row_actions();
if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
// _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter
wp_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
exit;
}
}
/** /**
* Render the list table page, including header, notices, status filters and table. * 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. * Get the text to display in the search box on the list table.
*/ */
protected function get_search_box_placeholder() { protected function get_search_box_placeholder() {
return $this->translate( 'Search' ); return esc_html__( 'Search', 'action-scheduler' );
} }
} }

View File

@@ -44,28 +44,30 @@ abstract class ActionScheduler_Abstract_QueueRunner extends ActionScheduler_Abst
* Process an individual action. * Process an individual action.
* *
* @param int $action_id The action ID to process. * @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 { 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 ) ) { 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; return;
} }
$action = $this->store->fetch_action( $action_id ); $action = $this->store->fetch_action( $action_id );
$this->store->log_execution( $action_id ); $this->store->log_execution( $action_id );
$action->execute(); $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 ); $this->store->mark_complete( $action_id );
} catch ( Exception $e ) { } catch ( Exception $e ) {
$this->store->mark_failure( $action_id ); $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' ) ) { if ( isset( $action ) && is_a( $action, 'ActionScheduler_Action' ) && $action->get_schedule()->is_recurring() ) {
$this->schedule_next_instance( $action ); $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. * Schedule the next instance of the action if necessary.
* *
* @param ActionScheduler_Action $action * @param ActionScheduler_Action $action
* @param int $action_id
*/ */
protected function schedule_next_instance( ActionScheduler_Action $action ) { protected function schedule_next_instance( ActionScheduler_Action $action, $action_id ) {
$schedule = $action->get_schedule(); try {
$next = $schedule->next( as_get_datetime_object() ); ActionScheduler::factory()->repeat( $action );
} catch ( Exception $e ) {
if ( ! is_null( $next ) && $schedule->is_recurring() ) { do_action( 'action_scheduler_failed_to_schedule_next_instance', $action_id, $e, $action );
$this->store->save_action( $action, $next );
} }
} }
@@ -98,7 +100,16 @@ abstract class ActionScheduler_Abstract_QueueRunner extends ActionScheduler_Abst
* @return int * @return int
*/ */
public function get_allowed_concurrent_batches() { 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. * Process actions in the queue.
* *
* @author Jeremy Pry * @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. * @return int The number of actions processed.
*/ */
abstract public function run(); abstract public function run( $context = '' );
} }

View File

@@ -0,0 +1,102 @@
<?php
/**
* Class ActionScheduler_Abstract_RecurringSchedule
*/
abstract class ActionScheduler_Abstract_RecurringSchedule extends ActionScheduler_Abstract_Schedule {
/**
* The date & time the first instance of this schedule was setup to run (which may not be this instance).
*
* Schedule objects are attached to an action object. Each schedule stores the run date for that
* object as the start date - @see $this->start - and logic to calculate the next run date after
* that - @see $this->calculate_next(). The $first_date property also keeps a record of when the very
* first instance of this chain of schedules ran.
*
* @var DateTime
*/
private $first_date = NULL;
/**
* Timestamp equivalent of @see $this->first_date
*
* @var int
*/
protected $first_timestamp = NULL;
/**
* The recurrance between each time an action is run using this schedule.
* Used to calculate the start date & time. Can be a number of seconds, in the
* case of ActionScheduler_IntervalSchedule, or a cron expression, as in the
* case of ActionScheduler_CronSchedule. Or something else.
*
* @var mixed
*/
protected $recurrence;
/**
* @param DateTime $date The date & time to run the action.
* @param mixed $recurrence The data used to determine the schedule's recurrance.
* @param DateTime|null $first (Optional) The date & time the first instance of this interval schedule ran. Default null, meaning this is the first instance.
*/
public function __construct( DateTime $date, $recurrence, DateTime $first = null ) {
parent::__construct( $date );
$this->first_date = empty( $first ) ? $date : $first;
$this->recurrence = $recurrence;
}
/**
* @return bool
*/
public function is_recurring() {
return true;
}
/**
* Get the date & time of the first schedule in this recurring series.
*
* @return DateTime|null
*/
public function get_first_date() {
return clone $this->first_date;
}
/**
* @return string
*/
public function get_recurrence() {
return $this->recurrence;
}
/**
* For PHP 5.2 compat, since DateTime objects can't be serialized
* @return array
*/
public function __sleep() {
$sleep_params = parent::__sleep();
$this->first_timestamp = $this->first_date->getTimestamp();
return array_merge( $sleep_params, array(
'first_timestamp',
'recurrence'
) );
}
/**
* Unserialize recurring schedules serialized/stored prior to AS 3.0.0
*
* Prior to Action Scheduler 3.0.0, schedules used different property names to refer
* to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
* was the same as ActionScheduler_SimpleSchedule::timestamp. This was addressed in
* Action Scheduler 3.0.0, where properties and property names were aligned for better
* inheritance. To maintain backward compatibility with scheduled serialized and stored
* prior to 3.0, we need to correctly map the old property names.
*/
public function __wakeup() {
parent::__wakeup();
if ( $this->first_timestamp > 0 ) {
$this->first_date = as_get_datetime_object( $this->first_timestamp );
} else {
$this->first_date = $this->get_date();
}
}
}

View File

@@ -0,0 +1,83 @@
<?php
/**
* Class ActionScheduler_Abstract_Schedule
*/
abstract class ActionScheduler_Abstract_Schedule extends ActionScheduler_Schedule_Deprecated {
/**
* The date & time the schedule is set to run.
*
* @var DateTime
*/
private $scheduled_date = NULL;
/**
* Timestamp equivalent of @see $this->scheduled_date
*
* @var int
*/
protected $scheduled_timestamp = NULL;
/**
* @param DateTime $date The date & time to run the action.
*/
public function __construct( DateTime $date ) {
$this->scheduled_date = $date;
}
/**
* Check if a schedule should recur.
*
* @return bool
*/
abstract public function is_recurring();
/**
* Calculate when the next instance of this schedule would run based on a given date & time.
*
* @param DateTime $after
* @return DateTime
*/
abstract protected function calculate_next( DateTime $after );
/**
* Get the next date & time when this schedule should run after a given date & time.
*
* @param DateTime $after
* @return DateTime|null
*/
public function get_next( DateTime $after ) {
$after = clone $after;
if ( $after > $this->scheduled_date ) {
$after = $this->calculate_next( $after );
return $after;
}
return clone $this->scheduled_date;
}
/**
* Get the date & time the schedule is set to run.
*
* @return DateTime|null
*/
public function get_date() {
return $this->scheduled_date;
}
/**
* For PHP 5.2 compat, since DateTime objects can't be serialized
* @return array
*/
public function __sleep() {
$this->scheduled_timestamp = $this->scheduled_date->getTimestamp();
return array(
'scheduled_timestamp',
);
}
public function __wakeup() {
$this->scheduled_date = as_get_datetime_object( $this->scheduled_timestamp );
unset( $this->scheduled_timestamp );
}
}

View File

@@ -0,0 +1,133 @@
<?php
/**
* Class ActionScheduler_Abstract_Schema
*
* @package Action_Scheduler
*
* @codeCoverageIgnore
*
* Utility class for creating/updating custom tables
*/
abstract class ActionScheduler_Abstract_Schema {
/**
* @var int Increment this value in derived class to trigger a schema update.
*/
protected $schema_version = 1;
/**
* @var array Names of tables that will be registered by this class.
*/
protected $tables = [];
/**
* Register tables with WordPress, and create them if needed.
*
* @return void
*/
public function register_tables() {
global $wpdb;
// make WP aware of our tables
foreach ( $this->tables as $table ) {
$wpdb->tables[] = $table;
$name = $this->get_full_table_name( $table );
$wpdb->$table = $name;
}
// create the tables
if ( $this->schema_update_required() ) {
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;
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* Abstract class for setting a basic lock to throttle some action.
*
* Class ActionScheduler_Lock
*/
abstract class ActionScheduler_Lock {
/** @var ActionScheduler_Lock */
private static $locker = NULL;
/** @var int */
protected static $lock_duration = MINUTE_IN_SECONDS;
/**
* Check if a lock is set for a given lock type.
*
* @param string $lock_type A string to identify different lock types.
* @return bool
*/
public function is_locked( $lock_type ) {
return ( $this->get_expiration( $lock_type ) >= time() );
}
/**
* Set a lock.
*
* @param string $lock_type A string to identify different lock types.
* @return bool
*/
abstract public function set( $lock_type );
/**
* If a lock is set, return the timestamp it was set to expiry.
*
* @param string $lock_type A string to identify different lock types.
* @return bool|int False if no lock is set, otherwise the timestamp for when the lock is set to expire.
*/
abstract public function get_expiration( $lock_type );
/**
* Get the amount of time to set for a given lock. 60 seconds by default.
*
* @param string $lock_type A string to identify different lock types.
* @return int
*/
protected function get_duration( $lock_type ) {
return apply_filters( 'action_scheduler_lock_duration', self::$lock_duration, $lock_type );
}
/**
* @return ActionScheduler_Lock
*/
public static function instance() {
if ( empty( self::$locker ) ) {
$class = apply_filters( 'action_scheduler_lock_class', 'ActionScheduler_OptionLock' );
self::$locker = new $class();
}
return self::$locker;
}
}

View File

@@ -0,0 +1,176 @@
<?php
/**
* Class ActionScheduler_Logger
* @codeCoverageIgnore
*/
abstract class ActionScheduler_Logger {
private static $logger = NULL;
/**
* @return ActionScheduler_Logger
*/
public static function instance() {
if ( empty(self::$logger) ) {
$class = apply_filters('action_scheduler_logger_class', 'ActionScheduler_wpCommentLogger');
self::$logger = new $class();
}
return self::$logger;
}
/**
* @param string $action_id
* @param string $message
* @param DateTime $date
*
* @return string The log entry ID
*/
abstract public function log( $action_id, $message, DateTime $date = NULL );
/**
* @param string $entry_id
*
* @return ActionScheduler_LogEntry
*/
abstract public function get_entry( $entry_id );
/**
* @param string $action_id
*
* @return ActionScheduler_LogEntry[]
*/
abstract public function get_logs( $action_id );
/**
* @codeCoverageIgnore
*/
public function init() {
$this->hook_stored_action();
add_action( 'action_scheduler_canceled_action', array( $this, 'log_canceled_action' ), 10, 1 );
add_action( 'action_scheduler_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 );
}
}
}

View File

@@ -0,0 +1,345 @@
<?php
/**
* Class ActionScheduler_Store
* @codeCoverageIgnore
*/
abstract class ActionScheduler_Store extends ActionScheduler_Store_Deprecated {
const STATUS_COMPLETE = 'complete';
const STATUS_PENDING = 'pending';
const STATUS_RUNNING = 'in-progress';
const STATUS_FAILED = 'failed';
const STATUS_CANCELED = 'canceled';
const DEFAULT_CLASS = 'ActionScheduler_wpPostStore';
/** @var ActionScheduler_Store */
private static $store = NULL;
/** @var int */
private static $max_index_length = 191;
/**
* @param ActionScheduler_Action $action
* @param DateTime $scheduled_date Optional Date of the first instance
* to store. Otherwise uses the first date of the action's
* schedule.
*
* @return string The action ID
*/
abstract public function save_action( ActionScheduler_Action $action, DateTime $scheduled_date = NULL );
/**
* @param string $action_id
*
* @return ActionScheduler_Action
*/
abstract public function fetch_action( $action_id );
/**
* @param string $hook Hook name/slug.
* @param array $params Hook arguments.
* @return string ID of the next action matching the criteria.
*/
abstract public function find_action( $hook, $params = array() );
/**
* @param array $query Query parameters.
* @param string $query_type Whether to select or count the results. Default, select.
*
* @return array|int The IDs of or count of actions matching the query.
*/
abstract public function query_actions( $query = array(), $query_type = 'select' );
/**
* Get a count of all actions in the store, grouped by status
*
* @return array
*/
abstract public function action_counts();
/**
* @param string $action_id
*/
abstract public function cancel_action( $action_id );
/**
* @param string $action_id
*/
abstract public function delete_action( $action_id );
/**
* @param string $action_id
*
* @return DateTime The date the action is schedule to run, or the date that it ran.
*/
abstract public function get_date( $action_id );
/**
* @param int $max_actions
* @param DateTime $before_date Claim only actions schedule before the given date. Defaults to now.
* @param array $hooks Claim only actions with a hook or hooks.
* @param string $group Claim only actions in the given group.
*
* @return ActionScheduler_ActionClaim
*/
abstract public function stake_claim( $max_actions = 10, DateTime $before_date = null, $hooks = array(), $group = '' );
/**
* @return int
*/
abstract public function get_claim_count();
/**
* @param ActionScheduler_ActionClaim $claim
*/
abstract public function release_claim( ActionScheduler_ActionClaim $claim );
/**
* @param string $action_id
*/
abstract public function unclaim_action( $action_id );
/**
* @param string $action_id
*/
abstract public function mark_failure( $action_id );
/**
* @param string $action_id
*/
abstract public function log_execution( $action_id );
/**
* @param string $action_id
*/
abstract public function mark_complete( $action_id );
/**
* @param string $action_id
*
* @return string
*/
abstract public function get_status( $action_id );
/**
* @param string $action_id
* @return mixed
*/
abstract public function get_claim_id( $action_id );
/**
* @param string $claim_id
* @return array
*/
abstract public function find_actions_by_claim_id( $claim_id );
/**
* @param string $comparison_operator
* @return string
*/
protected function validate_sql_comparator( $comparison_operator ) {
if ( in_array( $comparison_operator, array('!=', '>', '>=', '<', '<=', '=') ) ) {
return $comparison_operator;
}
return '=';
}
/**
* Get the time MySQL formated date/time string for an action's (next) scheduled date.
*
* @param ActionScheduler_Action $action
* @param DateTime $scheduled_date (optional)
* @return string
*/
protected function get_scheduled_date_string( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
$next = null === $scheduled_date ? $action->get_schedule()->get_date() : $scheduled_date;
if ( ! $next ) {
return '0000-00-00 00:00:00';
}
$next->setTimezone( new DateTimeZone( 'UTC' ) );
return $next->format( 'Y-m-d H:i:s' );
}
/**
* Get the time MySQL formated date/time string for an action's (next) scheduled date.
*
* @param ActionScheduler_Action $action
* @param DateTime $scheduled_date (optional)
* @return string
*/
protected function get_scheduled_date_string_local( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
$next = null === $scheduled_date ? $action->get_schedule()->get_date() : $scheduled_date;
if ( ! $next ) {
return '0000-00-00 00:00:00';
}
ActionScheduler_TimezoneHelper::set_local_timezone( $next );
return $next->format( 'Y-m-d H:i:s' );
}
/**
* Validate that we could decode action arguments.
*
* @param mixed $args The decoded arguments.
* @param int $action_id The action ID.
*
* @throws ActionScheduler_InvalidActionException When the decoded arguments are invalid.
*/
protected function validate_args( $args, $action_id ) {
// Ensure we have an array of args.
if ( ! is_array( $args ) ) {
throw ActionScheduler_InvalidActionException::from_decoding_args( $action_id );
}
// Validate JSON decoding if possible.
if ( function_exists( 'json_last_error' ) && JSON_ERROR_NONE !== json_last_error() ) {
throw ActionScheduler_InvalidActionException::from_decoding_args( $action_id, $args );
}
}
/**
* Validate a ActionScheduler_Schedule object.
*
* @param mixed $schedule The unserialized ActionScheduler_Schedule object.
* @param int $action_id The action ID.
*
* @throws ActionScheduler_InvalidActionException When the schedule is invalid.
*/
protected function validate_schedule( $schedule, $action_id ) {
if ( empty( $schedule ) || ! is_a( $schedule, 'ActionScheduler_Schedule' ) ) {
throw ActionScheduler_InvalidActionException::from_schedule( $action_id, $schedule );
}
}
/**
* InnoDB indexes have a maximum size of 767 bytes by default, which is only 191 characters with utf8mb4.
*
* Previously, AS wasn't concerned about args length, as we used the (unindex) post_content column. However,
* 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;
}
}

View File

@@ -16,6 +16,8 @@ class ActionScheduler_CanceledAction extends ActionScheduler_FinishedAction {
*/ */
public function __construct( $hook, array $args = array(), ActionScheduler_Schedule $schedule = null, $group = '' ) { public function __construct( $hook, array $args = array(), ActionScheduler_Schedule $schedule = null, $group = '' ) {
parent::__construct( $hook, $args, $schedule, $group ); parent::__construct( $hook, $args, $schedule, $group );
if ( is_null( $schedule ) ) {
$this->set_schedule( new ActionScheduler_NullSchedule() ); $this->set_schedule( new ActionScheduler_NullSchedule() );
} }
} }
}

View File

@@ -0,0 +1,146 @@
<?php
/**
* Class ActionScheduler_DBLogger
*
* Action logs data table data store.
*
* @since 3.0.0
*/
class ActionScheduler_DBLogger extends ActionScheduler_Logger {
/**
* Add a record to an action log.
*
* @param int $action_id Action ID.
* @param string $message Message to be saved in the log entry.
* @param DateTime $date Timestamp of the log entry.
*
* @return int The log entry ID.
*/
public function log( $action_id, $message, DateTime $date = null ) {
if ( empty( $date ) ) {
$date = as_get_datetime_object();
} else {
$date = clone $date;
}
$date_gmt = $date->format( 'Y-m-d H:i:s' );
ActionScheduler_TimezoneHelper::set_local_timezone( $date );
$date_local = $date->format( 'Y-m-d H:i:s' );
/** @var \wpdb $wpdb */
global $wpdb;
$wpdb->insert( $wpdb->actionscheduler_logs, [
'action_id' => $action_id,
'message' => $message,
'log_date_gmt' => $date_gmt,
'log_date_local' => $date_local,
], [ '%d', '%s', '%s', '%s' ] );
return $wpdb->insert_id;
}
/**
* Retrieve an action log entry.
*
* @param int $entry_id Log entry ID.
*
* @return ActionScheduler_LogEntry
*/
public function get_entry( $entry_id ) {
/** @var \wpdb $wpdb */
global $wpdb;
$entry = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_logs} WHERE log_id=%d", $entry_id ) );
return $this->create_entry_from_db_record( $entry );
}
/**
* Create an action log entry from a database record.
*
* @param object $record Log entry database record object.
*
* @return ActionScheduler_LogEntry
*/
private function create_entry_from_db_record( $record ) {
if ( empty( $record ) ) {
return new ActionScheduler_NullLogEntry();
}
$date = as_get_datetime_object( $record->log_date_gmt );
return new ActionScheduler_LogEntry( $record->action_id, $record->message, $date );
}
/**
* Retrieve the an action's log entries from the database.
*
* @param int $action_id Action ID.
*
* @return ActionScheduler_LogEntry[]
*/
public function get_logs( $action_id ) {
/** @var \wpdb $wpdb */
global $wpdb;
$records = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->actionscheduler_logs} WHERE action_id=%d", $action_id ) );
return array_map( [ $this, 'create_entry_from_db_record' ], $records );
}
/**
* Initialize the data store.
*
* @codeCoverageIgnore
*/
public function init() {
$table_maker = new ActionScheduler_LoggerSchema();
$table_maker->register_tables();
parent::init();
add_action( 'action_scheduler_deleted_action', [ $this, 'clear_deleted_action_logs' ], 10, 1 );
}
/**
* Delete the action logs for an action.
*
* @param int $action_id Action ID.
*/
public function clear_deleted_action_logs( $action_id ) {
/** @var \wpdb $wpdb */
global $wpdb;
$wpdb->delete( $wpdb->actionscheduler_logs, [ 'action_id' => $action_id, ], [ '%d' ] );
}
/**
* Bulk add cancel action log entries.
*
* @param array $action_ids List of action ID.
*/
public function bulk_log_cancel_actions( $action_ids ) {
if ( empty( $action_ids ) ) {
return;
}
/** @var \wpdb $wpdb */
global $wpdb;
$date = as_get_datetime_object();
$date_gmt = $date->format( 'Y-m-d H:i:s' );
ActionScheduler_TimezoneHelper::set_local_timezone( $date );
$date_local = $date->format( 'Y-m-d H:i:s' );
$message = __( 'action canceled', 'action-scheduler' );
$format = '(%d, ' . $wpdb->prepare( '%s, %s, %s', $message, $date_gmt, $date_local ) . ')';
$sql_query = "INSERT {$wpdb->actionscheduler_logs} (action_id, message, log_date_gmt, log_date_local) VALUES ";
$value_rows = [];
foreach ( $action_ids as $action_id ) {
$value_rows[] = $wpdb->prepare( $format, $action_id );
}
$sql_query .= implode( ',', $value_rows );
$wpdb->query( $sql_query );
}
}

View File

@@ -0,0 +1,803 @@
<?php
/**
* Class ActionScheduler_DBStore
*
* Action data table data store.
*
* @since 3.0.0
*/
class ActionScheduler_DBStore extends ActionScheduler_Store {
/**
* Initialize the data store
*
* @codeCoverageIgnore
*/
public function init() {
$table_maker = new ActionScheduler_StoreSchema();
$table_maker->register_tables();
}
/**
* Save an action.
*
* @param ActionScheduler_Action $action Action object.
* @param DateTime $date Optional schedule date. Default null.
*
* @return int Action ID.
*/
public function save_action( ActionScheduler_Action $action, \DateTime $date = null ) {
try {
$this->validate_action( $action );
/** @var \wpdb $wpdb */
global $wpdb;
$data = [
'hook' => $action->get_hook(),
'status' => ( $action->is_finished() ? self::STATUS_COMPLETE : self::STATUS_PENDING ),
'scheduled_date_gmt' => $this->get_scheduled_date_string( $action, $date ),
'scheduled_date_local' => $this->get_scheduled_date_string_local( $action, $date ),
'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;
}
}
}

View File

@@ -0,0 +1,380 @@
<?php
use ActionScheduler_Store as Store;
use Action_Scheduler\Migration\Runner;
use Action_Scheduler\Migration\Config;
use Action_Scheduler\Migration\Controller;
/**
* Class ActionScheduler_HybridStore
*
* A wrapper around multiple stores that fetches data from both.
*
* @since 3.0.0
*/
class ActionScheduler_HybridStore extends Store {
const DEMARKATION_OPTION = 'action_scheduler_hybrid_store_demarkation';
private $primary_store;
private $secondary_store;
private $migration_runner;
/**
* @var int The dividing line between IDs of actions created
* by the primary and secondary stores.
*
* Methods that accept an action ID will compare the ID against
* this to determine which store will contain that ID. In almost
* all cases, the ID should come from the primary store, but if
* client code is bypassing the API functions and fetching IDs
* from elsewhere, then there is a chance that an unmigrated ID
* might be requested.
*/
private $demarkation_id = 0;
/**
* ActionScheduler_HybridStore constructor.
*
* @param Config $config Migration config object.
*/
public function __construct( Config $config = null ) {
$this->demarkation_id = (int) get_option( self::DEMARKATION_OPTION, 0 );
if ( empty( $config ) ) {
$config = Controller::instance()->get_migration_config_object();
}
$this->primary_store = $config->get_destination_store();
$this->secondary_store = $config->get_source_store();
$this->migration_runner = new Runner( $config );
}
/**
* Initialize the table data store tables.
*
* @codeCoverageIgnore
*/
public function init() {
add_action( 'action_scheduler/created_table', [ $this, 'set_autoincrement' ], 10, 2 );
$this->primary_store->init();
$this->secondary_store->init();
remove_action( 'action_scheduler/created_table', [ $this, 'set_autoincrement' ], 10 );
}
/**
* When the actions table is created, set its autoincrement
* value to be one higher than the posts table to ensure that
* there are no ID collisions.
*
* @param string $table_name
* @param string $table_suffix
*
* @return void
* @codeCoverageIgnore
*/
public function set_autoincrement( $table_name, $table_suffix ) {
if ( ActionScheduler_StoreSchema::ACTIONS_TABLE === $table_suffix ) {
if ( empty( $this->demarkation_id ) ) {
$this->demarkation_id = $this->set_demarkation_id();
}
/** @var \wpdb $wpdb */
global $wpdb;
$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 );
}
}

View File

@@ -7,13 +7,11 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
const POST_TYPE = 'scheduled-action'; const POST_TYPE = 'scheduled-action';
const GROUP_TAXONOMY = 'action-group'; const GROUP_TAXONOMY = 'action-group';
const SCHEDULE_META_KEY = '_action_manager_schedule'; const SCHEDULE_META_KEY = '_action_manager_schedule';
const DEPENDENCIES_MET = 'as-post-store-dependencies-met';
/** @var DateTimeZone */ /** @var DateTimeZone */
protected $local_timezone = NULL; protected $local_timezone = NULL;
/** @var int */
private static $max_index_length = 191;
public function save_action( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ){ public function save_action( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ){
try { try {
$this->validate_action( $action ); $this->validate_action( $action );
@@ -43,7 +41,20 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
protected function save_post_array( $post_array ) { protected function save_post_array( $post_array ) {
add_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 ); 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 ); 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); $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( '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 ); 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. * action's slug, being probably unique is good enough.
* *
* For more backstory on this issue, see: * 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 * - https://core.trac.wordpress.org/ticket/21112
* *
* @param string $override_slug Short-circuit return value. * @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 ) { if ( empty($post) || $post->post_type != self::POST_TYPE ) {
return $this->get_null_action(); 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 ) { protected function get_post( $action_id ) {
@@ -131,13 +150,13 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
protected function make_action_from_post( $post ) { protected function make_action_from_post( $post ) {
$hook = $post->post_title; $hook = $post->post_title;
$args = json_decode( $post->post_content, true ); $args = json_decode( $post->post_content, true );
$this->validate_args( $args, $post->ID ); $this->validate_args( $args, $post->ID );
$schedule = get_post_meta( $post->ID, self::SCHEDULE_META_KEY, true ); $schedule = get_post_meta( $post->ID, self::SCHEDULE_META_KEY, true );
if ( empty( $schedule ) || ! is_a( $schedule, 'ActionScheduler_Schedule' ) ) { $this->validate_schedule( $schedule, $post->ID );
$schedule = new ActionScheduler_NullSchedule();
}
$group = wp_get_object_terms( $post->ID, self::GROUP_TAXONOMY, array('fields' => 'names') ); $group = wp_get_object_terms( $post->ID, self::GROUP_TAXONOMY, array('fields' => 'names') );
$group = empty( $group ) ? '' : reset($group); $group = empty( $group ) ? '' : reset($group);
@@ -286,16 +305,17 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
$sql = ( 'count' === $select_or_count ) ? 'SELECT count(p.ID)' : 'SELECT p.ID '; $sql = ( 'count' === $select_or_count ) ? 'SELECT count(p.ID)' : 'SELECT p.ID ';
$sql .= "FROM {$wpdb->posts} p"; $sql .= "FROM {$wpdb->posts} p";
$sql_params = array(); $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_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->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id";
$sql .= " INNER JOIN {$wpdb->terms} t ON tt.term_id=t.term_id"; $sql .= " INNER JOIN {$wpdb->terms} t ON tt.term_id=t.term_id";
if ( ! empty( $query['group'] ) ) {
$sql .= " AND t.slug=%s"; $sql .= " AND t.slug=%s";
$sql_params[] = $query['group']; $sql_params[] = $query['group'];
} }
}
$sql .= " WHERE post_type=%s"; $sql .= " WHERE post_type=%s";
$sql_params[] = self::POST_TYPE; $sql_params[] = self::POST_TYPE;
if ( $query['hook'] ) { if ( $query['hook'] ) {
@@ -448,6 +468,7 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
throw new InvalidArgumentException(sprintf(__('Unidentified action %s', 'action-scheduler'), $action_id)); throw new InvalidArgumentException(sprintf(__('Unidentified action %s', 'action-scheduler'), $action_id));
} }
do_action( 'action_scheduler_deleted_action', $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() ) ); $sql = $wpdb->prepare( $sql, array( $claim->get_id() ) );
$result = $wpdb->query($sql); $result = $wpdb->query($sql);
if ( $result === false ) { if ( $result === false ) {
/* translators: %s: claim ID */
throw new RuntimeException( sprintf( __('Unable to unlock claim %s. Database error.', 'action-scheduler'), $claim->get_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 ); $sql = $wpdb->prepare( $sql, $action_id, self::POST_TYPE );
$result = $wpdb->query($sql); $result = $wpdb->query($sql);
if ( $result === false ) { if ( $result === false ) {
/* translators: %s: action ID */
throw new RuntimeException( sprintf( __('Unable to unlock claim on action %s. Database error.', 'action-scheduler'), $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 ); $sql = $wpdb->prepare( $sql, self::STATUS_FAILED, $action_id, self::POST_TYPE );
$result = $wpdb->query($sql); $result = $wpdb->query($sql);
if ( $result === false ) { if ( $result === false ) {
/* translators: %s: action ID */
throw new RuntimeException( sprintf( __('Unable to mark failure on action %s. Database error.', 'action-scheduler'), $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); $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 ) { public function mark_complete( $action_id ) {
$post = get_post($action_id); $post = get_post($action_id);
if ( empty($post) || ($post->post_type != self::POST_TYPE) ) { 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. * 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 * @param ActionScheduler_Action $action
*/ */
protected function validate_action( ActionScheduler_Action $action ) { protected function validate_action( ActionScheduler_Action $action ) {
if ( strlen( json_encode( $action->get_args() ) ) > self::$max_index_length ) { try {
_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' ); 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 * @codeCoverageIgnore
*/ */
public function init() { 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 = new ActionScheduler_wpPostStore_PostTypeRegistrar();
$post_type_registrar->register(); $post_type_registrar->register();
@@ -784,24 +855,4 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
$taxonomy_registrar = new ActionScheduler_wpPostStore_TaxonomyRegistrar(); $taxonomy_registrar = new ActionScheduler_wpPostStore_TaxonomyRegistrar();
$taxonomy_registrar->register(); $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 );
}
}
} }

View File

@@ -33,8 +33,9 @@ class ActionScheduler_wpPostStore_PostStatusRegistrar {
*/ */
protected function post_status_failed_labels() { protected function post_status_failed_labels() {
$labels = array( $labels = array(
'label' => _x( 'Failed', 'post' ), 'label' => _x( 'Failed', 'post', 'action-scheduler' ),
'label_count' => _n_noop( 'Failed <span class="count">(%s)</span>', 'Failed <span class="count">(%s)</span>' ), /* translators: %s: count */
'label_count' => _n_noop( 'Failed <span class="count">(%s)</span>', 'Failed <span class="count">(%s)</span>', 'action-scheduler' ),
); );
return apply_filters( 'action_scheduler_post_status_failed_labels', $labels ); return apply_filters( 'action_scheduler_post_status_failed_labels', $labels );
@@ -47,11 +48,11 @@ class ActionScheduler_wpPostStore_PostStatusRegistrar {
*/ */
protected function post_status_running_labels() { protected function post_status_running_labels() {
$labels = array( $labels = array(
'label' => _x( 'In-Progress', 'post' ), 'label' => _x( 'In-Progress', 'post', 'action-scheduler' ),
'label_count' => _n_noop( 'In-Progress <span class="count">(%s)</span>', 'In-Progress <span class="count">(%s)</span>' ), /* translators: %s: count */
'label_count' => _n_noop( 'In-Progress <span class="count">(%s)</span>', 'In-Progress <span class="count">(%s)</span>', 'action-scheduler' ),
); );
return apply_filters( 'action_scheduler_post_status_running_labels', $labels ); return apply_filters( 'action_scheduler_post_status_running_labels', $labels );
} }
} }

View File

@@ -0,0 +1,109 @@
<?php
namespace Action_Scheduler\Migration;
/**
* Class ActionMigrator
*
* @package Action_Scheduler\Migration
*
* @since 3.0.0
*
* @codeCoverageIgnore
*/
class ActionMigrator {
/** var ActionScheduler_Store */
private $source;
/** var ActionScheduler_Store */
private $destination;
/** var LogMigrator */
private $log_migrator;
/**
* ActionMigrator constructor.
*
* @param ActionScheduler_Store $source_store Source store object.
* @param ActionScheduler_Store $destination_store Destination store object.
* @param LogMigrator $log_migrator Log migrator object.
*/
public function __construct( \ActionScheduler_Store $source_store, \ActionScheduler_Store $destination_store, LogMigrator $log_migrator ) {
$this->source = $source_store;
$this->destination = $destination_store;
$this->log_migrator = $log_migrator;
}
/**
* Migrate an action.
*
* @param int $source_action_id Action ID.
*
* @return int 0|new action ID
*/
public function migrate( $source_action_id ) {
try {
$action = $this->source->fetch_action( $source_action_id );
$status = $this->source->get_status( $source_action_id );
} catch ( \Exception $e ) {
$action = null;
$status = '';
}
if ( is_null( $action ) || empty( $status ) || ! $action->get_schedule()->get_date() ) {
// null action or empty status means the fetch operation failed or the action didn't exist
// null schedule means it's missing vital data
// delete it and move on
try {
$this->source->delete_action( $source_action_id );
} catch ( \Exception $e ) {
// nothing to do, it didn't exist in the first place
}
do_action( 'action_scheduler/no_action_to_migrate', $source_action_id, $this->source, $this->destination );
return 0;
}
try {
// Make sure the last attempt date is set correctly for completed and failed actions
$last_attempt_date = ( $status !== \ActionScheduler_Store::STATUS_PENDING ) ? $this->source->get_date( $source_action_id ) : null;
$destination_action_id = $this->destination->save_action( $action, null, $last_attempt_date );
} catch ( \Exception $e ) {
do_action( 'action_scheduler/migrate_action_failed', $source_action_id, $this->source, $this->destination );
return 0; // could not save the action in the new store
}
try {
switch ( $status ) {
case \ActionScheduler_Store::STATUS_FAILED :
$this->destination->mark_failure( $destination_action_id );
break;
case \ActionScheduler_Store::STATUS_CANCELED :
$this->destination->cancel_action( $destination_action_id );
break;
}
$this->log_migrator->migrate( $source_action_id, $destination_action_id );
$this->source->delete_action( $source_action_id );
$test_action = $this->source->fetch_action( $source_action_id );
if ( ! is_a( $test_action, 'ActionScheduler_NullAction' ) ) {
throw new \RuntimeException( sprintf( __( 'Unable to remove source migrated action %s', 'action-scheduler' ), $source_action_id ) );
}
do_action( 'action_scheduler/migrated_action', $source_action_id, $destination_action_id, $this->source, $this->destination );
return $destination_action_id;
} catch ( \Exception $e ) {
// could not delete from the old store
$this->source->mark_migrated( $source_action_id );
do_action( 'action_scheduler/migrate_action_incomplete', $source_action_id, $destination_action_id, $this->source, $this->destination );
do_action( 'action_scheduler/migrated_action', $source_action_id, $destination_action_id, $this->source, $this->destination );
return $destination_action_id;
}
}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* Class ActionScheduler_DBStoreMigrator
*
* A class for direct saving of actions to the table data store during migration.
*
* @since 3.0.0
*/
class ActionScheduler_DBStoreMigrator extends ActionScheduler_DBStore {
/**
* Save an action with optional last attempt date.
*
* Normally, saving an action sets its attempted date to 0000-00-00 00:00:00 because when an action is first saved,
* it can't have been attempted yet, but migrated completed actions will have an attempted date, so we need to save
* that when first saving the action.
*
* @param ActionScheduler_Action $action
* @param \DateTime $scheduled_date Optional date of the first instance to store.
* @param \DateTime $last_attempt_date Optional date the action was last attempted.
*
* @return string The action ID
* @throws \RuntimeException When the action is not saved.
*/
public function save_action( ActionScheduler_Action $action, \DateTime $scheduled_date = null, \DateTime $last_attempt_date = null ){
try {
/** @var \wpdb $wpdb */
global $wpdb;
$action_id = parent::save_action( $action, $scheduled_date );
if ( null !== $last_attempt_date ) {
$data = [
'last_attempt_gmt' => $this->get_scheduled_date_string( $action, $last_attempt_date ),
'last_attempt_local' => $this->get_scheduled_date_string_local( $action, $last_attempt_date ),
];
$wpdb->update( $wpdb->actionscheduler_actions, $data, array( 'action_id' => $action_id ), array( '%s', '%s' ), array( '%d' ) );
}
return $action_id;
} catch ( \Exception $e ) {
throw new \RuntimeException( sprintf( __( 'Error saving action: %s', 'action-scheduler' ), $e->getMessage() ), 0 );
}
}
}

View File

@@ -0,0 +1,86 @@
<?php
namespace Action_Scheduler\Migration;
use ActionScheduler_Store as Store;
/**
* Class BatchFetcher
*
* @package Action_Scheduler\Migration
*
* @since 3.0.0
*
* @codeCoverageIgnore
*/
class BatchFetcher {
/** var ActionScheduler_Store */
private $store;
/**
* BatchFetcher constructor.
*
* @param ActionScheduler_Store $source_store Source store object.
*/
public function __construct( Store $source_store ) {
$this->store = $source_store;
}
/**
* Retrieve a list of actions.
*
* @param int $count The number of actions to retrieve
*
* @return int[] A list of action IDs
*/
public function fetch( $count = 10 ) {
foreach ( $this->get_query_strategies( $count ) as $query ) {
$action_ids = $this->store->query_actions( $query );
if ( ! empty( $action_ids ) ) {
return $action_ids;
}
}
return [];
}
/**
* Generate a list of prioritized of action search parameters.
*
* @param int $count Number of actions to find.
*
* @return array
*/
private function get_query_strategies( $count ) {
$now = as_get_datetime_object();
$args = [
'date' => $now,
'per_page' => $count,
'offset' => 0,
'orderby' => 'date',
'order' => 'ASC',
];
$priorities = [
Store::STATUS_PENDING,
Store::STATUS_FAILED,
Store::STATUS_CANCELED,
Store::STATUS_COMPLETE,
Store::STATUS_RUNNING,
'', // any other unanticipated status
];
foreach ( $priorities as $status ) {
yield wp_parse_args( [
'status' => $status,
'date_compare' => '<=',
], $args );
yield wp_parse_args( [
'status' => $status,
'date_compare' => '>=',
], $args );
}
}
}

View File

@@ -0,0 +1,168 @@
<?php
namespace Action_Scheduler\Migration;
use Action_Scheduler\WP_CLI\ProgressBar;
use ActionScheduler_Logger as Logger;
use ActionScheduler_Store as Store;
/**
* Class Config
*
* @package Action_Scheduler\Migration
*
* @since 3.0.0
*
* A config builder for the ActionScheduler\Migration\Runner class
*/
class Config {
/** @var ActionScheduler_Store */
private $source_store;
/** @var ActionScheduler_Logger */
private $source_logger;
/** @var ActionScheduler_Store */
private $destination_store;
/** @var ActionScheduler_Logger */
private $destination_logger;
/** @var Progress bar */
private $progress_bar;
/** @var bool */
private $dry_run = false;
/**
* Config constructor.
*/
public function __construct() {
}
/**
* Get the configured source store.
*
* @return ActionScheduler_Store
*/
public function get_source_store() {
if ( empty( $this->source_store ) ) {
throw new \RuntimeException( __( 'Source store must be configured before running a migration', 'action-scheduler' ) );
}
return $this->source_store;
}
/**
* Set the configured source store.
*
* @param ActionScheduler_Store $store Source store object.
*/
public function set_source_store( Store $store ) {
$this->source_store = $store;
}
/**
* Get the configured source loger.
*
* @return ActionScheduler_Logger
*/
public function get_source_logger() {
if ( empty( $this->source_logger ) ) {
throw new \RuntimeException( __( 'Source logger must be configured before running a migration', 'action-scheduler' ) );
}
return $this->source_logger;
}
/**
* Set the configured source logger.
*
* @param ActionScheduler_Logger $logger
*/
public function set_source_logger( Logger $logger ) {
$this->source_logger = $logger;
}
/**
* Get the configured destination store.
*
* @return ActionScheduler_Store
*/
public function get_destination_store() {
if ( empty( $this->destination_store ) ) {
throw new \RuntimeException( __( 'Destination store must be configured before running a migration', 'action-scheduler' ) );
}
return $this->destination_store;
}
/**
* Set the configured destination store.
*
* @param ActionScheduler_Store $store
*/
public function set_destination_store( Store $store ) {
$this->destination_store = $store;
}
/**
* Get the configured destination logger.
*
* @return ActionScheduler_Logger
*/
public function get_destination_logger() {
if ( empty( $this->destination_logger ) ) {
throw new \RuntimeException( __( 'Destination logger must be configured before running a migration', 'action-scheduler' ) );
}
return $this->destination_logger;
}
/**
* Set the configured destination logger.
*
* @param ActionScheduler_Logger $logger
*/
public function set_destination_logger( Logger $logger ) {
$this->destination_logger = $logger;
}
/**
* Get flag indicating whether it's a dry run.
*
* @return bool
*/
public function get_dry_run() {
return $this->dry_run;
}
/**
* Set flag indicating whether it's a dry run.
*
* @param bool $dry_run
*/
public function set_dry_run( $dry_run ) {
$this->dry_run = (bool) $dry_run;
}
/**
* Get progress bar object.
*
* @return ActionScheduler\WPCLI\ProgressBar
*/
public function get_progress_bar() {
return $this->progress_bar;
}
/**
* Set progress bar object.
*
* @param ActionScheduler\WPCLI\ProgressBar $progress_bar
*/
public function set_progress_bar( ProgressBar $progress_bar ) {
$this->progress_bar = $progress_bar;
}
}

View File

@@ -0,0 +1,206 @@
<?php
namespace Action_Scheduler\Migration;
use Action_Scheduler\WP_CLI\Migration_Command;
use Action_Scheduler\WP_CLI\ProgressBar;
/**
* Class Controller
*
* The main plugin/initialization class for migration to custom tables.
*
* @package Action_Scheduler\Migration
*
* @since 3.0.0
*
* @codeCoverageIgnore
*/
class Controller {
private static $instance;
/** @var Action_Scheduler\Migration\Scheduler */
private $migration_scheduler;
/** @var string */
private $store_classname;
/** @var string */
private $logger_classname;
/** @var bool */
private $migrate_custom_store;
/**
* Controller constructor.
*
* @param Scheduler $migration_scheduler Migration scheduler object.
*/
protected function __construct( Scheduler $migration_scheduler ) {
$this->migration_scheduler = $migration_scheduler;
$this->store_classname = '';
}
/**
* Set the action store class name.
*
* @param string $class Classname of the store class.
*
* @return string
*/
public function get_store_class( $class ) {
if ( \ActionScheduler_DataController::is_migration_complete() ) {
return \ActionScheduler_DataController::DATASTORE_CLASS;
} elseif ( \ActionScheduler_Store::DEFAULT_CLASS !== $class ) {
$this->store_classname = $class;
return $class;
} else {
return 'ActionScheduler_HybridStore';
}
}
/**
* Set the action logger class name.
*
* @param string $class Classname of the logger class.
*
* @return string
*/
public function get_logger_class( $class ) {
\ActionScheduler_Store::instance();
if ( $this->has_custom_datastore() ) {
$this->logger_classname = $class;
return $class;
} else {
return \ActionScheduler_DataController::LOGGER_CLASS;
}
}
/**
* Get flag indicating whether a custom datastore is in use.
*
* @return bool
*/
public function has_custom_datastore() {
return (bool) $this->store_classname;
}
/**
* Set up the background migration process
*
* @return void
*/
public function schedule_migration() {
if ( \ActionScheduler_DataController::is_migration_complete() || $this->migration_scheduler->is_migration_scheduled() ) {
return;
}
$this->migration_scheduler->schedule_migration();
}
/**
* Get the default migration config object
*
* @return ActionScheduler\Migration\Config
*/
public function get_migration_config_object() {
static $config = null;
if ( ! $config ) {
$source_store = $this->store_classname ? new $this->store_classname() : new \ActionScheduler_wpPostStore();
$source_logger = $this->logger_classname ? new $this->logger_classname() : new \ActionScheduler_wpCommentLogger();
$config = new Config();
$config->set_source_store( $source_store );
$config->set_source_logger( $source_logger );
$config->set_destination_store( new \ActionScheduler_DBStoreMigrator() );
$config->set_destination_logger( new \ActionScheduler_DBLogger() );
if ( defined( 'WP_CLI' ) && WP_CLI ) {
$config->set_progress_bar( new ProgressBar( '', 0 ) );
}
}
return apply_filters( 'action_scheduler/migration_config', $config );
}
/**
* Hook dashboard migration notice.
*/
public function hook_admin_notices() {
if ( ! $this->allow_migration() || \ActionScheduler_DataController::is_migration_complete() ) {
return;
}
add_action( 'admin_notices', array( $this, 'display_migration_notice' ), 10, 0 );
}
/**
* Show a dashboard notice that migration is in progress.
*/
public function display_migration_notice() {
printf( '<div class="notice notice-warning"><p>%s</p></div>', __( 'Action Scheduler migration in progress. The list of scheduled actions may be incomplete.', 'action-scheduler' ) );
}
/**
* Add store classes. Hook migration.
*/
private function hook() {
add_filter( 'action_scheduler_store_class', array( $this, 'get_store_class' ), 100, 1 );
add_filter( 'action_scheduler_logger_class', array( $this, 'get_logger_class' ), 100, 1 );
add_action( 'init', array( $this, 'maybe_hook_migration' ) );
add_action( '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;
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Action_Scheduler\Migration;
/**
* Class DryRun_ActionMigrator
*
* @package Action_Scheduler\Migration
*
* @since 3.0.0
*
* @codeCoverageIgnore
*/
class DryRun_ActionMigrator extends ActionMigrator {
/**
* Simulate migrating an action.
*
* @param int $source_action_id Action ID.
*
* @return int
*/
public function migrate( $source_action_id ) {
do_action( 'action_scheduler/migrate_action_dry_run', $source_action_id );
return 0;
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Action_Scheduler\Migration;
/**
* Class DryRun_LogMigrator
*
* @package Action_Scheduler\Migration
*
* @codeCoverageIgnore
*/
class DryRun_LogMigrator extends LogMigrator {
/**
* Simulate migrating an action log.
*
* @param int $source_action_id Source logger object.
* @param int $destination_action_id Destination logger object.
*/
public function migrate( $source_action_id, $destination_action_id ) {
// no-op
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace Action_Scheduler\Migration;
use ActionScheduler_Logger;
/**
* Class LogMigrator
*
* @package Action_Scheduler\Migration
*
* @since 3.0.0
*
* @codeCoverageIgnore
*/
class LogMigrator {
/** @var ActionScheduler_Logger */
private $source;
/** @var ActionScheduler_Logger */
private $destination;
/**
* ActionMigrator constructor.
*
* @param ActionScheduler_Logger $source_logger Source logger object.
* @param ActionScheduler_Logger $destination_Logger Destination logger object.
*/
public function __construct( ActionScheduler_Logger $source_logger, ActionScheduler_Logger $destination_Logger ) {
$this->source = $source_logger;
$this->destination = $destination_Logger;
}
/**
* Migrate an action log.
*
* @param int $source_action_id Source logger object.
* @param int $destination_action_id Destination logger object.
*/
public function migrate( $source_action_id, $destination_action_id ) {
$logs = $this->source->get_logs( $source_action_id );
foreach ( $logs as $log ) {
if ( $log->get_action_id() == $source_action_id ) {
$this->destination->log( $destination_action_id, $log->get_message(), $log->get_date() );
}
}
}
}

View File

@@ -0,0 +1,136 @@
<?php
namespace Action_Scheduler\Migration;
/**
* Class Runner
*
* @package Action_Scheduler\Migration
*
* @since 3.0.0
*
* @codeCoverageIgnore
*/
class Runner {
/** @var ActionScheduler_Store */
private $source_store;
/** @var ActionScheduler_Store */
private $destination_store;
/** @var ActionScheduler_Logger */
private $source_logger;
/** @var ActionScheduler_Logger */
private $destination_logger;
/** @var BatchFetcher */
private $batch_fetcher;
/** @var ActionMigrator */
private $action_migrator;
/** @var LogMigrator */
private $log_migrator;
/** @var ProgressBar */
private $progress_bar;
/**
* Runner constructor.
*
* @param Config $config Migration configuration object.
*/
public function __construct( Config $config ) {
$this->source_store = $config->get_source_store();
$this->destination_store = $config->get_destination_store();
$this->source_logger = $config->get_source_logger();
$this->destination_logger = $config->get_destination_logger();
$this->batch_fetcher = new BatchFetcher( $this->source_store );
if ( $config->get_dry_run() ) {
$this->log_migrator = new DryRun_LogMigrator( $this->source_logger, $this->destination_logger );
$this->action_migrator = new DryRun_ActionMigrator( $this->source_store, $this->destination_store, $this->log_migrator );
} else {
$this->log_migrator = new LogMigrator( $this->source_logger, $this->destination_logger );
$this->action_migrator = new ActionMigrator( $this->source_store, $this->destination_store, $this->log_migrator );
}
if ( defined( 'WP_CLI' ) && WP_CLI ) {
$this->progress_bar = $config->get_progress_bar();
}
}
/**
* Run migration batch.
*
* @param int $batch_size Optional batch size. Default 10.
*
* @return int Size of batch processed.
*/
public function run( $batch_size = 10 ) {
$batch = $this->batch_fetcher->fetch( $batch_size );
$batch_size = count( $batch );
if ( ! $batch_size ) {
return 0;
}
if ( $this->progress_bar ) {
/* translators: %d: amount of actions */
$this->progress_bar->set_message( sprintf( _n( 'Migrating %d action', 'Migrating %d actions', $batch_size, 'action-scheduler' ), number_format_i18n( $batch_size ) ) );
$this->progress_bar->set_count( $batch_size );
}
$this->migrate_actions( $batch );
return $batch_size;
}
/**
* Migration a batch of actions.
*
* @param array $action_ids List of action IDs to migrate.
*/
public function migrate_actions( array $action_ids ) {
do_action( 'action_scheduler/migration_batch_starting', $action_ids );
\ActionScheduler::logger()->unhook_stored_action();
$this->destination_logger->unhook_stored_action();
foreach ( $action_ids as $source_action_id ) {
$destination_action_id = $this->action_migrator->migrate( $source_action_id );
if ( $destination_action_id ) {
$this->destination_logger->log( $destination_action_id, sprintf(
/* translators: 1: source action ID 2: source store class 3: destination action ID 4: destination store class */
__( 'Migrated action with ID %1$d in %2$s to ID %3$d in %4$s', 'action-scheduler' ),
$source_action_id,
get_class( $this->source_store ),
$destination_action_id,
get_class( $this->destination_store )
) );
}
if ( $this->progress_bar ) {
$this->progress_bar->tick();
}
}
if ( $this->progress_bar ) {
$this->progress_bar->finish();
}
\ActionScheduler::logger()->hook_stored_action();
do_action( 'action_scheduler/migration_batch_complete', $action_ids );
}
/**
* Initialize destination store and logger.
*/
public function init_destination() {
$this->destination_store->init();
$this->destination_logger->init();
}
}

View File

@@ -0,0 +1,128 @@
<?php
namespace Action_Scheduler\Migration;
/**
* Class Scheduler
*
* @package Action_Scheduler\WP_CLI
*
* @since 3.0.0
*
* @codeCoverageIgnore
*/
class Scheduler {
/** Migration action hook. */
const HOOK = 'action_scheduler/migration_hook';
/** Migration action group. */
const GROUP = 'action-scheduler-migration';
/**
* Set up the callback for the scheduled job.
*/
public function hook() {
add_action( self::HOOK, array( $this, 'run_migration' ), 10, 0 );
}
/**
* Remove the callback for the scheduled job.
*/
public function unhook() {
remove_action( self::HOOK, array( $this, 'run_migration' ), 10 );
}
/**
* The migration callback.
*/
public function run_migration() {
$migration_runner = $this->get_migration_runner();
$count = $migration_runner->run( $this->get_batch_size() );
if ( $count === 0 ) {
$this->mark_complete();
} else {
$this->schedule_migration( time() + $this->get_schedule_interval() );
}
}
/**
* Mark the migration complete.
*/
public function mark_complete() {
$this->unschedule_migration();
\ActionScheduler_DataController::mark_migration_complete();
do_action( 'action_scheduler/migration_complete' );
}
/**
* Get a flag indicating whether the migration is scheduled.
*
* @return bool Whether there is a pending action in the store to handle the migration
*/
public function is_migration_scheduled() {
$next = as_next_scheduled_action( self::HOOK );
return ! empty( $next );
}
/**
* Schedule the migration.
*
* @param int $when Optional timestamp to run the next migration batch. Defaults to now.
*
* @return string The action ID
*/
public function schedule_migration( $when = 0 ) {
$next = as_next_scheduled_action( self::HOOK );
if ( ! empty( $next ) ) {
return $next;
}
if ( empty( $when ) ) {
$when = time();
}
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 );
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* Class ActionScheduler_SimpleSchedule
*/
class ActionScheduler_CanceledSchedule extends ActionScheduler_SimpleSchedule {
/**
* Deprecated property @see $this->__wakeup() for details.
**/
private $timestamp = NULL;
/**
* @param DateTime $after
*
* @return DateTime|null
*/
public function calculate_next( DateTime $after ) {
return null;
}
/**
* Cancelled actions should never have a next schedule, even if get_next()
* is called with $after < $this->scheduled_date.
*
* @param DateTime $after
* @return DateTime|null
*/
public function get_next( DateTime $after ) {
return null;
}
/**
* @return bool
*/
public function is_recurring() {
return false;
}
/**
* Unserialize recurring schedules serialized/stored prior to AS 3.0.0
*
* Prior to Action Scheduler 3.0.0, schedules used different property names to refer
* to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
* was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
* aligned properties and property names for better inheritance. To maintain backward
* compatibility with schedules serialized and stored prior to 3.0, we need to correctly
* map the old property names with matching visibility.
*/
public function __wakeup() {
if ( ! is_null( $this->timestamp ) ) {
$this->scheduled_timestamp = $this->timestamp;
unset( $this->timestamp );
}
parent::__wakeup();
}
}

View File

@@ -0,0 +1,102 @@
<?php
/**
* Class ActionScheduler_CronSchedule
*/
class ActionScheduler_CronSchedule extends ActionScheduler_Abstract_RecurringSchedule implements ActionScheduler_Schedule {
/**
* Deprecated property @see $this->__wakeup() for details.
**/
private $start_timestamp = NULL;
/**
* Deprecated property @see $this->__wakeup() for details.
**/
private $cron = NULL;
/**
* Wrapper for parent constructor to accept a cron expression string and map it to a CronExpression for this
* objects $recurrence property.
*
* @param DateTime $start The date & time to run the action at or after. If $start aligns with the CronSchedule passed via $recurrence, it will be used. If it does not align, the first matching date after it will be used.
* @param CronExpression|string $recurrence The CronExpression used to calculate the schedule's next instance.
* @param DateTime|null $first (Optional) The date & time the first instance of this interval schedule ran. Default null, meaning this is the first instance.
*/
public function __construct( DateTime $start, $recurrence, DateTime $first = null ) {
if ( ! is_a( $recurrence, 'CronExpression' ) ) {
$recurrence = CronExpression::factory( $recurrence );
}
// For backward compatibility, we need to make sure the date is set to the first matching cron date, not whatever date is passed in. Importantly, by passing true as the 3rd param, if $start matches the cron expression, then it will be used. This was previously handled in the now deprecated next() method.
$date = $recurrence->getNextRunDate( $start, 0, true );
// parent::__construct() will set this to $date by default, but that may be different to $start now.
$first = empty( $first ) ? $start : $first;
parent::__construct( $date, $recurrence, $first );
}
/**
* Calculate when an instance of this schedule would start based on a given
* date & time using its the CronExpression.
*
* @param DateTime $after
* @return DateTime
*/
protected function calculate_next( DateTime $after ) {
return $this->recurrence->getNextRunDate( $after, 0, false );
}
/**
* @return string
*/
public function get_recurrence() {
return strval( $this->recurrence );
}
/**
* Serialize cron schedules with data required prior to AS 3.0.0
*
* Prior to Action Scheduler 3.0.0, reccuring schedules used different property names to
* refer to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
* was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
* aligned properties and property names for better inheritance. To guard against the
* possibility of infinite loops if downgrading to Action Scheduler < 3.0.0, we need to
* also store the data with the old property names so if it's unserialized in AS < 3.0,
* the schedule doesn't end up with a null recurrence.
*
* @return array
*/
public function __sleep() {
$sleep_params = parent::__sleep();
$this->start_timestamp = $this->scheduled_timestamp;
$this->cron = $this->recurrence;
return array_merge( $sleep_params, array(
'start_timestamp',
'cron'
) );
}
/**
* Unserialize cron schedules serialized/stored prior to AS 3.0.0
*
* For more background, @see ActionScheduler_Abstract_RecurringSchedule::__wakeup().
*/
public function __wakeup() {
if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->start_timestamp ) ) {
$this->scheduled_timestamp = $this->start_timestamp;
unset( $this->start_timestamp );
}
if ( is_null( $this->recurrence ) && ! is_null( $this->cron ) ) {
$this->recurrence = $this->cron;
unset( $this->cron );
}
parent::__wakeup();
}
}

View File

@@ -0,0 +1,81 @@
<?php
/**
* Class ActionScheduler_IntervalSchedule
*/
class ActionScheduler_IntervalSchedule extends ActionScheduler_Abstract_RecurringSchedule implements ActionScheduler_Schedule {
/**
* Deprecated property @see $this->__wakeup() for details.
**/
private $start_timestamp = NULL;
/**
* Deprecated property @see $this->__wakeup() for details.
**/
private $interval_in_seconds = NULL;
/**
* Calculate when this schedule should start after a given date & time using
* the number of seconds between recurrences.
*
* @param DateTime $after
* @return DateTime
*/
protected function calculate_next( DateTime $after ) {
$after->modify( '+' . (int) $this->get_recurrence() . ' seconds' );
return $after;
}
/**
* @return int
*/
public function interval_in_seconds() {
_deprecated_function( __METHOD__, '3.0.0', '(int)ActionScheduler_Abstract_RecurringSchedule::get_recurrence()' );
return (int) $this->get_recurrence();
}
/**
* Serialize interval schedules with data required prior to AS 3.0.0
*
* Prior to Action Scheduler 3.0.0, reccuring schedules used different property names to
* refer to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
* was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
* aligned properties and property names for better inheritance. To guard against the
* possibility of infinite loops if downgrading to Action Scheduler < 3.0.0, we need to
* also store the data with the old property names so if it's unserialized in AS < 3.0,
* the schedule doesn't end up with a null/false/0 recurrence.
*
* @return array
*/
public function __sleep() {
$sleep_params = parent::__sleep();
$this->start_timestamp = $this->scheduled_timestamp;
$this->interval_in_seconds = $this->recurrence;
return array_merge( $sleep_params, array(
'start_timestamp',
'interval_in_seconds'
) );
}
/**
* Unserialize interval schedules serialized/stored prior to AS 3.0.0
*
* For more background, @see ActionScheduler_Abstract_RecurringSchedule::__wakeup().
*/
public function __wakeup() {
if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->start_timestamp ) ) {
$this->scheduled_timestamp = $this->start_timestamp;
unset( $this->start_timestamp );
}
if ( is_null( $this->recurrence ) && ! is_null( $this->interval_in_seconds ) ) {
$this->recurrence = $this->interval_in_seconds;
unset( $this->interval_in_seconds );
}
parent::__wakeup();
}
}

View File

@@ -0,0 +1,28 @@
<?php
/**
* Class ActionScheduler_NullSchedule
*/
class ActionScheduler_NullSchedule extends ActionScheduler_SimpleSchedule {
/**
* Make the $date param optional and default to null.
*
* @param null $date The date & time to run the action.
*/
public function __construct( DateTime $date = null ) {
$this->scheduled_date = null;
}
/**
* This schedule has no scheduled DateTime, so we need to override the parent __sleep()
* @return array
*/
public function __sleep() {
return array();
}
public function __wakeup() {
$this->scheduled_date = null;
}
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* Class ActionScheduler_SimpleSchedule
*/
class ActionScheduler_SimpleSchedule extends ActionScheduler_Abstract_Schedule {
/**
* Deprecated property @see $this->__wakeup() for details.
**/
private $timestamp = NULL;
/**
* @param DateTime $after
*
* @return DateTime|null
*/
public function calculate_next( DateTime $after ) {
return null;
}
/**
* @return bool
*/
public function is_recurring() {
return false;
}
/**
* Serialize schedule with data required prior to AS 3.0.0
*
* Prior to Action Scheduler 3.0.0, schedules used different property names to refer
* to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
* was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
* aligned properties and property names for better inheritance. To guard against the
* scheduled date for single actions always being seen as "now" if downgrading to
* Action Scheduler < 3.0.0, we need to also store the data with the old property names
* so if it's unserialized in AS < 3.0, the schedule doesn't end up with a null recurrence.
*
* @return array
*/
public function __sleep() {
$sleep_params = parent::__sleep();
$this->timestamp = $this->scheduled_timestamp;
return array_merge( $sleep_params, array(
'timestamp',
) );
}
/**
* Unserialize recurring schedules serialized/stored prior to AS 3.0.0
*
* Prior to Action Scheduler 3.0.0, schedules used different property names to refer
* to equivalent data. For example, ActionScheduler_IntervalSchedule::start_timestamp
* was the same as ActionScheduler_SimpleSchedule::timestamp. Action Scheduler 3.0.0
* aligned properties and property names for better inheritance. To maintain backward
* compatibility with schedules serialized and stored prior to 3.0, we need to correctly
* map the old property names with matching visibility.
*/
public function __wakeup() {
if ( is_null( $this->scheduled_timestamp ) && ! is_null( $this->timestamp ) ) {
$this->scheduled_timestamp = $this->timestamp;
unset( $this->timestamp );
}
parent::__wakeup();
}
}

View File

@@ -0,0 +1,48 @@
<?php
/**
* Class ActionScheduler_LoggerSchema
*
* @codeCoverageIgnore
*
* Creates a custom table for storing action logs
*/
class ActionScheduler_LoggerSchema extends ActionScheduler_Abstract_Schema {
const LOG_TABLE = 'actionscheduler_logs';
/**
* @var int Increment this value to trigger a schema update.
*/
protected $schema_version = 2;
public function __construct() {
$this->tables = [
self::LOG_TABLE,
];
}
protected function get_table_definition( $table ) {
global $wpdb;
$table_name = $wpdb->$table;
$charset_collate = $wpdb->get_charset_collate();
$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 '';
}
}
}

View File

@@ -0,0 +1,82 @@
<?php
/**
* Class ActionScheduler_StoreSchema
*
* @codeCoverageIgnore
*
* Creates custom tables for storing scheduled actions
*/
class ActionScheduler_StoreSchema extends ActionScheduler_Abstract_Schema {
const ACTIONS_TABLE = 'actionscheduler_actions';
const CLAIMS_TABLE = 'actionscheduler_claims';
const GROUPS_TABLE = 'actionscheduler_groups';
/**
* @var int Increment this value to trigger a schema update.
*/
protected $schema_version = 2;
public function __construct() {
$this->tables = [
self::ACTIONS_TABLE,
self::CLAIMS_TABLE,
self::GROUPS_TABLE,
];
}
protected function get_table_definition( $table ) {
global $wpdb;
$table_name = $wpdb->$table;
$charset_collate = $wpdb->get_charset_collate();
$max_index_length = 191; // @see wp_get_db_schema()
switch ( $table ) {
case self::ACTIONS_TABLE:
return "CREATE TABLE {$table_name} (
action_id bigint(20) unsigned NOT NULL auto_increment,
hook varchar(191) NOT NULL,
status varchar(20) NOT NULL,
scheduled_date_gmt datetime NOT NULL default '0000-00-00 00:00:00',
scheduled_date_local datetime NOT NULL default '0000-00-00 00:00:00',
args varchar($max_index_length),
schedule longtext,
group_id bigint(20) unsigned NOT NULL default '0',
attempts int(11) NOT NULL default '0',
last_attempt_gmt datetime NOT NULL default '0000-00-00 00:00:00',
last_attempt_local datetime NOT NULL default '0000-00-00 00:00:00',
claim_id bigint(20) unsigned NOT NULL default '0',
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 '';
}
}
}

View File

@@ -0,0 +1,29 @@
<?php
/**
* Class ActionScheduler_Abstract_Schedule
*/
abstract class ActionScheduler_Schedule_Deprecated implements ActionScheduler_Schedule {
/**
* Get the date & time this schedule was created to run, or calculate when it should be run
* after a given date & time.
*
* @param DateTime $after
*
* @return DateTime|null
*/
public function next( DateTime $after = NULL ) {
if ( empty( $after ) ) {
$return_value = $this->get_date();
$replacement_method = 'get_date()';
} else {
$return_value = $this->get_next( $after );
$replacement_method = 'get_next( $after )';
}
_deprecated_function( __METHOD__, '3.0.0', __CLASS__ . '::' . $replacement_method );
return $return_value;
}
}

View File

@@ -0,0 +1,49 @@
<?php
/**
* Class ActionScheduler_Store_Deprecated
* @codeCoverageIgnore
*/
abstract class ActionScheduler_Store_Deprecated {
/**
* Mark an action that failed to fetch correctly as failed.
*
* @since 2.2.6
*
* @param int $action_id The ID of the action.
*/
public function mark_failed_fetch_action( $action_id ) {
_deprecated_function( __METHOD__, '3.0.0', 'ActionScheduler_Store::mark_failure()' );
self::$store->mark_failure( $action_id );
}
/**
* Add base hooks
*
* @since 2.2.6
*/
protected static function hook() {
_deprecated_function( __METHOD__, '3.0.0' );
}
/**
* Remove base hooks
*
* @since 2.2.6
*/
protected static function unhook() {
_deprecated_function( __METHOD__, '3.0.0' );
}
/**
* Get the site's local time.
*
* @deprecated 2.1.0
* @return DateTimeZone
*/
protected function get_local_timezone() {
_deprecated_function( __FUNCTION__, '2.1.0', 'ActionScheduler_TimezoneHelper::set_local_timezone()' );
return ActionScheduler_TimezoneHelper::get_local_timezone();
}
}

View File

@@ -4,6 +4,18 @@
* General API functions for scheduling actions * 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 * 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. * 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 * @param string $schedule A cron-link schedule string
* @see http://en.wikipedia.org/wiki/Cron * @see http://en.wikipedia.org/wiki/Cron
* * * * * * * * * * * * * *
@@ -99,17 +113,35 @@ function as_unschedule_action( $hook, $args = array(), $group = '' ) {
* @param string $group * @param string $group
*/ */
function as_unschedule_all_actions( $hook, $args = array(), $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 { do {
$unscheduled_action = as_unschedule_action( $hook, $args, $group ); $unscheduled_action = as_unschedule_action( $hook, $args, $group );
} while ( ! empty( $unscheduled_action ) ); } 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 string $hook
* @param array $args * @param array $args
* @param string $group * @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 = '' ) { function as_next_scheduled_action( $hook, $args = NULL, $group = '' ) {
$params = array(); $params = array();
@@ -119,14 +151,24 @@ function as_next_scheduled_action( $hook, $args = NULL, $group = '' ) {
if ( !empty($group) ) { if ( !empty($group) ) {
$params['group'] = $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 ); $job_id = ActionScheduler::store()->find_action( $hook, $params );
if ( empty($job_id) ) { if ( empty($job_id) ) {
return false; return false;
} }
$job = ActionScheduler::store()->fetch_action( $job_id ); $job = ActionScheduler::store()->fetch_action( $job_id );
$next = $job->get_schedule()->next(); $scheduled_date = $job->get_schedule()->get_date();
if ( $next ) { if ( $scheduled_date ) {
return (int)($next->format('U')); return (int) $scheduled_date->format( 'U' );
} elseif ( NULL === $scheduled_date ) { // pending async action with NullSchedule
return true;
} }
return false; return false;
} }

View File

@@ -0,0 +1,170 @@
<?php
/**
* WP Async Request
*
* @package WP-Background-Processing
*/
/*
Library URI: https://github.com/deliciousbrains/wp-background-processing/blob/fbbc56f2480910d7959972ec9ec0819a13c6150a/classes/wp-async-request.php
Author: Delicious Brains Inc.
Author URI: https://deliciousbrains.com/
License: GNU General Public License v2.0
License URI: https://github.com/deliciousbrains/wp-background-processing/commit/126d7945dd3d39f39cb6488ca08fe1fb66cb351a
*/
if ( ! class_exists( 'WP_Async_Request' ) ) {
/**
* Abstract WP_Async_Request class.
*
* @abstract
*/
abstract class WP_Async_Request {
/**
* Prefix
*
* (default value: 'wp')
*
* @var string
* @access protected
*/
protected $prefix = 'wp';
/**
* Action
*
* (default value: 'async_request')
*
* @var string
* @access protected
*/
protected $action = 'async_request';
/**
* Identifier
*
* @var mixed
* @access protected
*/
protected $identifier;
/**
* Data
*
* (default value: array())
*
* @var array
* @access protected
*/
protected $data = array();
/**
* Initiate new async request
*/
public function __construct() {
$this->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();
}
}

View File

@@ -155,6 +155,13 @@ class WCS_Retry_Database_Store extends WCS_Retry_Store {
'limit' => -1, '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'; $where = ' WHERE 1=1';
if ( 'any' !== $args['status'] ) { if ( 'any' !== $args['status'] ) {
@@ -173,7 +180,7 @@ class WCS_Retry_Database_Store extends WCS_Retry_Store {
$where .= $date_query->get_sql(); $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'] ) : ''; $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" ); $raw_retries = $wpdb->get_results( "SELECT * FROM {$this->get_full_table_name()} $where $orderby $limit" );

View File

@@ -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. * 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 * For more details @see https://github.com/Prospress/woocommerce-subscriptions/pull/3239
* *
* @author Automattic * @author WooCommerce
* @category Admin * @category Admin
* @package WooCommerce Subscriptions/Admin/Upgrades * @package WooCommerce Subscriptions/Admin/Upgrades
* @version 2.6.0 * @version 2.6.0

View File

@@ -19,7 +19,7 @@ class WCS_Upgrade_Notice_Manager {
* *
* @var string * @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. * The number of times the notice will be displayed before being dismissed automatically.
@@ -77,24 +77,19 @@ class WCS_Upgrade_Notice_Manager {
return; 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' ); $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 ); $notice = new WCS_Admin_Notice( 'notice notice-info', array(), $dismiss_url );
$features = array( $features = array(
array( array(
'title' => __( 'Improved experience for customers who renew their subscriptions early', 'woocommerce-subscriptions' ), 'title' => __( 'Improved scheduled action data storage', 'woocommerce-subscriptions' ),
'description' => sprintf( __( 'Allow customers to renew early from their %sMy Account > Subscription%s page without going through the checkout.', 'woocommerce-subscriptions' ), '<strong>', '</strong>' ), '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( array(
'title' => __( 'Improved subscription switching proration calculations', 'woocommerce-subscriptions' ), 'title' => __( 'Increased processing rate for scheduled payments', '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' ),
'description' => sprintf( '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' ),
'<span style="font-size: 17px;" class="dashicons dashicons-external"></span>', '<a href="https://docs.woocommerce.com/document/subscriptions/develop/complete-guide-to-scheduled-events-with-subscriptions/#section-2">', '</a>'
'<a href="' . esc_url( add_query_arg( array( 'page' => 'wc-reports', 'tab' => 'subscriptions' ), admin_url( 'admin.php' ) ) ) . '">', '</a>'
), ),
), ),
); );
@@ -108,7 +103,7 @@ class WCS_Upgrade_Notice_Manager {
$notice->set_actions( array( $notice->set_actions( array(
array( array(
'name' => __( 'Learn more', 'woocommerce-subscriptions' ), '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/',
), ),
) ); ) );

View File

@@ -2,7 +2,7 @@
<p><?php esc_html_e( 'Thank you for updating to the latest version of WooCommerce Subscriptions.', 'woocommerce-subscriptions' ); ?></p> <p><?php esc_html_e( 'Thank you for updating to the latest version of WooCommerce Subscriptions.', 'woocommerce-subscriptions' ); ?></p>
<p> <p>
<?php // translators: placeholder $1 is the Subscription version string ('2.3'), $2-3 are opening and closing <em> tags ?> <?php // translators: placeholder $1 is the Subscription version string ('2.3'), $2-3 are opening and closing <em> tags ?>
<?php echo wp_kses_post( sprintf( __( 'Version %1$s brings some great new features requested by store managers just like you (and possibly even by %2$syou%3$s).', 'woocommerce-subscriptions' ), $version, '<em>', '</em>' ) ); ?> <?php echo wp_kses_post( sprintf( __( 'Version %1$s brings some new improvements requested by store managers just like you (and possibly even by %2$syou%3$s).', 'woocommerce-subscriptions' ), $version, '<em>', '</em>' ) ); ?>
<?php esc_html_e( 'We hope you enjoy it!', 'woocommerce-subscriptions' ); ?> <?php esc_html_e( 'We hope you enjoy it!', 'woocommerce-subscriptions' ); ?>
</p> </p>
<h3><?php esc_html_e( "What's new?", 'woocommerce-subscriptions' ); ?></h3> <h3><?php esc_html_e( "What's new?", 'woocommerce-subscriptions' ); ?></h3>
@@ -13,4 +13,4 @@
</ul> </ul>
<hr> <hr>
<?php // translators: placeholder is Subscription version string ('2.3') ?> <?php // translators: placeholder is Subscription version string ('2.3') ?>
<p><?php echo esc_html( sprintf( __( 'Want to know more about Subscriptions %s and these new features?', 'woocommerce-subscriptions' ), $version ) ); ?></p> <p><?php echo esc_html( sprintf( __( 'Want to know more about Subscriptions %s?', 'woocommerce-subscriptions' ), $version ) ); ?></p>

View File

@@ -19,10 +19,21 @@ if ( ! defined( 'ABSPATH' ) ) {
* Display a recurring cart's subtotal * Display a recurring cart's subtotal
* *
* @access public * @access public
* @param WC_Cart $cart The cart do print the subtotal html for.
* @return string * @return string
*/ */
function wcs_cart_totals_subtotal_html( $cart ) { 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 .= ' <small class="tax_label">' . WC()->countries->inc_tax_or_vat() . '</small>';
} elseif ( ! $cart->display_prices_including_tax() && wc_prices_include_tax() ) {
$subtotal_html .= ' <small class="tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
}
}
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 * @param WC_Cart The cart to display the total for.
* @return void
*/ */
function wcs_cart_totals_order_total_html( $cart ) { function wcs_cart_totals_order_total_html( $cart ) {
$value = '<strong>' . $cart->get_total() . '</strong> '; $order_total_html = '<strong>' . $cart->get_total() . '</strong> ';
$tax_total_html = '';
// If prices are tax inclusive, show taxes here // If prices are tax inclusive, show taxes here
if ( wc_tax_enabled() && $cart->tax_display_cart == 'incl' ) { 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 ) ) { if ( ! empty( $tax_string_array ) ) {
// translators: placeholder is price string, denotes tax included in cart/order total // translators: placeholder is price string, denotes tax included in cart/order total
$value .= '<small class="includes_tax">' . sprintf( _x( '(Includes %s)', 'includes tax', 'woocommerce-subscriptions' ), implode( ', ', $tax_string_array ) ) . '</small>'; $tax_total_html = '<small class="includes_tax"> ' . sprintf( _x( '(includes %s)', 'includes tax', 'woocommerce-subscriptions' ), implode( ', ', $tax_string_array ) ) . '</small>';
} }
} }
// Apply WooCommerce core filter // 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 ) );
} }
/** /**

View File

@@ -796,7 +796,10 @@ function wcs_copy_order_item( $from_item, &$to_item ) {
) ); ) );
break; break;
case 'tax': 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( $to_item->set_props( array(
'rate_id' => $from_item->get_rate_id(), 'rate_id' => $from_item->get_rate_id(),
'label' => $from_item->get_label(), '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(), 'tax_total' => $from_item->get_tax_total(),
'shipping_tax_total' => $from_item->get_shipping_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; break;
case 'fee': case 'fee':
/** @var WC_Order_Item_Fee $from_item */ /** @var WC_Order_Item_Fee $from_item */

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