This commit is contained in:
Remco Tolsma
2022-10-21 13:34:45 +02:00
parent 2bbca688af
commit 50b02db331
562 changed files with 47883 additions and 23303 deletions

View File

@@ -1,57 +0,0 @@
jQuery(document).ready(function($){
if(arePointersEnabled()){
setTimeout(showSubscriptionPointers, 800); // give TinyMCE a chance to finish loading
}
$('select#product-type').change(function(){
if(arePointersEnabled()){
$('#product-type').pointer('close');
}
});
$('#_subscription_price, #_subscription_period, #_subscription_length').change(function(){
if(arePointersEnabled()){
$('.options_group.subscription_pricing').pointer('close');
$('#product-type').pointer('close');
}
});
function arePointersEnabled(){
if($.getParameterByName('subscription_pointers')=='true'){
return true;
} else {
return false;
}
}
function showSubscriptionPointers(){
$('#product-type').pointer({
content: WCSPointers.typePointerContent,
position: {
edge: 'left',
align: 'center'
},
close: function() {
if ($('select#product-type').val()==WCSubscriptions.productType){
$('.options_group.subscription_pricing:not(".subscription_sync")').pointer({
content: WCSPointers.pricePointerContent,
position: 'bottom',
close: function() {
dismissSubscriptionPointer();
}
}).pointer('open');
}
dismissSubscriptionPointer();
}
}).pointer('open');
}
function dismissSubscriptionPointer(){
$.post( ajaxurl, {
pointer: 'wcs_pointer',
action: 'dismiss-wp-pointer'
});
}
});

View File

@@ -1,831 +0,0 @@
jQuery(document).ready(function($){
$.extend({
getParameterByName: function(name) {
name = name.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
var regexS = '[\\?&]' + name + '=([^&#]*)';
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null) {
return '';
} else {
return decodeURIComponent(results[1].replace(/\+/g, ' '));
}
},
daysInMonth: function( month ) {
// Intentionally choose a non-leap year because we want february to have only 28 days.
return new Date(Date.UTC(2001, month, 0)).getUTCDate();
},
showHideSubscriptionMeta: function(){
if ($('select#product-type').val()==WCSubscriptions.productType) {
$('.show_if_simple').show();
$('.grouping_options').hide();
$('.options_group.pricing ._regular_price_field').hide();
$('#sale-price-period').show();
$('.hide_if_subscription').hide();
$( 'input#_manage_stock' ).change();
if('day' == $('#_subscription_period').val()) {
$('.subscription_sync').hide();
}
} else {
$('.options_group.pricing ._regular_price_field').show();
$('#sale-price-period').hide();
}
},
showHideVariableSubscriptionMeta: function(){
// In order for WooCommerce not to show the stock_status_field on variable subscriptions, make sure it has the hide if variable subscription class.
$( 'p.stock_status_field' ).addClass( 'hide_if_variable-subscription' );
if ($('select#product-type').val()=='variable-subscription') {
$( 'input#_downloadable' ).prop( 'checked', false );
$( 'input#_virtual' ).removeAttr( 'checked' );
$('.show_if_variable').show();
$('.hide_if_variable').hide();
$('.show_if_variable-subscription').show();
$('.hide_if_variable-subscription').hide();
$.showOrHideStockFields();
// Make the sale price row full width
$('.sale_price_dates_fields').prev('.form-row').addClass('form-row-full').removeClass('form-row-last');
} else {
if ( 'variable' === $('select#product-type').val() ) {
$( '.show_if_variable-subscription' ).hide();
$( '.show_if_variable' ).show();
$( '.hide_if_variable' ).hide();
$.showOrHideStockFields();
}
// Restore the sale price row width to half
$('.sale_price_dates_fields').prev('.form-row').removeClass('form-row-full').addClass('form-row-last');
}
},
showOrHideStockFields : function(){
if ( $( 'input#_manage_stock' ).is( ':checked' ) ) {
$( 'div.stock_fields' ).show();
} else {
$( 'div.stock_fields' ).hide();
}
},
setSubscriptionLengths: function(){
$('[name^="_subscription_length"], [name^="variable_subscription_length"]').each(function(){
var $lengthElement = $(this),
selectedLength = $lengthElement.val(),
hasSelectedLength = false,
matches = $lengthElement.attr('name').match(/\[(.*?)\]/),
periodSelector,
interval;
if (matches) { // Variation
periodSelector = '[name="variable_subscription_period['+matches[1]+']"]';
billingInterval = parseInt($('[name="variable_subscription_period_interval['+matches[1]+']"]').val());
} else {
periodSelector = '#_subscription_period';
billingInterval = parseInt($('#_subscription_period_interval').val());
}
$lengthElement.empty();
$.each(WCSubscriptions.subscriptionLengths[ $(periodSelector).val() ], function(length,description) {
if(parseInt(length) == 0 || 0 == (parseInt(length) % billingInterval)) {
$lengthElement.append($('<option></option>').attr('value',length).text(description));
}
});
$lengthElement.children('option').each(function(){
if (this.value == selectedLength) {
hasSelectedLength = true;
return false;
}
});
if(hasSelectedLength){
$lengthElement.val(selectedLength);
} else {
$lengthElement.val(0);
}
});
},
setTrialPeriods: function(){
$('[name^="_subscription_trial_length"], [name^="variable_subscription_trial_length"]').each(function(){
var $trialLengthElement = $(this),
trialLength = $trialLengthElement.val(),
matches = $trialLengthElement.attr('name').match(/\[(.*?)\]/),
periodStrings;
if (matches) { // Variation
$trialPeriodElement = $('[name="variable_subscription_trial_period['+matches[1]+']"]');
} else {
$trialPeriodElement = $('#_subscription_trial_period');
}
selectedTrialPeriod = $trialPeriodElement.val();
$trialPeriodElement.empty();
if( parseInt(trialLength) == 1 ) {
periodStrings = WCSubscriptions.trialPeriodSingular;
} else {
periodStrings = WCSubscriptions.trialPeriodPlurals;
}
$.each(periodStrings, function(key,description) {
$trialPeriodElement.append($('<option></option>').attr('value',key).text(description));
});
$trialPeriodElement.val(selectedTrialPeriod);
});
},
setSalePeriod: function(){
$('#sale-price-period').fadeOut(80,function(){
$('#sale-price-period').text($('#_subscription_period_interval option:selected').text()+' '+$('#_subscription_period option:selected').text());
$('#sale-price-period').fadeIn(180);
});
},
setSyncOptions: function(periodField) {
if ( typeof periodField != 'undefined' ) {
if ($('select#product-type').val()=='variable-subscription') {
var $container = periodField.closest('.woocommerce_variable_attributes').find('.variable_subscription_sync');
} else {
$container = periodField.closest('#general_product_data').find('.subscription_sync');
}
var $syncWeekMonthContainer = $container.find('.subscription_sync_week_month'),
$syncWeekMonthSelect = $syncWeekMonthContainer.find('select'),
$syncAnnualContainer = $container.find('.subscription_sync_annual'),
$varSubField = $container.find('[name^="variable_subscription_payment_sync_date"]'),
billingPeriod;
if ($varSubField.length > 0) { // Variation
var matches = $varSubField.attr('name').match(/\[(.*?)\]/);
$subscriptionPeriodElement = $('[name="variable_subscription_period['+matches[1]+']"]');
} else {
$subscriptionPeriodElement = $('#_subscription_period');
}
billingPeriod = $subscriptionPeriodElement.val();
if('day'==billingPeriod) {
$syncWeekMonthSelect.val(0);
$syncAnnualContainer.find('input[type="number"]').val(0).trigger('change');
} else {
if('year'==billingPeriod) {
// Make sure the year sync fields are reset
$syncAnnualContainer.find('input[type="number"]').val(0).trigger('change');
// And the week/month field has no option selected
$syncWeekMonthSelect.val(0);
} else {
// Make sure the year sync value is 0
$syncAnnualContainer.find('input[type="number"]').val(0).trigger('change');
// And the week/month field has the appropriate options
$syncWeekMonthSelect.empty();
$.each(WCSubscriptions.syncOptions[billingPeriod], function(key,description) {
$syncWeekMonthSelect.append($('<option></option>').attr('value',key).text(description));
});
}
}
}
},
showHideSyncOptions: function(){
if($('#_subscription_payment_sync_date').length > 0 || $('.wc_input_subscription_payment_sync').length > 0){
$('.subscription_sync, .variable_subscription_sync').each(function(){ // loop through all sync field groups
var $syncWeekMonthContainer = $(this).find('.subscription_sync_week_month'),
$syncWeekMonthSelect = $syncWeekMonthContainer.find('select'),
$syncAnnualContainer = $(this).find('.subscription_sync_annual'),
$varSubField = $(this).find('[name^="variable_subscription_payment_sync_date"]'),
$slideSwitch = false, // stop the general sync field group sliding down if editing a variable subscription
billingPeriod;
if ($varSubField.length > 0) { // Variation
var matches = $varSubField.attr('name').match(/\[(.*?)\]/);
$subscriptionPeriodElement = $('[name="variable_subscription_period['+matches[1]+']"]');
if ($('select#product-type').val()=='variable-subscription') {
$slideSwitch = true;
}
} else {
$subscriptionPeriodElement = $('#_subscription_period');
if ($('select#product-type').val()==WCSubscriptions.productType) {
$slideSwitch = true;
}
}
billingPeriod = $subscriptionPeriodElement.val();
if('day'==billingPeriod) {
$(this).slideUp(400);
} else {
if ( $slideSwitch ) {
$(this).slideDown(400);
if('year'==billingPeriod) {
// Make sure the year sync fields are visible
$syncAnnualContainer.slideDown(400);
// And the week/month field is hidden
$syncWeekMonthContainer.slideUp(400);
} else {
// Make sure the year sync fields are hidden
$syncAnnualContainer.slideUp(400);
// And the week/month field is visible
$syncWeekMonthContainer.slideDown(400);
}
}
}
});
}
},
moveSubscriptionVariationFields: function(){
$('#variable_product_options .variable_subscription_pricing').not('wcs_moved').each(function(){
var $regularPriceRow = $(this).siblings('.variable_pricing'),
$trialSignUpRow = $(this).siblings('.variable_subscription_trial_sign_up'),
$saleDatesRow;
$saleDatesRow = $(this).siblings('.variable_pricing');
// Add the subscription price fields above the standard price fields
$(this).insertBefore($regularPriceRow);
$trialSignUpRow.insertBefore($(this));
// Replace the regular price field with the trial period field
$regularPriceRow.children(':first').addClass('hide_if_variable-subscription');
$(this).addClass('wcs_moved');
});
},
getVariationBulkEditValue: function(variation_action){
var value;
switch( variation_action ) {
case 'variable_subscription_period':
case 'variable_subscription_trial_period':
value = prompt( WCSubscriptions.bulkEditPeriodMessage );
break;
case 'variable_subscription_period_interval':
value = prompt( WCSubscriptions.bulkEditIntervalhMessage );
break;
case 'variable_subscription_trial_length':
case 'variable_subscription_length':
value = prompt( WCSubscriptions.bulkEditLengthMessage );
break;
case 'variable_subscription_sign_up_fee':
value = prompt( woocommerce_admin_meta_boxes_variations.i18n_enter_a_value );
value = accounting.unformat( value, woocommerce_admin.mon_decimal_point );
break;
}
return value;
},
disableEnableOneTimeShipping: function() {
var is_synced_or_has_trial = false;
if ( 'variable-subscription' == $( 'select#product-type' ).val() ) {
var variations = $( '.woocommerce_variations .woocommerce_variation' ),
variations_checked = {},
number_of_pages = $( '.woocommerce_variations' ).attr( 'data-total_pages' );
$(variations).each(function() {
var period_field = $( this ).find( '.wc_input_subscription_period' ),
variation_index = $( period_field ).attr( 'name' ).match(/\[(.*?)\]/),
variation_id = $( '[name="variable_post_id['+variation_index[1]+']"]' ).val(),
period = period_field.val(),
trial = $( this ).find( '.wc_input_subscription_trial_length' ).val(),
sync_date = 0;
if ( 0 != trial ) {
is_synced_or_has_trial = true;
// break
return false;
}
if ( $( this ).find( '.variable_subscription_sync' ).length ) {
if ( 'month' == period || 'week' == period ) {
sync_date = $( '[name="variable_subscription_payment_sync_date['+variation_index[1]+']"]' ).val();
} else if ( 'year' == period ) {
sync_date = $( '[name="variable_subscription_payment_sync_date_day['+variation_index[1]+']"]' ).val();
}
if ( 0 != sync_date ) {
is_synced_or_has_trial = true;
// break
return false;
}
}
variations_checked[ variation_index[1] ] = variation_id;
});
// if we haven't found a variation synced or with a trial at this point check the backend for other product variations
if ( ( number_of_pages > 1 || 0 == variations.length ) && false == is_synced_or_has_trial ) {
var data = {
action: 'wcs_product_has_trial_or_is_synced',
product_id: woocommerce_admin_meta_boxes_variations.post_id,
variations_checked: variations_checked,
nonce: WCSubscriptions.oneTimeShippingCheckNonce,
};
$.ajax({
url: WCSubscriptions.ajaxUrl,
data: data,
type: 'POST',
success : function( response ) {
$( '#_subscription_one_time_shipping' ).prop( 'disabled', response.is_synced_or_has_trial );
// trigger an event now we have determined the one time shipping availability, in case we need to update the backend
$( '#_subscription_one_time_shipping' ).trigger( 'subscription_one_time_shipping_updated', [ response.is_synced_or_has_trial ] );
}
});
} else {
// trigger an event now we have determined the one time shipping availability, in case we need to update the backend
$( '#_subscription_one_time_shipping' ).trigger( 'subscription_one_time_shipping_updated', [ is_synced_or_has_trial ] );
}
} else {
var trial = $( '#general_product_data #_subscription_trial_length' ).val();
if ( 0 != trial ) {
is_synced_or_has_trial = true;
}
if ( $( '.subscription_sync' ).length && false == is_synced_or_has_trial ) {
var period = $( '#_subscription_period' ).val(),
sync_date = 0;
if ( 'month' == period || 'week' == period ) {
sync_date = $( '#_subscription_payment_sync_date' ).val();
} else if ( 'year' == period ) {
sync_date = $( '#_subscription_payment_sync_date_day' ).val();
}
if ( 0 != sync_date ) {
is_synced_or_has_trial = true;
}
}
}
$( '#_subscription_one_time_shipping' ).prop( 'disabled', is_synced_or_has_trial );
},
showHideSubscriptionsPanels: function() {
var tab = $( 'div.panel-wrap' ).find( 'ul.wc-tabs li' ).eq( 0 ).find( 'a' );
var panel = tab.attr( 'href' );
var visible = $( panel ).children( '.options_group' ).filter( function() {
return 'none' != $( this ).css( 'display' );
});
if ( 0 != visible.length ) {
tab.click().parent().show();
}
},
maybeDisableRemoveLinks: function() {
$( '#variable_product_options .woocommerce_variation' ).each( function() {
var $removeLink = $( this ).find( '.remove_variation' );
var can_remove_variation = ( '1' === $( this ).find( 'input.wcs-can-remove-variation').val() );
var $msg = $( this ).find( '.wcs-can-not-remove-variation-msg' );
if ( ! can_remove_variation ) {
$msg.text( $removeLink.text() );
$removeLink.replaceWith( $msg );
}
} );
},
});
$('.options_group.pricing ._sale_price_field .description').prepend('<span id="sale-price-period" style="display: none;"></span>');
// Move the subscription pricing section to the same location as the normal pricing section
$('.options_group.subscription_pricing').not('.variable_subscription_pricing .options_group.subscription_pricing').insertBefore($('.options_group.pricing:first'));
$('.show_if_subscription.clear').insertAfter($('.options_group.subscription_pricing'));
// Move the subscription variation pricing section to a better location in the DOM on load
if($('#variable_product_options .variable_subscription_pricing').length > 0) {
$.moveSubscriptionVariationFields();
}
// When a variation is added
$('#woocommerce-product-data').on('woocommerce_variations_added woocommerce_variations_loaded',function(){
$.moveSubscriptionVariationFields();
$.showHideVariableSubscriptionMeta();
$.showHideSyncOptions();
$.setSubscriptionLengths();
});
if($('.options_group.pricing').length > 0) {
$.setSalePeriod();
$.showHideSubscriptionMeta();
$.showHideVariableSubscriptionMeta();
$.setSubscriptionLengths();
$.setTrialPeriods();
$.showHideSyncOptions();
$.disableEnableOneTimeShipping();
$.showHideSubscriptionsPanels();
}
// Update subscription ranges when subscription period or interval is changed
$('#woocommerce-product-data').on('change','[name^="_subscription_period"], [name^="_subscription_period_interval"], [name^="variable_subscription_period"], [name^="variable_subscription_period_interval"]',function(){
$.setSubscriptionLengths();
$.showHideSyncOptions();
$.setSyncOptions( $(this) );
$.setSalePeriod();
$.disableEnableOneTimeShipping();
});
$('#woocommerce-product-data').on('propertychange keyup input paste change','[name^="_subscription_trial_length"], [name^="variable_subscription_trial_length"]',function(){
$.setTrialPeriods();
});
// Handles changes to sync date select/input for yearly subscription products.
$('#woocommerce-product-data').on('change', '[name^="_subscription_payment_sync_date_day"], [name^="variable_subscription_payment_sync_date_day"]', function() {
if ( 0 == $(this).val() ) {
$(this).siblings('[name^="_subscription_payment_sync_date_month"], [name^="variable_subscription_payment_sync_date_month"]').val(0);
$(this).prop('disabled', true);
}
}).on('change', '[name^="_subscription_payment_sync_date_month"], [name^="variable_subscription_payment_sync_date_month"]', function() {
var $syncDayOfMonthInput = $(this).siblings('[name^="_subscription_payment_sync_date_day"], [name^="variable_subscription_payment_sync_date_day"]');
if ( 0 < $(this).val() ) {
$syncDayOfMonthInput.val(1).attr({step: "1", min: "1", max: $.daysInMonth($(this).val())}).prop('disabled', false);
} else {
$syncDayOfMonthInput.val(0).trigger('change');
}
});
$('body').bind('woocommerce-product-type-change',function(){
$.showHideSubscriptionMeta();
$.showHideVariableSubscriptionMeta();
$.showHideSyncOptions();
$.showHideSubscriptionsPanels();
});
$('input#_downloadable, input#_virtual').change(function(){
$.showHideSubscriptionMeta();
$.showHideVariableSubscriptionMeta();
});
// Make sure the "Used for variations" checkbox is visible when adding attributes to a variable subscription
$('body').on('woocommerce_added_attribute', function(){
$.showHideVariableSubscriptionMeta();
});
if($.getParameterByName('select_subscription')=='true'){
$('select#product-type option[value="'+WCSubscriptions.productType+'"]').attr('selected', 'selected');
$('select#product-type').select().change();
}
// Before saving a subscription product, validate the trial period
$('#post').submit(function(e){
if ( WCSubscriptions.subscriptionLengths !== undefined ){
var trialLength = $('#_subscription_trial_length').val(),
selectedTrialPeriod = $('#_subscription_trial_period').val();
if ( parseInt(trialLength) >= WCSubscriptions.subscriptionLengths[selectedTrialPeriod].length ) {
alert(WCSubscriptions.trialTooLongMessages[selectedTrialPeriod]);
$('#ajax-loading').hide();
$('#publish').removeClass('button-primary-disabled');
e.preventDefault();
}
}
});
// Notify store manager that deleting an order via the Orders screen also deletes subscriptions associated with the orders
$('#posts-filter').submit(function(){
if($('[name="post_type"]').val()=='shop_order'&&($('[name="action"]').val()=='trash'||$('[name="action2"]').val()=='trash')){
var containsSubscription = false;
$('[name="post[]"]:checked').each(function(){
if(true===$('.contains_subscription',$('#post-'+$(this).val())).data('contains_subscription')){
containsSubscription = true;
}
return (false === containsSubscription);
});
if(containsSubscription){
return confirm(WCSubscriptions.bulkTrashWarning);
}
}
});
$('.order_actions .submitdelete').click(function(){
if($('[name="contains_subscription"]').val()=='true'){
return confirm(WCSubscriptions.trashWarning);
}
});
$( '#variable_product_options' ).on( 'click', '.delete.wcs-can-not-remove-variation-msg', function( e ) {
e.preventDefault();
e.stopPropagation();
} );
// Notify the store manager that trashing an order via the admin orders table row action also deletes the associated subscription if it exists
$( '.row-actions .submitdelete' ).click( function() {
var order = $( this ).closest( '.type-shop_order' ).attr( 'id' );
if ( true === $( '.contains_subscription', $( '#' + order ) ).data( 'contains_subscription' ) ) {
return confirm( WCSubscriptions.trashWarning );
}
});
// Editing a variable product
$('#variable_product_options').on('change','[name^="variable_regular_price"]',function(){
var matches = $(this).attr('name').match(/\[(.*?)\]/);
if (matches) {
var loopIndex = matches[1];
$('[name="variable_subscription_price['+loopIndex+']"]').val($(this).val());
}
});
// Editing a variable product
$('#variable_product_options').on('change','[name^="variable_subscription_price"]',function(){
var matches = $(this).attr('name').match(/\[(.*?)\]/);
if (matches) {
var loopIndex = matches[1];
$('[name="variable_regular_price['+loopIndex+']"]').val($(this).val());
}
});
// Update hidden regular price when subscription price is update on simple products
$('#general_product_data').on('change', '[name^="_subscription_price"]', function() {
$('[name="_regular_price"]').val($(this).val());
});
// Notify store manager that deleting an user via the Users screen also removed them from any subscriptions.
$('.users-php .submitdelete').on('click',function(){
return confirm(WCSubscriptions.deleteUserWarning);
});
// WC 2.4+ variation bulk edit handling
$('select.variation_actions').on('variable_subscription_sign_up_fee_ajax_data variable_subscription_period_interval_ajax_data variable_subscription_period_ajax_data variable_subscription_trial_period_ajax_data variable_subscription_trial_length_ajax_data variable_subscription_length_ajax_data', function(event, data) {
bulk_action = event.type.replace(/_ajax_data/g,'');
value = $.getVariationBulkEditValue( bulk_action );
if ( 'variable_subscription_trial_length' == bulk_action ) {
// After variations have their trial length bulk updated in the backend, flag the One Time Shipping field as needing to be updated
$( '#_subscription_one_time_shipping' ).addClass( 'wcs_ots_needs_update' );
}
if ( value != null ) {
data.value = value;
}
return data;
});
var $allowSwitching = $( document.getElementById( 'woocommerce_subscriptions_allow_switching' ) ),
$syncRenewals = $( document.getElementById( 'woocommerce_subscriptions_sync_payments' ) );
// We're on the Subscriptions settings page
if ( $allowSwitching.length > 0 ) {
var allowSwitchingEnabled = $allowSwitching.find( 'input:checked' ).length,
$switchSettingsRows = $allowSwitching.parents( 'tr' ).siblings( 'tr' ),
$prorateFirstRenewal = $( document.getElementById( 'woocommerce_subscriptions_prorate_synced_payments' ) ),
$syncRows = $syncRenewals.parents( 'tr' ).siblings( 'tr' ),
$daysNoFeeRow = $( document.getElementById( 'woocommerce_subscriptions_days_no_fee' ) ).parents( 'tr' ),
$suspensionExtensionRow = $( '#woocommerce_subscriptions_recoup_suspension' ).parents( 'tr' );
// No animation for initial hiding when switching is disabled.
if ( 0 === allowSwitchingEnabled ) {
$switchSettingsRows.hide();
}
$allowSwitching.find( 'input' ).on( 'change', function() {
var isEnabled = $allowSwitching.find( 'input:checked' ).length;
if ( 0 === isEnabled ) {
$switchSettingsRows.fadeOut();
} else if ( 0 === allowSwitchingEnabled ) { // switching was previously disabled, so settings will be hidden
$switchSettingsRows.fadeIn();
}
allowSwitchingEnabled = isEnabled;
} );
// Show/hide suspension extension setting
$( '#woocommerce_subscriptions_max_customer_suspensions' ).on( 'change', function() {
if ( $( this ).val() > 0 ) {
$suspensionExtensionRow.show();
} else {
$suspensionExtensionRow.hide();
}
} ).change();
// No animation when initially hiding prorated rows.
if ( ! $syncRenewals.is( ':checked' ) ) {
$syncRows.hide();
} else if ( 'recurring' !== $prorateFirstRenewal.val() ) {
$daysNoFeeRow.hide();
}
// Animate showing and hiding the synchronization rows.
$syncRenewals.on( 'change', function(){
if ( $( this ).is( ':checked' ) ) {
$syncRows.not( $daysNoFeeRow ).fadeIn();
$prorateFirstRenewal.change();
} else {
$syncRows.fadeOut();
}
} );
// Watch the Prorate First Renewal field for changes.
$prorateFirstRenewal.on( 'change', function() {
if ( 'recurring' === $( this ).val() ) {
$daysNoFeeRow.fadeIn();
} else {
$daysNoFeeRow.fadeOut();
}
} );
}
// Don't display the variation notice for variable subscription products
$( 'body' ).on( 'woocommerce-display-product-type-alert', function(e, select_val) {
if (select_val=='variable-subscription') {
return false;
}
});
$('.wcs_payment_method_selector').on('change', function() {
var payment_method = $(this).val();
$('.wcs_payment_method_meta_fields').hide();
$('#wcs_' + payment_method + '_fields').show();
});
// After variations have been saved/updated in the backend, flag the One Time Shipping field as needing to be updated
$( '#woocommerce-product-data' ).on( 'woocommerce_variations_saved', function() {
$( '#_subscription_one_time_shipping' ).addClass( 'wcs_ots_needs_update' );
});
// After variations have been loaded and if the One Time Shipping field needs updating, check if One Time Shipping is still available
$( '#woocommerce-product-data' ).on( 'woocommerce_variations_loaded', function() {
if ( $( '.wcs_ots_needs_update' ).length ) {
$.disableEnableOneTimeShipping();
}
});
// After variations have been loaded, check which ones are tied to subscriptions to prevent them from being deleted.
$( '#woocommerce-product-data' ).on( 'woocommerce_variations_loaded', function() {
$.maybeDisableRemoveLinks();
} );
// Triggered by $.disableEnableOneTimeShipping() after One Time shipping has been enabled or disabled for variations.
// If the One Time Shipping field needs updating, send the ajax request to update the product setting in the backend
$( '#_subscription_one_time_shipping' ).on( 'subscription_one_time_shipping_updated', function( event, is_synced_or_has_trial ) {
if ( $( '.wcs_ots_needs_update' ).length ) {
var data = {
action: 'wcs_update_one_time_shipping',
product_id: woocommerce_admin_meta_boxes_variations.post_id,
one_time_shipping_enabled: ! is_synced_or_has_trial,
one_time_shipping_selected: $( '#_subscription_one_time_shipping' ).prop( 'checked' ),
nonce: WCSubscriptions.oneTimeShippingCheckNonce,
};
$.ajax({
url: WCSubscriptions.ajaxUrl,
data: data,
type: 'POST',
success : function( response ) {
// remove the flag requiring the one time shipping field to be updated
$( '#_subscription_one_time_shipping' ).removeClass( 'wcs_ots_needs_update' );
$( '#_subscription_one_time_shipping' ).prop( 'checked', response.one_time_shipping == 'yes' ? true : false );
}
});
}
});
$( '#general_product_data, #variable_product_options' ).on( 'change', '[class^="wc_input_subscription_payment_sync"], [class^="wc_input_subscription_trial_length"]', function() {
$.disableEnableOneTimeShipping();
});
/**
* Prevents removal of variations in use by a subscription.
*/
var wcs_prevent_variation_removal = {
init: function() {
if ( 0 === $( '#woocommerce-product-data' ).length ) {
return;
}
$( 'body' ).on( 'woocommerce-product-type-change', this.product_type_change );
$( '#variable_product_options' ).on( 'reload', this.product_type_change );
$( 'select.variation_actions' ).on( 'delete_all_no_subscriptions_ajax_data', this.bulk_action_data );
this.product_type_change();
},
product_type_change: function() {
var product_type = $( '#product-type' ).val();
var $variation_actions = $( 'select.variation_actions' );
var $delete_all = $variation_actions.find( 'option[value="delete_all"], option[value="delete_all_no_subscriptions"]' );
if ( 'variable-subscription' === product_type && 'delete_all' === $delete_all.val() ) {
$delete_all.data( 'wcs_original_wc_label', $delete_all.text() )
.attr( 'value', 'delete_all_no_subscriptions' )
.text( WCSubscriptions.bulkDeleteOptionLabel );
} else if ( 'variable-subscription' !== product_type && 'delete_all_no_subscriptions' === $delete_all.val() ) {
$delete_all.text( $delete_all.data( 'wcs_original_wc_label' ) )
.attr( 'value', 'delete_all' );
}
},
bulk_action_data: function( event, data ) {
if ( window.confirm( woocommerce_admin_meta_boxes_variations.i18n_delete_all_variations ) ) {
if ( window.confirm( woocommerce_admin_meta_boxes_variations.i18n_last_warning ) ) {
data.allowed = true;
// do_variation_action() in woocommerce/assets/js/admin/meta-boxes-product-variation.js doesn't
// allow us to do anything after the AJAX request, so we need to listen to all AJAX requests for a
// little while to update the quantity and refresh the variation list.
$( document ).bind( 'ajaxComplete', wcs_prevent_variation_removal.update_qty_after_removal );
}
}
return data;
},
update_qty_after_removal: function( event, jqXHR, ajaxOptions ) {
var $variations = $( '#variable_product_options .woocommerce_variations' );
var removed;
// Not our bulk edit request. Ignore.
if ( -1 === ajaxOptions.data.indexOf( 'action=woocommerce_bulk_edit_variations' ) || -1 === ajaxOptions.data.indexOf( 'bulk_action=delete_all_no_subscriptions' ) ) {
return;
}
// Unbind so this doesn't get called every time an AJAX request is performed.
$( document ).unbind( 'ajaxComplete', wcs_prevent_variation_removal.update_qty_after_removal );
// Update variation quantity.
removed = ( 'OK' === jqXHR.statusText ) ? parseInt( jqXHR.responseText, 10 ) : 0;
$variations.attr( 'data-total', Math.max( 0, parseInt( $variations.attr( 'data-total' ), 10 ) - removed ) );
$( '#variable_product_options' ).trigger( 'reload' );
},
};
wcs_prevent_variation_removal.init();
/*
* Prevents changing of the product type for subscription products in use by a subscription.
*/
var wcs_prevent_product_type_change = {
init: function() {
if ( 'yes' !== WCSubscriptions.productHasSubscriptions ) {
return;
}
var $select = $( 'select#product-type' );
var $options = $select.find( 'option' );
var $selection = $options.filter( 'option:selected' );
if ( 'subscription' !== $selection.val() && 'variable-subscription' !== $selection.val() ) {
return;
}
$options.not( $selection ).prop( 'disabled', true );
$select.addClass( 'tips' ).attr( 'data-tip', WCSubscriptions.productTypeWarning );
},
};
wcs_prevent_product_type_change.init();
/*
* Handles enabling and disabling PayPal Standard for Subscriptions.
*/
var wcs_paypal_standard_settings = {
init: function() {
if ( 0 === $( '#woocommerce_paypal_enabled' ).length ) {
return;
}
$( '#woocommerce_paypal_enabled' ).on( 'change', this.paypal_enabled_change );
$( '#woocommerce_paypal_enabled_for_subscriptions' ).on( 'change', this.paypal_for_subscriptions_enabled );
this.paypal_enabled_change();
},
/**
* Show and hide the enable PayPal for Subscriptions checkbox when PayPal is enabled or disabled.
*/
paypal_enabled_change: function() {
var $enabled_for_subscriptions_element = $( '#woocommerce_paypal_enabled_for_subscriptions' ).closest( 'tr' );
if ( $( '#woocommerce_paypal_enabled' ).is( ':checked' ) ) {
$enabled_for_subscriptions_element.show();
} else {
$enabled_for_subscriptions_element.hide();
}
},
/**
* Display a confirm dialog when PayPal for Subscriptions is enabled (checked).
*/
paypal_for_subscriptions_enabled: function() {
if ( $( this ).is( ':checked' ) && ! confirm( WCSubscriptions.enablePayPalWarning ) ) {
$( this ).removeAttr( 'checked' );
}
}
};
wcs_paypal_standard_settings.init();
});

View File

@@ -1,239 +0,0 @@
jQuery(document).ready(function($){
var timezone = jstz.determine();
// Display the timezone for date changes
$( '#wcs-timezone' ).text( timezone.name() );
// Display times in client's timezone (based on UTC)
$( '.woocommerce-subscriptions.date-picker' ).each(function(){
var $date_input = $(this),
date_type = $date_input.attr( 'id' ),
$hour_input = $( '#'+date_type+'_hour' ),
$minute_input = $( '#'+date_type+'_minute' ),
time = $('#'+date_type+'_timestamp_utc').val(),
date = moment.unix(time);
if ( time > 0 ) {
date.local();
$date_input.val( date.year() + '-' + ( zeroise( date.months() + 1 ) ) + '-' + ( date.format( 'DD' ) ) );
$hour_input.val( date.format( 'HH' ) );
$minute_input.val( date.format( 'mm' ) );
}
});
// 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());
// Validate date when hour/minute inputs change
$( '[name$="_hour"], [name$="_minute"]' ).on( 'change', function() {
$( '#' + $(this).attr( 'name' ).replace( '_hour', '' ).replace( '_minute', '' ) ).change();
});
// Validate entire date
$( '.woocommerce-subscriptions.date-picker' ).on( 'change',function(){
// The date was deleted, clear hour/minute inputs values and set the UTC timestamp to 0
if( '' == $(this).val() ) {
$( '#' + $(this).attr( 'id' ) + '_hour' ).val('');
$( '#' + $(this).attr( 'id' ) + '_minute' ).val('');
$( '#' + $(this).attr( 'id' ) + '_timestamp_utc' ).val(0);
return;
}
var time_now = moment(),
one_hour_from_now = moment().add(1,'hours' ),
$date_input = $(this),
date_type = $date_input.attr( 'id' ),
date_pieces = $date_input.val().split( '-' ),
$hour_input = $( '#'+date_type+'_hour' ),
$minute_input = $( '#'+date_type+'_minute' ),
chosen_hour = (0 == $hour_input.val().length) ? one_hour_from_now.format( 'HH' ) : $hour_input.val(),
chosen_minute = (0 == $minute_input.val().length) ? one_hour_from_now.format( 'mm' ) : $minute_input.val(),
chosen_date = moment({
years: date_pieces[0],
months: (date_pieces[1] - 1),
date: (date_pieces[2]),
hours: chosen_hour,
minutes: chosen_minute,
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
if ( ( 'trial_end' == date_type || 'next_payment' == date_type ) && '' != $( '#start_timestamp_utc' ).val() ) {
var change_date = false,
start = moment.unix( $('#start_timestamp_utc').val() );
// Make sure trial end is after start date
if ( 'trial_end' == date_type && chosen_date.isBefore( start, 'minute' ) ) {
if ( 'trial_end' == date_type ) {
alert( wcs_admin_meta_boxes.i18n_trial_end_start_notice );
} else if ( 'next_payment' == date_type ) {
alert( wcs_admin_meta_boxes.i18n_next_payment_start_notice );
}
// Change the date
$date_input.val( start.year() + '-' + ( zeroise( start.months() + 1 ) ) + '-' + ( start.format( 'DD' ) ) );
$hour_input.val( start.format( 'HH' ) );
$minute_input.val( start.format( 'mm' ) );
}
}
// Make sure next payment is after trial end
if ( 'next_payment' == date_type && '' != $( '#trial_end_timestamp_utc' ).val() ) {
var trial_end = moment.unix( $('#trial_end_timestamp_utc').val() );
if ( chosen_date.isBefore( trial_end, 'minute' ) ) {
alert( wcs_admin_meta_boxes.i18n_next_payment_trial_notice );
$date_input.val( trial_end.year() + '-' + ( zeroise( trial_end.months() + 1 ) ) + '-' + ( trial_end.format( 'DD' ) ) );
$hour_input.val( trial_end.format( 'HH' ) );
$minute_input.val( trial_end.format( 'mm' ) );
}
}
// Make sure trial end is before next payment and expiration is after next payment date
else if ( ( 'trial_end' == date_type || 'end' == date_type ) && '' != $( '#next_payment' ).val() ) {
var change_date = false,
next_payment = moment.unix( $('#next_payment_timestamp_utc').val() );
// Make sure trial end is before or equal to next payment
if ( 'trial_end' == date_type && next_payment.isBefore( chosen_date, 'minute' ) ) {
alert( wcs_admin_meta_boxes.i18n_trial_end_next_notice );
change_date = true;
}
// Make sure end date is after next payment date
else if ( 'end' == date_type && chosen_date.isBefore( next_payment, 'minute' ) ) {
alert( wcs_admin_meta_boxes.i18n_end_date_notice );
change_date = true;
}
if ( true === change_date ) {
$date_input.val( next_payment.year() + '-' + ( zeroise( next_payment.months() + 1 ) ) + '-' + ( next_payment.format( 'DD' ) ) );
$hour_input.val( next_payment.format( 'HH' ) );
$minute_input.val( next_payment.format( 'mm' ) );
}
}
// Make sure the date is more than an hour in the future
if ( 'trial_end' != date_type && 'start' != date_type && chosen_date.unix() < one_hour_from_now.unix() ) {
alert( wcs_admin_meta_boxes.i18n_past_date_notice );
// Set date to current day
$date_input.val( one_hour_from_now.year() + '-' + ( zeroise( one_hour_from_now.months() + 1 ) ) + '-' + ( one_hour_from_now.format( 'DD' ) ) );
// Set time if current time is in the past
if ( chosen_date.hours() < one_hour_from_now.hours() || ( chosen_date.hours() == one_hour_from_now.hours() && chosen_date.minutes() < one_hour_from_now.minutes() ) ) {
$hour_input.val( one_hour_from_now.format( 'HH' ) );
$minute_input.val( one_hour_from_now.format( 'mm' ) );
}
}
if( 0 == $hour_input.val().length ){
$hour_input.val(one_hour_from_now.format( 'HH' ));
}
if( 0 == $minute_input.val().length ){
$minute_input.val(one_hour_from_now.format( 'mm' ));
}
// Update the UTC timestamp sent to the server
date_pieces = $date_input.val().split( '-' );
$('#'+date_type+'_timestamp_utc').val(moment({
years: date_pieces[0],
months: (date_pieces[1] - 1),
date: (date_pieces[2]),
hours: $hour_input.val(),
minutes: $minute_input.val(),
seconds: one_hour_from_now.format( 'ss' )
}).utc().unix());
$( 'body' ).trigger( 'wcs-updated-date',date_type);
});
function zeroise( val ) {
return (val > 9 ) ? val : '0' + val;
}
if( $( '#parent-order-id' ).is( 'select' ) ) {
wcs_update_parent_order_options();
$( '#customer_user' ).on( 'change', wcs_update_parent_order_options );
}
function wcs_update_parent_order_options() {
// Get user ID to load orders for
var user_id = $( '#customer_user' ).val();
if ( ! user_id ) {
return false;
}
var data = {
user_id: user_id,
action: 'wcs_get_customer_orders',
security: wcs_admin_meta_boxes.get_customer_orders_nonce
};
$( '#parent-order-id' ).siblings( '.select2-container' ).block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
$.ajax({
url: WCSubscriptions.ajaxUrl,
data: data,
type: 'POST',
success: function( response ) {
if ( response ) {
var $orderlist = $( '#parent-order-id' );
$( '#parent-order-id' ).select2( 'val', '' );
$orderlist.empty(); // remove old options
$orderlist.append( $( '<option></option>' ).attr( 'value', '' ).text( 'Select an order' ) );
$.each( response, function( order_id, order_number ) {
$orderlist.append( $( '<option></option>' ).attr( 'value', order_id ).text( order_number ) );
});
$( '#parent-order-id' ).siblings( '.select2-container' ).unblock();
}
}
});
return false;
};
$('body.post-type-shop_subscription #post').submit(function(){
if('wcs_process_renewal' == $( "body.post-type-shop_subscription select[name='wc_order_action']" ).val()) {
return confirm(wcs_admin_meta_boxes.process_renewal_action_warning);
}
});
$('body.post-type-shop_subscription #post').submit(function(){
if ( typeof wcs_admin_meta_boxes.change_payment_method_warning != 'undefined' && wcs_admin_meta_boxes.payment_method != $('#_payment_method').val() ) {
return confirm(wcs_admin_meta_boxes.change_payment_method_warning);
}
});
});

View File

@@ -1,8 +0,0 @@
jQuery(document).ready(function($){
$('body.post-type-shop_order #post').submit(function(){
if('wcs_retry_renewal_payment' == $( "body.post-type-shop_order select[name='wc_order_action']" ).val()) {
return confirm(wcs_admin_order_meta_boxes.retry_renewal_payment_action_warning);
}
});
});

View File

@@ -1,206 +0,0 @@
jQuery(document).ready(function($){
var upgrade_start_time = null,
total_subscriptions = wcs_update_script_data.subscription_count;
$('#update-messages').slideUp();
$('#upgrade-step-3').slideUp();
$('form#subscriptions-upgrade').on('submit',function(e){
$('#update-welcome').slideUp(600);
$('#update-messages').slideDown(600);
if('true'==wcs_update_script_data.really_old_version){
wcs_ajax_update_really_old_version();
} else if('true'==wcs_update_script_data.upgrade_to_1_5){
wcs_ajax_update_products();
wcs_ajax_update_hooks();
} else if('true'==wcs_update_script_data.upgrade_to_2_0){
wcs_ajax_update_subscriptions();
} else if('true'==wcs_update_script_data.repair_2_0){
wcs_ajax_repair_subscriptions();
} else {
wcs_ajax_update_complete();
}
e.preventDefault();
});
function wcs_ajax_update_really_old_version(){
$.ajax({
url: wcs_update_script_data.ajax_url,
type: 'POST',
data: {
action: 'wcs_upgrade',
upgrade_step: 'really_old_version',
nonce: wcs_update_script_data.upgrade_nonce
},
success: function(results) {
$('#update-messages ol').append($('<li />').text(results.message));
wcs_ajax_update_products();
wcs_ajax_update_hooks();
},
error: function(results,status,errorThrown){
wcs_ajax_update_error();
}
});
}
function wcs_ajax_update_products(){
$.ajax({
url: wcs_update_script_data.ajax_url,
type: 'POST',
data: {
action: 'wcs_upgrade',
upgrade_step: 'products',
nonce: wcs_update_script_data.upgrade_nonce
},
success: function(results) {
$('#update-messages ol').append($('<li />').text(results.message));
},
error: function(results,status,errorThrown){
wcs_ajax_update_error();
}
});
}
function wcs_ajax_update_hooks() {
var start_time = new Date();
$.ajax({
url: wcs_update_script_data.ajax_url,
type: 'POST',
data: {
action: 'wcs_upgrade',
upgrade_step: 'hooks',
nonce: wcs_update_script_data.upgrade_nonce
},
success: function(results) {
if(results.message){
var end_time = new Date(),
execution_time = Math.ceil( ( end_time.getTime() - start_time.getTime() ) / 1000 );
$('#update-messages ol').append($('<li />').text(results.message.replace('{execution_time}',execution_time)));
}
if( undefined == typeof(results.upgraded_count) || parseInt(results.upgraded_count) <= ( wcs_update_script_data.hooks_per_request - 1 ) ){
wcs_ajax_update_subscriptions();
} else {
wcs_ajax_update_hooks();
}
},
error: function(results,status,errorThrown){
wcs_ajax_update_error();
}
});
}
function wcs_ajax_update_subscriptions() {
var start_time = new Date();
if ( null === upgrade_start_time ) {
upgrade_start_time = start_time;
}
$.ajax({
url: wcs_update_script_data.ajax_url,
type: 'POST',
data: {
action: 'wcs_upgrade',
upgrade_step: 'subscriptions',
nonce: wcs_update_script_data.upgrade_nonce
},
success: function(results) {
if('success'==results.status){
var end_time = new Date(),
execution_time = Math.ceil( ( end_time.getTime() - start_time.getTime() ) / 1000 );
$('#update-messages ol').append($('<li />').text(results.message.replace('{execution_time}',execution_time)));
wcs_update_script_data.subscription_count -= results.upgraded_count;
if( "undefined" === typeof(results.upgraded_count) || parseInt(wcs_update_script_data.subscription_count) <= 0 ) {
wcs_ajax_update_complete();
} else {
wcs_ajax_update_estimated_time(results.time_message);
wcs_ajax_update_subscriptions();
}
} else {
wcs_ajax_update_error(results.message);
}
},
error: function(results,status,errorThrown){
$('<br/><span>Error: ' + results.status + ' ' + errorThrown + '</span>').appendTo('#update-error p');
wcs_ajax_update_error( $('#update-error p').html() );
}
});
}
function wcs_ajax_repair_subscriptions() {
var start_time = new Date();
if ( null === upgrade_start_time ) {
upgrade_start_time = start_time;
}
$.ajax({
url: wcs_update_script_data.ajax_url,
type: 'POST',
data: {
action: 'wcs_upgrade',
upgrade_step: 'subscription_dates_repair',
nonce: wcs_update_script_data.upgrade_nonce
},
success: function(results) {
if('success'==results.status){
var end_time = new Date(),
execution_time = Math.ceil( ( end_time.getTime() - start_time.getTime() ) / 1000 );
$('#update-messages ol').append($('<li />').text(results.message.replace('{execution_time}',execution_time)));
wcs_update_script_data.subscription_count -= results.repaired_count;
wcs_update_script_data.subscription_count -= results.unrepaired_count;
if( parseInt(wcs_update_script_data.subscription_count) <= 0 ) {
wcs_ajax_update_complete();
} else {
wcs_ajax_update_estimated_time(results.time_message);
wcs_ajax_repair_subscriptions();
}
} else {
wcs_ajax_update_error(results.message);
}
},
error: function(results,status,errorThrown){
$('<br/><span>Error: ' + results.status + ' ' + errorThrown + '</span>').appendTo('#update-error p');
wcs_ajax_update_error( $('#update-error p').html() );
}
});
}
function wcs_ajax_update_complete() {
$('#update-ajax-loader, #estimated_time').slideUp(function(){
$('#update-complete').slideDown();
});
}
function wcs_ajax_update_error(message) {
message = message || '';
if ( message.length > 0 ){
$('#update-error p').html(message);
}
$('#update-ajax-loader, #estimated_time').slideUp(function(){
$('#update-error').slideDown();
});
}
function wcs_ajax_update_estimated_time(message) {
var total_updated = total_subscriptions - wcs_update_script_data.subscription_count,
now = new Date(),
execution_time,
time_per_update,
time_left,
time_left_minutes,
time_left_seconds;
execution_time = Math.ceil( ( now.getTime() - upgrade_start_time.getTime() ) / 1000 );
time_per_update = execution_time / total_updated;
time_left = Math.floor( wcs_update_script_data.subscription_count * time_per_update );
time_left_minutes = Math.floor( time_left / 60 );
time_left_seconds = time_left % 60;
$('#estimated_time').html(message.replace( '{time_left}', time_left_minutes + ":" + zeropad(time_left_seconds) ));
}
function zeropad(number) {
var pad_char = 0,
pad = new Array(3).join(pad_char);
return (pad + number).slice(-pad.length);
}
});

View File

@@ -1,4 +1,207 @@
*** WooCommerce Subscriptions Changelog *** *** WooCommerce Subscriptions Changelog ***
2022-10-11 - version 4.6.0
* Add: Declare incompatibility with WooCommerce High-Performance Order Storage (HPOS).
* Fix: Move One Time Shipping metabox fields to use the woocommerce_product_options_shipping_product_data hook introduced in WC 6.0.
* Update: Improve handling of bulk action execution.
* Dev: Update subscriptions-core to 2.3.0
2022-08-26 - version 4.5.1
* Fix - Fatal Error caused in rare cases where quantity is zero during renewal, builds upon fix released in 4.4.0.
2022-08-04 - version 4.5.0
* Dev: Add missing `woocommerce_subscriptions_switch_link_text` and `woocommerce_subscriptions_switch_link_classes` filters for finer control of switch link. PR#4382
* Fix: Update subscription address when changed with renewals on block checkout.
2022-06-07 - version 4.4.0
* Fix - Fatal Error caused in rare cases where quantity is zero during renewal.
2022-05-24 - version 4.3.0
* Dev: Retrieving users subscriptions order has been updated to use the WooCommerce specific APIs in WC_Subscriptions_Order.
* Dev: Deprecate the WC_Subscriptions_Order::get_meta() function. Use wcs_get_objects_property( $order, $meta_key, "single", $default ) instead.
* Dev: Update the wcs_get_objects_property() function to prevent calls to get_post_meta() on objects that support calling the get_meta() function.
* Dev: Replace the get_post_meta() calls in WCS_Post_Meta_Cache_Manager with WC_Order::get_meta().
* Dev: Replace code using get_post_type( $order_id ) with WC Data Store get_order_type().
* Dev: Replace all cases of update_post_meta() where an Order ID is passed to use WC_Order::update_meta_data() instead.
2022-04-29 - version 4.2.0
* Fix: Remove WooThemes helper/updater admin notice/banner. PR#4328
* Fix: Remove PHP/deprecation notices during the early renewal and switch process when using WooCommerce Blocks 7.2. PR#4341
* Fix: Display subscription billing details in the Cart Block when purchasing products with subscription plans created using the All Products extension. subscriptions-core#149
* Update: Switch to global functions to remove deprecation warnings originating from WooCommerce Blocks. subscriptions-core#124
* Dev: Update subscriptions-core to 1.9.0. PR#4345
2022-03-22 - version 4.1.0
* Fix: Undefined variable `user_can_suspend` when a customer suspension limit is defined and the max number of suspensions has been reached. PR#4318
* Fix: Sets up subscriptions integration with the Mini Cart Block and adds new hook to filter compatible blocks. subscriptions-core#103
* Fix: When using a WooCommerce Blocks powered checkout, fix an issue that led to limited products being removed from the cart when completing a switch or renewal order. subscriptions-core#119
* Fix: When there is only one Shipping Method available in the recurring shipping package, make sure that this method is treated as selected in the current session and the `woocommerce_after_shipping_rate` action runs. subscriptions-core#115
* Fix: Don't anonymize new subscriptions related to old subscriptions via a resubscribe relationship. subscriptions-core#121
* Fix: Content that appears on the My account > Payment methods page should be translatable. subscriptions-core#125
* Dev: Update subscriptions-core to 1.7.0. PR#4319
2022-02-07 - version 4.0.2
* Dev: Update subscriptions-core to 1.6.3. PR#4307
* Fix: Replace uses of is_ajax() with wp_doing_ajax(). wcs#4296 PR#4307
* Improve handling of session data.
2022-01-19 - version 4.0.1
* Fix: Prevent fatal error when too few arguments passed to widget_title filter. PR#4302
* Dev: Update subscriptions-core to 1.6.2. PR#4302
2022-01-19 - version 4.0.0
* New: Update the minimum required WooCommerce version from 3.9 to 4.4. PR#4282
* Fix: Unable to remove subscription line items via the REST API. PR#4258
* Fix: Don't show subscription related product fields when the custom variable type products are created. PR#4215
* Fix: Add consistent margins to the recurring taxes totals row on the Checkout and Cart block. PR#4273
* Fix: Fatal error due to order with no created date in order row template. PR#4273
* Fix: Fatal error on the customer payment page for renewal orders with deleted products. PR#4273
* Fix: Prevent fatal errors on the admin subscriptions screen when a subscription fails to load. PR#4290
* Fix: Incorrect message on the subscriptions table when filtering returns no results. PR#4290
* Fix: Update Cart and Checkout Block hooks to prevent deprecation warnings. PR#4280
* Tweak: Update tooltip wording when deleting product variation. PR#4273
* Tweak: Don't show an admin error notice when a store downgrades to a previous minor version of Subscriptions. PR#4273
* Tweak: Misleading order note on payment method change. PR#4273
* Dev: Moved subscription core files moved into a new subscriptions-core library (loaded from vendor/woocommerce/subscriptions-core). PR#4121
* Dev: New `WC_Subscriptions_Plugin` class to be the main Subscriptions plugin handler class. PR#4116
* Dev: Moved and deprecated 33 functions from class `WC_Subscriptions` to more suitable classes. PR#4114
* Dev: Moved switching feature related classes into its own directory (`includes/switching/`). PR#4122
* Dev: Moved payment retry feature related classes into its own directory (`includes/payment-retry/`). PR#4146
* Dev: Moved early renewal feature related classes into its own directory (`includes/early-renewals/`). PR#4148
* Dev: Moved the "Accept manual renewals" feature and settings to a new `WCS_Manual_Renewal_Manager` class. PR#4124
* Dev: Moved the "Customer Suspensions" feature and settings code to a new `WCS_Customer_Suspension_Manager` class. PR#4138
* Dev: Moved the "Drip Downloadable Content" feature and settings to a new `WCS_Drip_Downloads_Manager` class. PR#4142
* Dev: Moved the "Allow $0 initial checkout without a payment method" feature and settings to a new `WCS_Zero_Initial_Payment_Checkout_Manager` class. PR#4145
* Dev: Moved the "Limited payment recurring coupon" feature to a new `WCS_Limited_Recurring_Coupon_Manager` class. PR#4150
* Dev: Moved the custom subscription product and checkout button text feature to a new `WCS_Call_To_Action_Button_Text_Manager` class. PR#4152
* Dev: Moved the custom active and inactive subscriber roles feature to a new `WCS_Subscriber_Role_Manager` class. PR#4153
* Dev: Removed the Action Scheduler library from WC Subscriptions since it has been included in WooCommerce core since version 3.0. PR#4202
2021-10-06 - version 3.1.6
* Fix: Add back the limited subscription setting for simple subscription products (introduced in v3.1.5). PR#4214
2021-09-28 - version 3.1.5
* Fix: Update subtracted tax amounts to account for quantity changes. PR#4107
* Fix: Correctly remove limited coupons (i.e. "Active for x payments") when the coupon code is made up of only numeric characters. PR#4139
* Fix: Only set subtracted taxes on new items when the rates don't match the base location. PR#4177
* Fix: Hide variable subscription meta fields on the Edit Product page of custom variable products. PR#4193
* Fix: Use the shipping fields to get and save the edit subscription shipping field data. PR#4161
* Fix: Fix TypeError exceptions by checking for WC_Order types inside wcs_get_subscriptions_for_order(). PR#4188
* Fix: Incorrect subtracted tax calculations when updating the subscription when the store currency uses a comma decimal separator. PR#4182
* Fix: Hide the shipping address fields on checkout when the cart contains a subscription product and the 'Force shipping to billing address' setting is selected. PR#4172
* Fix: Get the signup fee for coupon calculation inclusive or excluding tax depending on store settings. PR#4166
2021-07-22 - version 3.1.4
* Fix: Points and Rewards discounts (including WC Coupons when Points and Rewards is active) being removed from the cart when applied on the checkout page. PR#4158
* Fix: Subscriptions with one-time shipping having shipping charged on all renewal orders. PR#4156
* Fix: Rare fatal error caused by missing WC_Query class. PR#4155
* Fix: Make loading the variation edit product tab more performant on large sites. PR#4144
* Fix: Add a primary key to the last payment temporary table to improve compatibility with some hosts on larger sites. PR#4151
* Tweak: Update the wording when a customer edits their subscription address that this applies to "future renewals". PR#4118
* Dev: Add missing `woocommerce_rest_pre_insert_shop_subscription_object` filter to prepare_object_for_database() within the Subscriptions REST API controller class. PR#4119
* Dev: Add a `data-payment-method` attribute to the Early Renewal modal button action. PR#4123
2021-06-09 - version 3.1.3
* Fix: Switch calculations not correctly charging the full sign up fee when the "Prorate Sign up Fee" option is set to "Never (charge the full sign up fee)". PR#4096
* Fix: Fixes PayPal Reference Transactions integration with Checkout blocks. PR#4105
* Fix: Set the updated payment token on all pending-payment renewals so that manually retrying a failed payment uses the updated token set on the subscription. PR#4108
* Dev: Moved the `WC_Subscriptions::enqueue_scripts` and` WC_Subscriptions::equeue_styles` static functions to the new `WC_Subscriptions_Frontend_Scripts` class (deprecated existing functions). PR#4104
2021-05-19 - version 3.1.2
* Fix: Don't show recurring shipping method selection when the rates and options match the initial cart options. PR#4091
* Fix: Update the recurring shipping totals on selection and fix invalid recurring shipping method notices. PR#4099
* Fix: Update the subscription shipping address after on switch. PR#4095
2021-05-12 - version 3.1.1
* Fix: "Invalid recurring shipping method" error on checkout when attempting to purchase a subscription with one-time shipping. PR#4088
* Fix: Rework subscription webhook migration script added in 3.1 to clear cached webhook data. PR#4082
2021-05-10 - version 3.1.0
* New: Add support for WooCommerce Cart and Checkout blocks. PR#3993
* New: Support v3 subscription endpoints. PR#4001
* New: Add woocommerce_inbox_variant option. PR#4084
* New: Update the WC minimum required version to WC 3.7. PR#3914
* New: Add a new Accounts setting to allow admin to enable registration on checkout of subscription customers. PR#3883
* New: Display switch, renewal and resubscribe context in the 'Add to cart' and 'Place order' buttons. PR#3624
* Fix: Fix customer subscription caching errors on multisite installations. PR#4074
* Fix: Update the `_subtracted_base_location_taxes` when an admin edits the subscription line item subtotal. PR#4068
* Fix: Migrate existing v3 subscription webhooks to v1 when upgrading to 3.1 to maintain the same payload delivered. PR#4079
* Fix: Fatal error when processing an initial PayPal Standard payment on a manually created subscription that has no parent order. PR#4033
* Fix: Only allow reactivation of pending-canceled subscription when end date is in the future. PR#4037
* Fix: Don't add a free trial period when resubscribing to a synced subscription. PR#4045
* Fix: Catch exceptions thrown when updating a subscription's payment method. PR#4051
* Fix: Incorrect sign-up fee discount amount calculated when the customer is outside of all tax zones and prices are entered with tax included. PR#4052
* Fix: Allow paying for pending parent orders that contain a limited subscription product where the subscription is already active. PR#4061
* Fix: Show recurring shipping totals/options when a virtual product is the last product added to the cart. PR#4053
* Fix: Refactor how `_subtracted_base_location_tax` order item meta is stored on subscription items to avoid calculation issues when the quantity is changed. PR#4062
* Fix: Fixes PHP notices when using the v1/subscriptions/ID/orders REST endpoint on a subscription where one of its related orders was directly deleted from the database. PR#4058
* Tweak: Always show the delete save card button but now display a notice when trying to delete a card tied to an active subscription. PR#4076
* Tweak: Update the subscription order note to when the PayPal Standard subscription is suspended and migrated over to PayPal Reference Transactions during a switch request. PR#4057
* Tweak: Display orders in the related orders admin table sorted by date. PR#3575
* Dev: Refactor the recurring totals template. PR#3550
2021-04-16 - version 3.0.15
* Tweak: Improve compatibility with WPML. PR#4034
* Dev: Introduce filter to allow third-parties gateways to filter whether a token meta was updated. PR#4030
* Fix: Fixes for endpoint in "My Account".
2021-04-07 - version 3.0.14
* New: Add support for importing and exporting subscription variations via the WooCommerce > Products > Export/Import tools. PR#3970
* Fix: Only show one Subscriptions settings menu item on the WC Admin navigation. PR#4054
* Fix: Prevent PHP notices on the Edit Subscription page caused accessing an undefined index. PR#4056
* Fix: Existing variations will no longer be deleted when updating a regular variable product to a subscription variable product. PR#3795
* Fix: Update the `_subtracted_base_location_tax` meta data when a subscription's line item quantity is modified. PR#4039
* Fix: Next payment date calculations when the start date and last payment date are the same. PR#4017
* Dev: Update jQuery 3.0 deprecations. PR#4015
2021-02-16 - version 3.0.13
* Fix: Pass an order status array to get_order_report_data() to prevent possible fatals by 3rd parties. PR#3930
* Fix: Change logic to allow customers to pay for failed order with limited product. PR#3947
* Fix: Prevent base length from being saved in the DB when retrieved in 'apportion_length'. PR#3954
* Fix: Prevent errors when using Product Bundles (which uses WCS_Add_Cart_Item) by introducing a WCS_Add_Cart_Item::is_switch_after_fully_reduced_prepaid_term() function. PR#3957
* Fix: Introduce an SQL Transactions helper with automatic commit/rollback on shutdown. Prevents strange behaviour when a shutdown occurs during a SQL transaction. PR#3827
* Fix: [PHP 8.0] Change maybe_retry_payment() arg name to prevent unknown variable name errors. PR#3984
* Fix: Delete '_switch_totals_calc_base_length' meta incorrectly saved in the database on upgrade. PR#3958
* Fix: Prevent WC_Order_Item_Coupon::offsetGet errors during renewal. PR#4009
* Dev: Introduce new hooks to various Switch_Totals_Calculator functions. PR#3872
2021-01-06 - version 3.0.12
* New: Add an order note when subscriptions are deleted after the customer is deleted. PR#3783
* New: [WC Admin] Register items in new navigation menu. PR#3868
* New: [WC Admin] Add the Subscriptions setting to WC Admin's Settings navigation list. PR#3911
* Tweak: Fix capitalisation of Subscription webhook topic names so they match WooCommerce core. PR#3902
* Tweak: Refactor `wcs_help_tip()` to enable custom tooltip classes. PR#3871
* Tweak: Replace remaining uses of new WC_Order() with wc_get_order() to get an order instance. PR#3858
* Fix: Fix the amount customers are charged after switching after a previous switch which reduced the pre-paid term fully. PR#3805
* Fix: Calculate a gap payment when switching to a subscription with one length and no payment date to extend. PR#3879
* Fix: Only require cart payment if there's a subscription with a next payment date. PR#3899
* Fix: Only display the failed scheduled action warning to admin users who can view subscriptions. PR#3905
* Fix: Prefix attribute keys correctly before getting switch url. Fixes issues with auto-switch redirects removing pre-exisiting URL params. PR#3913
* Fix: Prevent reducing stock while saving a subscription on the admin edit subscription screen. PR#3926
* Fix: Use product object to read the original, unmodified length of a cart item during a switch. PR#3929
* Dev: Trigger create/update webhooks during Subscription REST API calls. PR#3919
* Dev: Add filters to enable third-parties to change the new and old payment method titles used in subscription changed payment method notes. PR#3908
2020-11-25 - version 3.0.11
* Tweak: Improve the missing customer error message displayed for third-party built checkouts when registration is disabled on checkout. PR#3893
* Fix: Remove the possibility of a negative calculation of prepaid days on subscription downgrades. PR#3881
* Fix: Fix issues preventing stores using the $0 Initial Checkout feature from being able to checkout. PR#3887
* Fix: Remove potential fatal error when processing end-of-prepaid term scheduled actions caused by the subscription not existing. PR#3875
* Fix: Trigger payment complete actions after renewing early via modal. PR#3888
* Fix: Performance improvements to limited products running slow queries on the shop page. PR#3895
* Fix: [PHP 8.0] Only pass array values to call_user_func_array calls. PR#3884
* Fix: [PHP 8.0] Replaces certain uses of method_exists() with is_callable(). PR#3892
2020-11-10 - version 3.0.10
* Fix: Store shipping line item instance ID separately and copy it to renewal line item meta. PR#3712
* Fix: Account for the base store tax rates subtracted from line items when paying for renewals manually. PR#3745
* Fix: Update the persistent cart while paying for renewal orders via the checkout. Fixes division by zero errors while manually renewing. PR#3824
* Fix: Clear report cache data before regenerating new preset date results preventing infinitely growing report caches. PR#3800
* Fix: Remove subscription period string transient caching to fix issues after translating. PR#3770
* Fix: WC 4.7 compatibility. Use filter to change endpoint titles in My Account. PR#3857
* Fix: When generating product price strings fallback to a default period string if no period is set. PR#3848
* Fix: Remove uses of jQuery( document ).ready() which was deprecated. PR#3846
* New: Add option to enable admin to lock in increased parent order line item prices. PR#3816
* Tweak: Allow admin to set a next payment date in 2 minutes via the edit subscription screen on staging sites. PR#3778
2020-09-29 - version 3.0.9 2020-09-29 - version 3.0.9
* Fix: Offset subscription next payment date calculations based on site time. All dates still remain in UTC, but calculations on the 1st and last day of the month will now take into account the site timezone. PR#3708 * Fix: Offset subscription next payment date calculations based on site time. All dates still remain in UTC, but calculations on the 1st and last day of the month will now take into account the site timezone. PR#3708

View File

@@ -1,329 +0,0 @@
<?php
/**
* WooCommerce Subscriptions Admin Meta Boxes
*
* Sets up the write panels used by the subscription custom order/post type
*
* @author Prospress
* @category Admin
* @package WooCommerce Subscriptions/Admin
* @version 2.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* WC_Admin_Meta_Boxes
*/
class WCS_Admin_Meta_Boxes {
/**
* Constructor
*/
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ), 25 );
add_action( 'add_meta_boxes', array( $this, 'remove_meta_boxes' ), 35 );
// We need to remove core WC save methods for meta boxes we don't use
add_action( 'woocommerce_process_shop_order_meta', array( $this, 'remove_meta_box_save' ), -1, 2 );
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_styles_scripts' ), 20 );
// We need to hook to the 'shop_order' rather than 'shop_subscription' because we declared that the 'shop_susbcription' order type supports 'order-meta-boxes'
add_action( 'woocommerce_process_shop_order_meta', 'WCS_Meta_Box_Schedule::save', 10, 2 );
add_action( 'woocommerce_process_shop_order_meta', 'WCS_Meta_Box_Subscription_Data::save', 10, 2 );
add_filter( 'woocommerce_order_actions', array( __CLASS__, 'add_subscription_actions' ), 10, 1 );
add_action( 'woocommerce_order_action_wcs_process_renewal', array( __CLASS__, 'process_renewal_action_request' ), 10, 1 );
add_action( 'woocommerce_order_action_wcs_create_pending_renewal', array( __CLASS__, 'create_pending_renewal_action_request' ), 10, 1 );
add_action( 'woocommerce_order_action_wcs_create_pending_parent', array( __CLASS__, 'create_pending_parent_action_request' ), 10, 1 );
if ( WC_Subscriptions::is_woocommerce_pre( '3.2' ) ) {
add_filter( 'woocommerce_resend_order_emails_available', array( __CLASS__, 'remove_order_email_actions' ), 0, 1 );
}
add_action( 'woocommerce_order_action_wcs_retry_renewal_payment', array( __CLASS__, 'process_retry_renewal_payment_action_request' ), 10, 1 );
// Disable stock managment while adding line items to a subscription via AJAX.
add_action( 'option_woocommerce_manage_stock', array( __CLASS__, 'override_stock_management' ) );
}
/**
* Add WC Meta boxes
*/
public function add_meta_boxes() {
global $post_ID;
add_meta_box( 'woocommerce-subscription-data', _x( 'Subscription Data', 'meta box title', 'woocommerce-subscriptions' ), 'WCS_Meta_Box_Subscription_Data::output', 'shop_subscription', 'normal', 'high' );
add_meta_box( 'woocommerce-subscription-schedule', _x( 'Schedule', 'meta box title', 'woocommerce-subscriptions' ), 'WCS_Meta_Box_Schedule::output', 'shop_subscription', 'side', 'default' );
remove_meta_box( 'woocommerce-order-data', 'shop_subscription', 'normal' );
add_meta_box( 'subscription_renewal_orders', __( 'Related Orders', 'woocommerce-subscriptions' ), 'WCS_Meta_Box_Related_Orders::output', 'shop_subscription', 'normal', 'low' );
// Only display the meta box if an order relates to a subscription
if ( 'shop_order' === get_post_type( $post_ID ) && wcs_order_contains_subscription( $post_ID, 'any' ) ) {
add_meta_box( 'subscription_renewal_orders', __( 'Related Orders', 'woocommerce-subscriptions' ), 'WCS_Meta_Box_Related_Orders::output', 'shop_order', 'normal', 'low' );
}
}
/**
* Removes the core Order Data meta box as we add our own Subscription Data meta box
*/
public function remove_meta_boxes() {
remove_meta_box( 'woocommerce-order-data', 'shop_subscription', 'normal' );
}
/**
* Don't save save some order related meta boxes
*/
public function remove_meta_box_save( $post_id, $post ) {
if ( 'shop_subscription' == $post->post_type ) {
remove_action( 'woocommerce_process_shop_order_meta', 'WC_Meta_Box_Order_Data::save', 40 );
}
}
/**
* Print admin styles/scripts
*/
public function enqueue_styles_scripts() {
global $post;
// Get admin screen id
$screen = get_current_screen();
$screen_id = isset( $screen->id ) ? $screen->id : '';
if ( 'shop_subscription' == $screen_id ) {
wp_register_script( 'jstz', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/admin/jstz.min.js' );
wp_register_script( 'momentjs', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/admin/moment.min.js' );
wp_enqueue_script( 'wcs-admin-meta-boxes-subscription', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/admin/meta-boxes-subscription.js', array( 'wc-admin-meta-boxes', 'jstz', 'momentjs' ), WC_VERSION );
wp_localize_script( 'wcs-admin-meta-boxes-subscription', 'wcs_admin_meta_boxes', apply_filters( 'woocommerce_subscriptions_admin_meta_boxes_script_parameters', array(
'i18n_start_date_notice' => __( 'Please enter a start date in the past.', 'woocommerce-subscriptions' ),
'i18n_past_date_notice' => __( 'Please enter a date at least one hour into the future.', 'woocommerce-subscriptions' ),
'i18n_next_payment_start_notice' => __( 'Please enter a date after the trial end.', 'woocommerce-subscriptions' ),
'i18n_next_payment_trial_notice' => __( 'Please enter a date after the start date.', 'woocommerce-subscriptions' ),
'i18n_trial_end_start_notice' => __( 'Please enter a date after the start date.', 'woocommerce-subscriptions' ),
'i18n_trial_end_next_notice' => __( 'Please enter a date before the next payment.', 'woocommerce-subscriptions' ),
'i18n_end_date_notice' => __( 'Please enter a date after the next payment.', 'woocommerce-subscriptions' ),
'process_renewal_action_warning' => __( "Are you sure you want to process a renewal?\n\nThis will charge the customer and email them the renewal order (if emails are enabled).", 'woocommerce-subscriptions' ),
'payment_method' => wcs_get_subscription( $post )->get_payment_method(),
'search_customers_nonce' => wp_create_nonce( 'search-customers' ),
'get_customer_orders_nonce' => wp_create_nonce( 'get-customer-orders' ),
) ) );
} else if ( 'shop_order' == $screen_id ) {
wp_enqueue_script( 'wcs-admin-meta-boxes-order', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/admin/wcs-meta-boxes-order.js' );
wp_localize_script(
'wcs-admin-meta-boxes-order',
'wcs_admin_order_meta_boxes',
array(
'retry_renewal_payment_action_warning' => __( "Are you sure you want to retry payment for this renewal order?\n\nThis will attempt to charge the customer and send renewal order emails (if emails are enabled).", 'woocommerce-subscriptions' ),
)
);
}
// Enqueue the metabox script for coupons.
if ( ! WC_Subscriptions::is_woocommerce_pre( '3.2' ) && in_array( $screen_id, array( 'shop_coupon', 'edit-shop_coupon' ) ) ) {
wp_enqueue_script(
'wcs-admin-coupon-meta-boxes',
plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/admin/meta-boxes-coupon.js',
array( 'jquery', 'wc-admin-meta-boxes' ),
WC_Subscriptions::$version
);
}
}
/**
* Adds actions to the admin edit subscriptions page, if the subscription hasn't ended and the payment method supports them.
*
* @param array $actions An array of available actions
* @return array An array of updated actions
* @since 2.0
*/
public static function add_subscription_actions( $actions ) {
global $theorder;
if ( wcs_is_subscription( $theorder ) ) {
if ( ! WC_Subscriptions::is_woocommerce_pre( '3.2' ) ) {
unset( $actions['send_order_details'], $actions['send_order_details_admin'] );
}
if ( ! $theorder->has_status( wcs_get_subscription_ended_statuses() ) ) {
if ( $theorder->payment_method_supports( 'subscription_date_changes' ) && $theorder->has_status( 'active' ) ) {
$actions['wcs_process_renewal'] = esc_html__( 'Process renewal', 'woocommerce-subscriptions' );
}
if ( count( $theorder->get_related_orders() ) > 0 ) {
$actions['wcs_create_pending_renewal'] = esc_html__( 'Create pending renewal order', 'woocommerce-subscriptions' );
} else {
$actions['wcs_create_pending_parent'] = esc_html__( 'Create pending parent order', 'woocommerce-subscriptions' );
}
}
} else if ( self::can_renewal_order_be_retried( $theorder ) ) {
$actions['wcs_retry_renewal_payment'] = esc_html__( 'Retry Renewal Payment', 'woocommerce-subscriptions' );
}
return $actions;
}
/**
* Handles the action request to process a renewal order.
*
* @param array $subscription
* @since 2.0
*/
public static function process_renewal_action_request( $subscription ) {
$subscription->add_order_note( __( 'Process renewal order action requested by admin.', 'woocommerce-subscriptions' ), false, true );
do_action( 'woocommerce_scheduled_subscription_payment', $subscription->get_id() );
}
/**
* Handles the action request to create a pending renewal order.
*
* @param array $subscription
* @since 2.0
*/
public static function create_pending_renewal_action_request( $subscription ) {
$subscription->add_order_note( __( 'Create pending renewal order requested by admin action.', 'woocommerce-subscriptions' ), false, true );
$subscription->update_status( 'on-hold' );
$renewal_order = wcs_create_renewal_order( $subscription );
if ( ! $subscription->is_manual() ) {
$renewal_order->set_payment_method( wc_get_payment_gateway_by_order( $subscription ) ); // We need to pass the payment gateway instance to be compatible with WC < 3.0, only WC 3.0+ supports passing the string name
if ( is_callable( array( $renewal_order, 'save' ) ) ) { // WC 3.0+
$renewal_order->save();
}
}
}
/**
* Handles the action request to create a pending parent order.
*
* @param array $subscription
* @since 2.3
*/
public static function create_pending_parent_action_request( $subscription ) {
if ( ! $subscription->has_status( array( 'pending', 'on-hold' ) ) ) {
$subscription->update_status( 'on-hold' );
}
$parent_order = wcs_create_order_from_subscription( $subscription, 'parent' );
$subscription->set_parent_id( wcs_get_objects_property( $parent_order, 'id' ) );
$subscription->save();
if ( ! $subscription->is_manual() ) {
$parent_order->set_payment_method( wc_get_payment_gateway_by_order( $subscription ) ); // We need to pass the payment gateway instance to be compatible with WC < 3.0, only WC 3.0+ supports passing the string name
if ( is_callable( array( $parent_order, 'save' ) ) ) { // WC 3.0+
$parent_order->save();
}
}
wc_maybe_reduce_stock_levels( $parent_order );
$subscription->add_order_note( __( 'Create pending parent order requested by admin action.', 'woocommerce-subscriptions' ), false, true );
}
/**
* Removes order related emails from the available actions.
*
* @param array $available_emails
* @since 2.0
*/
public static function remove_order_email_actions( $email_actions ) {
global $theorder;
if ( wcs_is_subscription( $theorder ) ) {
$email_actions = array();
}
return $email_actions;
}
/**
* Process the action request to retry renewal payment for failed renewal orders.
*
* @param WC_Order $order
* @since 2.1
*/
public static function process_retry_renewal_payment_action_request( $order ) {
if ( self::can_renewal_order_be_retried( $order ) ) {
// init payment gateways
WC()->payment_gateways();
$order->add_order_note( __( 'Retry renewal payment action requested by admin.', 'woocommerce-subscriptions' ), false, true );
do_action( 'woocommerce_scheduled_subscription_payment_' . wcs_get_objects_property( $order, 'payment_method' ), $order->get_total(), $order );
}
}
/**
* Determines if a renewal order payment can be retried. A renewal order payment can only be retried when:
* - Order is a renewal order
* - Order status is failed
* - Order payment method isn't empty
* - Order total > 0
* - Subscription/s aren't manual
* - Subscription payment method supports date changes
* - Order payment method has_action('woocommerce_scheduled_subscription_payment_..')
*
* @param WC_Order $order
* @return bool
* @since 2.1
*/
private static function can_renewal_order_be_retried( $order ) {
$can_be_retried = false;
if ( wcs_order_contains_renewal( $order ) && $order->needs_payment() && '' != wcs_get_objects_property( $order, 'payment_method' ) ) {
$supports_date_changes = false;
$order_payment_gateway = wc_get_payment_gateway_by_order( $order );
$order_payment_gateway_supports = ( isset( $order_payment_gateway->id ) ) ? has_action( 'woocommerce_scheduled_subscription_payment_' . $order_payment_gateway->id ) : false;
foreach ( wcs_get_subscriptions_for_renewal_order( $order ) as $subscription ) {
$supports_date_changes = $subscription->payment_method_supports( 'subscription_date_changes' );
$is_automatic = ! $subscription->is_manual();
break;
}
$can_be_retried = $order_payment_gateway_supports && $supports_date_changes && $is_automatic;
}
return $can_be_retried;
}
/**
* Disables stock managment while adding items to a subscription via the edit subscription screen.
*
* @since 3.0.6
*
* @param string $manage_stock The default manage stock setting.
* @return string Whether the stock should be managed.
*/
public static function override_stock_management( $manage_stock ) {
// Override stock management while adding line items to a subscription via AJAX.
if ( isset( $_POST['order_id'] ) && wp_verify_nonce( $_REQUEST['security'], 'order-item' ) && doing_action( 'wp_ajax_woocommerce_add_order_item' ) && wcs_is_subscription( absint( wp_unslash( $_POST['order_id'] ) ) ) ) {
$manage_stock = 'no';
}
return $manage_stock;
}
}

View File

@@ -96,17 +96,15 @@ class WCS_Admin_Reports {
* @since 1.5 * @since 1.5
*/ */
public static function reports_scripts() { public static function reports_scripts() {
global $wp_query, $post;
$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
$screen = get_current_screen(); $screen = get_current_screen();
$wc_screen_id = sanitize_title( __( 'WooCommerce', 'woocommerce-subscriptions' ) ); $wc_screen_id = sanitize_title( __( 'WooCommerce', 'woocommerce-subscriptions' ) );
$version = WC_Subscriptions_Plugin::instance()->get_plugin_version();
// Reports Subscriptions Pages // Reports Subscriptions Pages
if ( in_array( $screen->id, apply_filters( 'woocommerce_reports_screen_ids', array( $wc_screen_id . '_page_wc-reports', 'toplevel_page_wc-reports', 'dashboard' ) ) ) && isset( $_GET['tab'] ) && 'subscriptions' == $_GET['tab'] ) { if ( in_array( $screen->id, apply_filters( 'woocommerce_reports_screen_ids', array( $wc_screen_id . '_page_wc-reports', 'toplevel_page_wc-reports', 'dashboard' ) ) ) && isset( $_GET['tab'] ) && 'subscriptions' == $_GET['tab'] ) {
wp_enqueue_script( 'wcs-reports', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/admin/reports.js', array( 'jquery', 'jquery-ui-datepicker', 'wc-reports', 'accounting' ), WC_Subscriptions::$version ); wp_enqueue_script( 'wcs-reports', WC_Subscriptions_Plugin::instance()->get_plugin_directory_url( 'assets/js/admin/reports.js' ), array( 'jquery', 'jquery-ui-datepicker', 'wc-reports', 'accounting' ), $version );
// Add currency localisation params for axis label // Add currency localisation params for axis label
wp_localize_script( 'wcs-reports', 'wcs_reports', array( wp_localize_script( 'wcs-reports', 'wcs_reports', array(
@@ -117,12 +115,12 @@ class WCS_Admin_Reports {
'currency_format' => esc_js( str_replace( array( '%1$s', '%2$s' ), array( '%s', '%v' ), get_woocommerce_price_format() ) ), // For accounting JS 'currency_format' => esc_js( str_replace( array( '%1$s', '%2$s' ), array( '%s', '%v' ), get_woocommerce_price_format() ) ), // For accounting JS
) ); ) );
wp_enqueue_script( 'flot-order', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/admin/jquery.flot.orderBars' . $suffix . '.js', array( 'jquery', 'flot' ), WC_Subscriptions::$version ); wp_enqueue_script( 'flot-order', WC_Subscriptions_Plugin::instance()->get_plugin_directory_url( 'assets/js/admin/jquery.flot.orderBars' ) . $suffix . '.js', array( 'jquery', 'flot' ), $version );
wp_enqueue_script( 'flot-axis-labels', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/admin/jquery.flot.axislabels' . $suffix . '.js', array( 'jquery', 'flot' ), WC_Subscriptions::$version ); wp_enqueue_script( 'flot-axis-labels', WC_Subscriptions_Plugin::instance()->get_plugin_directory_url( 'assets/js/admin/jquery.flot.axislabels' ) . $suffix . '.js', array( 'jquery', 'flot' ), $version );
// Add tracks script if tracking is enabled. // Add tracks script if tracking is enabled.
if ( 'yes' === get_option( 'woocommerce_allow_tracking', 'no' ) ) { if ( 'yes' === get_option( 'woocommerce_allow_tracking', 'no' ) ) {
wp_enqueue_script( 'wcs-tracks', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/admin/tracks.js', array( 'jquery' ), WC_Subscriptions::$version, true ); wp_enqueue_script( 'wcs-tracks', WC_Subscriptions_Plugin::instance()->get_plugin_directory_url( 'assets/js/admin/tracks.js' ), array( 'jquery' ), $version, true );
} }
} }
} }
@@ -174,7 +172,7 @@ class WCS_Admin_Reports {
$properties = array( $properties = array(
'orders_count' => array_sum( (array) wp_count_posts( 'shop_order' ) ), 'orders_count' => array_sum( (array) wp_count_posts( 'shop_order' ) ),
'subscriptions_count' => array_sum( (array) wp_count_posts( 'shop_subscription' ) ), 'subscriptions_count' => array_sum( (array) wp_count_posts( 'shop_subscription' ) ),
'subscriptions_version' => WC_Subscriptions::$version, 'subscriptions_version' => WC_Subscriptions_Plugin::instance()->get_plugin_version(),
); );
if ( in_array( $name, array( 'subscription-events-by-date', 'upcoming-recurring-revenue', 'subscription-payment-retry' ), true ) ) { if ( in_array( $name, array( 'subscription-events-by-date', 'upcoming-recurring-revenue', 'subscription-payment-retry' ), true ) ) {

View File

@@ -80,7 +80,7 @@ class WCS_Report_Cache_Manager {
public function __construct() { public function __construct() {
// Use the old hooks // Use the old hooks
if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) { if ( wcs_is_woocommerce_pre( '3.0' ) ) {
$hooks = array( $hooks = array(
'woocommerce_order_add_product' => 'woocommerce_new_order_item', 'woocommerce_order_add_product' => 'woocommerce_new_order_item',
@@ -218,12 +218,11 @@ class WCS_Report_Cache_Manager {
// Some report classes extend WP_List_Table which has a constructor using methods not available on WP-Cron (and unable to be loaded with a __doing_it_wrong() notice), so they have a static get_data() method and do not need to be instantiated // Some report classes extend WP_List_Table which has a constructor using methods not available on WP-Cron (and unable to be loaded with a __doing_it_wrong() notice), so they have a static get_data() method and do not need to be instantiated
if ( $reflector->isStatic() ) { if ( $reflector->isStatic() ) {
call_user_func( array( $report_class, 'clear_cache' ) );
call_user_func( array( $report_class, 'get_data' ), array( 'no_cache' => true ) ); call_user_func( array( $report_class, 'get_data' ), array( 'no_cache' => true ) );
} else { } else {
$report = new $report_class(); $report = new $report_class();
$report->clear_cache();
// Classes with a non-static get_data() method can be displayed for different time series, so we need to update the cache for each of those ranges // Classes with a non-static get_data() method can be displayed for different time series, so we need to update the cache for each of those ranges
foreach ( array( 'year', 'last_month', 'month', '7day' ) as $range ) { foreach ( array( 'year', 'last_month', 'month', '7day' ) as $range ) {

View File

@@ -41,8 +41,8 @@ class WCS_Report_Dashboard {
$args = apply_filters( 'wcs_reports_subscription_dashboard_args', $args ); $args = apply_filters( 'wcs_reports_subscription_dashboard_args', $args );
$args = wp_parse_args( $args, $default_args ); $args = wp_parse_args( $args, $default_args );
$offset = get_option( 'gmt_offset' ); $offset = get_option( 'gmt_offset' );
$update_cache = false;
// Use this once it is merged - wcs_get_gmt_offset_string(); // Use this once it is merged - wcs_get_gmt_offset_string();
// Convert from Decimal format(eg. 11.5) to a suitable format(eg. +11:30) for CONVERT_TZ() of SQL query. // Convert from Decimal format(eg. 11.5) to a suitable format(eg. +11:30) for CONVERT_TZ() of SQL query.
@@ -72,7 +72,7 @@ class WCS_Report_Dashboard {
if ( $args['no_cache'] || false === $cached_results || ! isset( $cached_results[ $query_hash ] ) ) { if ( $args['no_cache'] || false === $cached_results || ! isset( $cached_results[ $query_hash ] ) ) {
$wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' ); $wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' );
$cached_results[ $query_hash ] = $wpdb->get_var( apply_filters( 'woocommerce_subscription_dashboard_status_widget_signup_query', $query ) ); $cached_results[ $query_hash ] = $wpdb->get_var( apply_filters( 'woocommerce_subscription_dashboard_status_widget_signup_query', $query ) );
set_transient( strtolower( __CLASS__ ), $cached_results, WEEK_IN_SECONDS ); $update_cache = true;
} }
$report_data->signup_count = $cached_results[ $query_hash ]; $report_data->signup_count = $cached_results[ $query_hash ];
@@ -103,7 +103,7 @@ class WCS_Report_Dashboard {
if ( $args['no_cache'] || false === $cached_results || ! isset( $cached_results[ $query_hash ] ) ) { if ( $args['no_cache'] || false === $cached_results || ! isset( $cached_results[ $query_hash ] ) ) {
$wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' ); $wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' );
$cached_results[ $query_hash ] = $wpdb->get_var( apply_filters( 'woocommerce_subscription_dashboard_status_widget_signup_revenue_query', $query ) ); $cached_results[ $query_hash ] = $wpdb->get_var( apply_filters( 'woocommerce_subscription_dashboard_status_widget_signup_revenue_query', $query ) );
set_transient( strtolower( __CLASS__ ), $cached_results, HOUR_IN_SECONDS ); $update_cache = true;
} }
$report_data->signup_revenue = $cached_results[ $query_hash ]; $report_data->signup_revenue = $cached_results[ $query_hash ];
@@ -131,7 +131,7 @@ class WCS_Report_Dashboard {
if ( $args['no_cache'] || false === $cached_results || ! isset( $cached_results[ $query_hash ] ) ) { if ( $args['no_cache'] || false === $cached_results || ! isset( $cached_results[ $query_hash ] ) ) {
$wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' ); $wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' );
$cached_results[ $query_hash ] = $wpdb->get_var( apply_filters( 'woocommerce_subscription_dashboard_status_widget_renewal_query', $query ) ); $cached_results[ $query_hash ] = $wpdb->get_var( apply_filters( 'woocommerce_subscription_dashboard_status_widget_renewal_query', $query ) );
set_transient( strtolower( __CLASS__ ), $cached_results, HOUR_IN_SECONDS ); $update_cache = true;
} }
$report_data->renewal_count = $cached_results[ $query_hash ]; $report_data->renewal_count = $cached_results[ $query_hash ];
@@ -165,7 +165,7 @@ class WCS_Report_Dashboard {
if ( $args['no_cache'] || false === $cached_results || ! isset( $cached_results[ $query_hash ] ) ) { if ( $args['no_cache'] || false === $cached_results || ! isset( $cached_results[ $query_hash ] ) ) {
$wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' ); $wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' );
$cached_results[ $query_hash ] = $wpdb->get_var( apply_filters( 'woocommerce_subscription_dashboard_status_widget_renewal_revenue_query', $query ) ); $cached_results[ $query_hash ] = $wpdb->get_var( apply_filters( 'woocommerce_subscription_dashboard_status_widget_renewal_revenue_query', $query ) );
set_transient( strtolower( __CLASS__ ), $cached_results, HOUR_IN_SECONDS ); $update_cache = true;
} }
$report_data->renewal_revenue = $cached_results[ $query_hash ]; $report_data->renewal_revenue = $cached_results[ $query_hash ];
@@ -188,11 +188,15 @@ class WCS_Report_Dashboard {
if ( $args['no_cache'] || false === $cached_results || ! isset( $cached_results[ $query_hash ] ) ) { if ( $args['no_cache'] || false === $cached_results || ! isset( $cached_results[ $query_hash ] ) ) {
$wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' ); $wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' );
$cached_results[ $query_hash ] = $wpdb->get_var( apply_filters( 'woocommerce_subscription_dashboard_status_widget_cancellation_query', $query ) ); $cached_results[ $query_hash ] = $wpdb->get_var( apply_filters( 'woocommerce_subscription_dashboard_status_widget_cancellation_query', $query ) );
set_transient( strtolower( __CLASS__ ), $cached_results, HOUR_IN_SECONDS ); $update_cache = true;
} }
$report_data->cancel_count = $cached_results[ $query_hash ]; $report_data->cancel_count = $cached_results[ $query_hash ];
if ( $update_cache ) {
set_transient( strtolower( __CLASS__ ), $cached_results, HOUR_IN_SECONDS );
}
return $report_data; return $report_data;
} }
@@ -254,6 +258,15 @@ class WCS_Report_Dashboard {
* @since 2.1 * @since 2.1
*/ */
public static function dashboard_scripts() { public static function dashboard_scripts() {
wp_enqueue_style( 'wcs-dashboard-report', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/css/dashboard.css', array(), WC_Subscriptions::$version ); wp_enqueue_style( 'wcs-dashboard-report', WC_Subscriptions_Plugin::instance()->get_plugin_directory_url( 'assets/css/dashboard.css' ), array(), WC_Subscriptions_Plugin::instance()->get_plugin_version() );
}
/**
* Clears the cached report data.
*
* @since 3.0.10
*/
public static function clear_cache() {
delete_transient( strtolower( __CLASS__ ) );
} }
} }

View File

@@ -129,7 +129,7 @@ class WCS_Report_Retention_Rate extends WC_Admin_Report {
* @return null * @return null
*/ */
public function output_report() { public function output_report() {
include( plugin_dir_path( WC_Subscriptions::$plugin_file ) . '/includes/admin/views/html-report-by-period.php' ); include( WC_Subscriptions_Plugin::instance()->get_plugin_directory( 'includes/admin/views/html-report-by-period.php' ) );
} }
/** /**
@@ -172,7 +172,7 @@ class WCS_Report_Retention_Rate extends WC_Admin_Report {
var main_chart; var main_chart;
jQuery(function(){ jQuery(function(){
var subscription_lifespans = jQuery.parseJSON( '<?php echo json_encode( $data_to_plot ); ?>' ), var subscription_lifespans = JSON.parse( '<?php echo json_encode( $data_to_plot ); ?>' ),
unended_subscriptions = <?php echo esc_js( $this->report_data->unended_subscriptions ); ?>; unended_subscriptions = <?php echo esc_js( $this->report_data->unended_subscriptions ); ?>;
var drawGraph = function( highlight ) { var drawGraph = function( highlight ) {
@@ -232,7 +232,7 @@ class WCS_Report_Retention_Rate extends WC_Admin_Report {
} }
); );
jQuery('.chart-placeholder').resize(); jQuery('.chart-placeholder').trigger( 'resize' );
} }
drawGraph(); drawGraph();

View File

@@ -280,4 +280,13 @@ class WCS_Report_Subscription_By_Customer extends WP_List_Table {
return $customer_totals; return $customer_totals;
} }
/**
* Clears the cached report data.
*
* @since 3.0.10
*/
public static function clear_cache() {
delete_transient( strtolower( __CLASS__ ) );
}
} }

View File

@@ -304,7 +304,7 @@ class WCS_Report_Subscription_By_Product extends WP_List_Table {
} }
} }
); );
jQuery('.chart-placeholder.variation_breakdown_chart').resize(); jQuery('.chart-placeholder.variation_breakdown_chart').trigger( 'resize' );
jQuery.plot( jQuery.plot(
jQuery('.chart-placeholder.product_breakdown_chart'), jQuery('.chart-placeholder.product_breakdown_chart'),
[ [
@@ -346,9 +346,18 @@ class WCS_Report_Subscription_By_Product extends WP_List_Table {
} }
} }
); );
jQuery('.chart-placeholder.product_breakdown_chart').resize(); jQuery('.chart-placeholder.product_breakdown_chart').trigger( 'resize' );
}); });
</script> </script>
<?php <?php
} }
/**
* Clears the cached report data.
*
* @since 3.0.10
*/
public static function clear_cache() {
delete_transient( strtolower( __CLASS__ ) );
}
} }

View File

@@ -103,7 +103,7 @@ class WCS_Report_Subscription_Events_By_Date extends WC_Admin_Report {
), ),
), ),
'group_by' => $this->group_by_query, 'group_by' => $this->group_by_query,
'order_status' => '', 'order_status' => array(),
'order_by' => 'post_date ASC', 'order_by' => 'post_date ASC',
'query_type' => 'get_results', 'query_type' => 'get_results',
'filter_range' => true, 'filter_range' => true,
@@ -467,7 +467,7 @@ class WCS_Report_Subscription_Events_By_Date extends WC_Admin_Report {
set_transient( strtolower( get_class( $this ) ), $cached_results, WEEK_IN_SECONDS ); set_transient( strtolower( get_class( $this ) ), $cached_results, WEEK_IN_SECONDS );
// Remove this class from the list of classes WC updates on shutdown. Introduced in WC 3.7 // Remove this class from the list of classes WC updates on shutdown. Introduced in WC 3.7
if ( ! WC_Subscriptions::is_woocommerce_pre( '3.7' ) ) { if ( ! wcs_is_woocommerce_pre( '3.7' ) ) {
unset( WC_Admin_Report::$transients_to_update[ strtolower( get_class( $this ) ) ] ); unset( WC_Admin_Report::$transients_to_update[ strtolower( get_class( $this ) ) ] );
} }
} }
@@ -832,7 +832,7 @@ class WCS_Report_Subscription_Events_By_Date extends WC_Admin_Report {
var main_chart; var main_chart;
jQuery(function(){ jQuery(function(){
var order_data = jQuery.parseJSON( '<?php echo json_encode( $chart_data ); ?>' ); var order_data = JSON.parse( '<?php echo json_encode( $chart_data ); ?>' );
var drawGraph = function( highlight ) { var drawGraph = function( highlight ) {
var series = [ var series = [
{ {
@@ -1107,12 +1107,12 @@ class WCS_Report_Subscription_Events_By_Date extends WC_Admin_Report {
} }
); );
jQuery('.chart-placeholder').resize(); jQuery('.chart-placeholder').trigger( 'resize' );
} }
drawGraph(); drawGraph();
jQuery('.highlight_series').hover( jQuery('.highlight_series').on( 'hover',
function() { function() {
drawGraph( jQuery(this).data('series') ); drawGraph( jQuery(this).data('series') );
}, },
@@ -1205,4 +1205,13 @@ class WCS_Report_Subscription_Events_By_Date extends WC_Admin_Report {
return $prepared_data; return $prepared_data;
} }
/**
* Clears the cached report data.
*
* @since 3.0.10
*/
public function clear_cache() {
delete_transient( strtolower( get_class( $this ) ) );
}
} }

View File

@@ -239,7 +239,7 @@ class WCS_Report_Subscription_Payment_Retry extends WC_Admin_Report {
var main_chart; var main_chart;
jQuery(function(){ jQuery(function(){
var chart_data = jQuery.parseJSON( '<?php echo json_encode( $chart_data ); ?>' ); var chart_data = JSON.parse( '<?php echo json_encode( $chart_data ); ?>' );
var drawGraph = function( highlight ) { var drawGraph = function( highlight ) {
var series = [ var series = [
@@ -378,12 +378,12 @@ class WCS_Report_Subscription_Payment_Retry extends WC_Admin_Report {
} }
); );
jQuery('.chart-placeholder').resize(); jQuery('.chart-placeholder').trigger( 'resize' );
} }
drawGraph(); drawGraph();
jQuery('.highlight_series').hover( jQuery('.highlight_series').on( 'hover',
function() { function() {
drawGraph( jQuery(this).data('series') ); drawGraph( jQuery(this).data('series') );
}, },

View File

@@ -240,7 +240,7 @@ class WCS_Report_Upcoming_Recurring_Revenue extends WC_Admin_Report {
var main_chart; var main_chart;
jQuery(function(){ jQuery(function(){
var order_data = jQuery.parseJSON( '<?php echo json_encode( $chart_data ); ?>' ); var order_data = JSON.parse( '<?php echo json_encode( $chart_data ); ?>' );
var drawGraph = function( highlight ) { var drawGraph = function( highlight ) {
var series = [ var series = [
{ {
@@ -331,12 +331,12 @@ class WCS_Report_Upcoming_Recurring_Revenue extends WC_Admin_Report {
} }
); );
jQuery('.chart-placeholder').resize(); jQuery('.chart-placeholder').trigger( 'resize' );
} }
drawGraph(); drawGraph();
jQuery('.highlight_series').hover( jQuery('.highlight_series').on( 'hover',
function() { function() {
drawGraph( jQuery(this).data('series') ); drawGraph( jQuery(this).data('series') );
}, },
@@ -430,4 +430,13 @@ class WCS_Report_Upcoming_Recurring_Revenue extends WC_Admin_Report {
return $current_range; return $current_range;
} }
/**
* Clears the cached query results.
*
* @since 3.0.10
*/
public function clear_cache() {
delete_transient( strtolower( get_class( $this ) ) );
}
} }

View File

@@ -1,23 +1,16 @@
<?php <?php
/** /**
* REST API subscription notes controller * REST API Subscription notes controller.
* *
* Handles requests to the /subscription/<id>/notes endpoint. * Handles requests to the /subscriptions/<id>/notes endpoint.
* *
* @author Prospress * @package WooCommerce Subscriptions\Rest Api
* @since 2.1 * @since 3.1.0
*/ */
if ( ! defined( 'ABSPATH' ) ) { defined( 'ABSPATH' ) || exit;
exit;
} class WC_REST_Subscription_notes_Controller extends WC_REST_Order_Notes_Controller {
/**
* REST API Subscription Notes controller class.
*
* @package WooCommerce_Subscriptions/API
* @extends WC_REST_Order_Notes_Controller
*/
class WC_REST_Subscription_Notes_Controller extends WC_REST_Order_Notes_V1_Controller {
/** /**
* Route base. * Route base.
@@ -33,4 +26,18 @@ class WC_REST_Subscription_Notes_Controller extends WC_REST_Order_Notes_V1_Contr
*/ */
protected $post_type = 'shop_subscription'; protected $post_type = 'shop_subscription';
/**
* Prepare links for the request.
*
* @since 3.1.0
*
* @param WP_Comment $note
* @return array Links for the given order note.
*/
protected function prepare_links( $note ) {
$links = parent::prepare_links( $note );
$links['up'] = array( 'href' => rest_url( sprintf( '/%s/subscriptions/%d', $this->namespace, (int) $note->comment_post_ID ) ) );
return $links;
}
} }

View File

@@ -0,0 +1,148 @@
<?php
/**
* REST API System Status Endpoint Manager.
*
* Adds additional subscription-related data to the /wc/<version>/system_status endpoint.
*
* @package WooCommerce Subscriptions\Rest Api
* @since 3.1.0
*/
defined( 'ABSPATH' ) || exit;
class WC_REST_Subscription_System_Status_Manager {
/**
* Attach callbacks.
*/
public static function init() {
add_filter( 'woocommerce_rest_prepare_system_status', array( __CLASS__, 'add_subscription_fields_to_reponse' ) );
add_filter( 'woocommerce_rest_system_status_schema', array( __CLASS__, 'add_additional_fields_to_schema' ) );
}
/**
* Adds subscription fields to System Status response.
*
* @since 3.1.0
*
* @param WP_REST_Response $response The base system status response.
* @return WP_REST_Response
*/
public static function add_subscription_fields_to_reponse( $response ) {
$response->data['subscriptions'] = array(
'wcs_debug' => defined( 'WCS_DEBUG' ) ? WCS_DEBUG : false,
'mode' => ( WCS_Staging::is_duplicate_site() ) ? __( 'staging', 'woocommerce-subscriptions' ) : __( 'live', 'woocommerce-subscriptions' ),
'live_url' => esc_url( WCS_Staging::get_site_url_from_source( 'subscriptions_install' ) ),
'statuses' => array_filter( (array) wp_count_posts( 'shop_subscription' ) ),
'report_cache_enabled' => ( 'yes' === get_option( 'woocommerce_subscriptions_cache_updates_enabled', 'yes' ) ),
'cache_update_failures' => absint( get_option( 'woocommerce_subscriptions_cache_updates_failures', 0 ) ),
'subscriptions_by_payment_gateway' => WCS_Admin_System_Status::get_subscriptions_by_gateway(),
'payment_gateway_feature_support' => self::get_payment_gateway_feature_support(),
);
return $response;
}
/**
* Gets the store's payment gateways and the features they support.
*
* @since 3.1.0
* @return array Payment gateway and their features.
*/
private static function get_payment_gateway_feature_support() {
$gateway_features = array();
foreach ( WC()->payment_gateways->get_available_payment_gateways() as $gateway_id => $gateway ) {
// Some gateways include array keys. For consistancy, only send the values.
$gateway_features[ $gateway_id ] = array_values( (array) apply_filters( 'woocommerce_subscriptions_payment_gateway_features_list', $gateway->supports, $gateway ) );
if ( 'paypal' === $gateway_id && WCS_PayPal::are_reference_transactions_enabled() ) {
$gateway_features[ $gateway_id ][] = 'paypal_reference_transactions';
}
}
return $gateway_features;
}
/**
* Adds subscription system status fields the system status schema.
*
* @since 3.1.0
* @param array $schema
*
* @return array the system status schema.
*/
public static function add_additional_fields_to_schema( $schema ) {
$schema['properties']['subscriptions'] = array(
array(
'description' => __( 'Subscriptions.', 'woocommerce-subscriptions' ),
'type' => 'object',
'context' => array( 'view' ),
'readonly' => true,
'properties' => array(
'wcs_debug_enabled' => array(
'description' => __( 'WCS debug constant.', 'woocommerce-subscriptions' ),
'type' => 'boolean',
'context' => array( 'view' ),
'readonly' => true,
),
'mode' => array(
'description' => __( 'Subscriptions Mode', 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view' ),
'readonly' => true,
),
'live_url' => array(
'description' => __( 'Subscriptions Live Site URL', 'woocommerce-subscriptions' ),
'type' => 'string',
'format' => 'uri',
'context' => array( 'view' ),
'readonly' => true,
),
'statuses' => array(
'description' => __( 'Subscriptions broken down by status.', 'woocommerce-subscriptions' ),
'type' => 'array',
'context' => array( 'view' ),
'readonly' => true,
'items' => array(
'type' => 'string',
),
),
'report_cache_enabled' => array(
'description' => __( 'Whether the Report Cache is enabled.', 'woocommerce-subscriptions' ),
'type' => 'boolean',
'context' => array( 'view' ),
'readonly' => true,
),
'cache_update_failures' => array(
'description' => __( 'Number of report cache failures.', 'woocommerce-subscriptions' ),
'type' => 'integer',
'context' => array( 'view' ),
'readonly' => true,
),
'subscriptions_by_payment_gateway' => array(
'description' => __( 'Subscriptions by Payment Gateway.', 'woocommerce-subscriptions' ),
'type' => 'array',
'context' => array( 'view' ),
'readonly' => true,
'items' => array(
'type' => 'string',
),
),
'payment_gateway_feature_support' => array(
'description' => __( 'Payment Gateway Feature Support.', 'woocommerce-subscriptions' ),
'type' => 'array',
'context' => array( 'view' ),
'readonly' => true,
'items' => array(
'type' => 'string',
),
),
),
),
);
return $schema;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -302,14 +302,13 @@ class WC_API_Subscriptions extends WC_API_Orders {
* @since 2.0 * @since 2.0
*/ */
public function update_payment_method( $subscription, $payment_details, $updating ) { public function update_payment_method( $subscription, $payment_details, $updating ) {
global $wpdb;
$payment_gateways = WC()->payment_gateways->get_available_payment_gateways(); $payment_gateways = WC()->payment_gateways->get_available_payment_gateways();
$payment_method = ( ! empty( $payment_details['method_id'] ) ) ? $payment_details['method_id'] : 'manual'; $payment_method = ( ! empty( $payment_details['method_id'] ) ) ? $payment_details['method_id'] : 'manual';
$payment_gateway = ( isset( $payment_gateways[ $payment_details['method_id'] ] ) ) ? $payment_gateways[ $payment_details['method_id'] ] : ''; $payment_gateway = ( isset( $payment_gateways[ $payment_details['method_id'] ] ) ) ? $payment_gateways[ $payment_details['method_id'] ] : '';
try { try {
$wpdb->query( 'START TRANSACTION' ); $transaction = new WCS_SQL_Transaction();
$transaction->start();
if ( $updating && ! array_key_exists( $payment_method, WCS_Change_Payment_Method_Admin::get_valid_payment_methods( $subscription ) ) ) { if ( $updating && ! array_key_exists( $payment_method, WCS_Change_Payment_Method_Admin::get_valid_payment_methods( $subscription ) ) ) {
throw new Exception( 'wcs_api_edit_subscription_error', __( 'Gateway does not support admin changing the payment method on a Subscription.', 'woocommerce-subscriptions' ) ); throw new Exception( 'wcs_api_edit_subscription_error', __( 'Gateway does not support admin changing the payment method on a Subscription.', 'woocommerce-subscriptions' ) );
@@ -344,10 +343,10 @@ class WC_API_Subscriptions extends WC_API_Orders {
$subscription->set_payment_method( $payment_gateway, $payment_method_meta ); $subscription->set_payment_method( $payment_gateway, $payment_method_meta );
$wpdb->query( 'COMMIT' ); $transaction->commit();
} catch ( Exception $e ) { } catch ( Exception $e ) {
$wpdb->query( 'ROLLBACK' ); $transaction->rollback();
// translators: 1$: gateway id, 2$: error message // translators: 1$: gateway id, 2$: error message
throw new Exception( sprintf( __( 'Subscription payment method could not be set to %1$s and has been set to manual with error message: %2$s', 'woocommerce-subscriptions' ), ( ! empty( $payment_gateway->id ) ) ? $payment_gateway->id : 'manual', $e->getMessage() ) ); throw new Exception( sprintf( __( 'Subscription payment method could not be set to %1$s and has been set to manual with error message: %2$s', 'woocommerce-subscriptions' ), ( ! empty( $payment_gateway->id ) ) ? $payment_gateway->id : 'manual', $e->getMessage() ) );

View File

@@ -166,7 +166,7 @@ class WC_REST_Subscriptions_Controller extends WC_REST_Orders_Controller {
* @return WP_Error|WP_REST_Response $response * @return WP_Error|WP_REST_Response $response
*/ */
public function get_subscription_orders( $request ) { public function get_subscription_orders( $request ) {
$id = (int) $request['id']; $id = absint( $request['id'] );
if ( empty( $id ) || ! wcs_is_subscription( $id ) ) { if ( empty( $id ) || ! wcs_is_subscription( $id ) ) {
return new WP_Error( 'woocommerce_rest_invalid_shop_subscription_id', __( 'Invalid subscription id.', 'woocommerce-subscriptions' ), array( 'status' => 404 ) ); return new WP_Error( 'woocommerce_rest_invalid_shop_subscription_id', __( 'Invalid subscription id.', 'woocommerce-subscriptions' ), array( 'status' => 404 ) );

View File

@@ -0,0 +1,36 @@
<?php
/**
* REST API subscription notes controller
*
* Handles requests to the /subscription/<id>/notes endpoint.
*
* @author Prospress
* @since 2.1
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* REST API Subscription Notes controller class.
*
* @package WooCommerce_Subscriptions/API
* @extends WC_REST_Order_Notes_Controller
*/
class WC_REST_Subscription_Notes_V1_Controller extends WC_REST_Order_Notes_V1_Controller {
/**
* Route base.
*
* @var string
*/
protected $rest_base = 'subscriptions/(?P<order_id>[\d]+)/notes';
/**
* Post type.
*
* @var string
*/
protected $post_type = 'shop_subscription';
}

View File

@@ -0,0 +1,786 @@
<?php
/**
* REST API Subscriptions controller
*
* Handles requests to the /subscriptions endpoint.
*
* @package WooCommerce Subscriptions\Rest Api
* @author WooCommerce
* @since 2.1.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* REST API Subscriptions controller class.
*
* @package WooCommerce_Subscriptions/API
* @extends WC_REST_Orders_Controller
*/
class WC_REST_Subscriptions_V1_Controller extends WC_REST_Orders_V1_Controller {
/**
* Route base.
*
* @var string
*/
protected $rest_base = 'subscriptions';
/**
* Post type.
*
* @var string
*/
protected $post_type = 'shop_subscription';
/**
* Initialize subscription actions and filters
*/
public function __construct() {
add_filter( 'woocommerce_rest_prepare_shop_subscription', array( $this, 'filter_get_subscription_response' ), 10, 3 );
add_filter( 'woocommerce_rest_shop_subscription_query', array( $this, 'query_args' ), 10, 2 );
}
/**
* Register the routes for subscriptions.
*/
public function register_routes() {
parent::register_routes();
register_rest_route( $this->namespace, '/' . $this->rest_base . '/(?P<id>[\d]+)/orders', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_subscription_orders' ),
'permission_callback' => array( $this, 'get_items_permissions_check' ),
'args' => $this->get_collection_params(),
),
'schema' => array( $this, 'get_public_item_schema' ),
) );
register_rest_route( $this->namespace, '/' . $this->rest_base . '/statuses', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_statuses' ),
'permission_callback' => '__return_true',
),
'schema' => array( $this, 'get_public_item_schema' ),
) );
}
/**
* Filter WC_REST_Orders_Controller::get_item response for subscription post types
*
* @since 2.1
* @param WP_REST_Response $response
* @param WP_POST $post
* @param WP_REST_Request $request
*/
public function filter_get_subscription_response( $response, $post, $request ) {
$decimal_places = is_null( $request['dp'] ) ? wc_get_price_decimals() : absint( $request['dp'] );
if ( ! empty( $post->post_type ) && ! empty( $post->ID ) && 'shop_subscription' == $post->post_type ) {
$subscription = wcs_get_subscription( $post->ID );
$response->data['billing_period'] = $subscription->get_billing_period();
$response->data['billing_interval'] = $subscription->get_billing_interval();
// Send resubscribe data
$resubscribed_subscriptions = array_filter( $subscription->get_related_orders( 'ids', 'resubscribe' ), 'wcs_is_subscription' );
$response->data['resubscribed_from'] = strval( wcs_get_objects_property( $subscription, 'subscription_resubscribe' ) );
$response->data['resubscribed_subscription'] = strval( reset( $resubscribed_subscriptions ) ); // Subscriptions can only be resubscribed to once so return the first and only element.
foreach ( array( 'start', 'trial_end', 'next_payment', 'end' ) as $date_type ) {
$date = $subscription->get_date( $date_type );
$response->data[ $date_type . '_date' ] = ( ! empty( $date ) ) ? wc_rest_prepare_date_response( $date ) : '';
}
// v1 API includes some date types in site time, include those dates in UTC as well.
$response->data['date_completed_gmt'] = wc_rest_prepare_date_response( $subscription->get_date_completed() );
$response->data['date_paid_gmt'] = wc_rest_prepare_date_response( $subscription->get_date_paid() );
$response->data['removed_line_items'] = array();
// Include removed line items of a subscription
foreach ( $subscription->get_items( 'line_item_removed' ) as $item_id => $item ) {
$product = $item->get_product();
$product_id = 0;
$variation_id = 0;
$product_sku = null;
// Check if the product exists.
if ( is_object( $product ) ) {
$product_id = $item->get_product_id();
$variation_id = $item->get_variation_id();
$product_sku = $product->get_sku();
}
$item_meta = array();
$hideprefix = 'true' === $request['all_item_meta'] ? null : '_';
foreach ( $item->get_formatted_meta_data( $hideprefix, true ) as $meta_key => $formatted_meta ) {
$item_meta[] = array(
'key' => $formatted_meta->key,
'label' => $formatted_meta->display_key,
'value' => wc_clean( $formatted_meta->display_value ),
);
}
$line_item = array(
'id' => $item_id,
'name' => $item['name'],
'sku' => $product_sku,
'product_id' => (int) $product_id,
'variation_id' => (int) $variation_id,
'quantity' => wc_stock_amount( $item['qty'] ),
'tax_class' => ! empty( $item['tax_class'] ) ? $item['tax_class'] : '',
'price' => wc_format_decimal( $subscription->get_item_total( $item, false, false ), $decimal_places ),
'subtotal' => wc_format_decimal( $subscription->get_line_subtotal( $item, false, false ), $decimal_places ),
'subtotal_tax' => wc_format_decimal( $item['line_subtotal_tax'], $decimal_places ),
'total' => wc_format_decimal( $subscription->get_line_total( $item, false, false ), $decimal_places ),
'total_tax' => wc_format_decimal( $item['line_tax'], $decimal_places ),
'taxes' => array(),
'meta' => $item_meta,
);
$item_line_taxes = maybe_unserialize( $item['line_tax_data'] );
if ( isset( $item_line_taxes['total'] ) ) {
$line_tax = array();
foreach ( $item_line_taxes['total'] as $tax_rate_id => $tax ) {
$line_tax[ $tax_rate_id ] = array(
'id' => $tax_rate_id,
'total' => $tax,
'subtotal' => '',
);
}
foreach ( $item_line_taxes['subtotal'] as $tax_rate_id => $tax ) {
$line_tax[ $tax_rate_id ]['subtotal'] = $tax;
}
$line_item['taxes'] = array_values( $line_tax );
}
$response->data['removed_line_items'][] = $line_item;
}
}
return $response;
}
/**
* Sets the order_total value on the subscription after WC_REST_Orders_Controller::create_order
* calls calculate_totals(). This allows store admins to create a recurring payment via the api
* without needing to attach a product to the subscription.
*
* @since 2.1
* @param WP_REST_Request $request
*/
protected function create_order( $request ) {
try {
if ( ! is_null( $request['customer_id'] ) && 0 !== $request['customer_id'] && false === get_user_by( 'id', $request['customer_id'] ) ) {
throw new WC_REST_Exception( 'woocommerce_rest_invalid_customer_id', __( 'Customer ID is invalid.', 'woocommerce-subscriptions' ), 400 );
}
// If the start date is not set in the request, set its default to now
if ( ! isset( $request['start_date'] ) ) {
$request['start_date'] = gmdate( 'Y-m-d H:i:s' );
}
// prepare all subscription data from the request
$subscription = $this->prepare_item_for_database( $request );
$subscription->set_created_via( 'rest-api' );
$subscription->set_prices_include_tax( 'yes' === get_option( 'woocommerce_prices_include_tax' ) );
$subscription->calculate_totals();
// allow the order total to be overriden (i.e. if you want to have a subscription with no order items but a flat $10.00 recurring payment )
if ( isset( $request['order_total'] ) ) {
$subscription->set_total( wc_format_decimal( $request['order_total'], get_option( 'woocommerce_price_num_decimals' ) ) );
}
// Store the post meta on the subscription after it's saved, this is to avoid compat. issue with the filters in WC_Subscription::set_payment_method_meta() expecting the $subscription to have an ID (therefore it needs to be called after the WC_Subscription has been saved)
$payment_data = ( ! empty( $request['payment_details'] ) ) ? $request['payment_details'] : array();
if ( empty( $payment_data['payment_details']['method_id'] ) && ! empty( $request['payment_method'] ) ) {
$payment_data['method_id'] = $request['payment_method'];
}
$this->update_payment_method( $subscription, $payment_data );
$subscription->save();
// Handle set paid.
if ( true === $request['set_paid'] ) {
$subscription->payment_complete( $request['transaction_id'] );
}
do_action( 'wcs_api_subscription_created', $subscription->get_id() );
return $subscription->get_id();
} catch ( WC_Data_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), $e->getErrorData() );
} catch ( WC_REST_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Overrides WC_REST_Orders_Controller::update_order to update subscription specific meta
* calls parent::update_order to update the rest.
*
* @since 2.1
* @param WP_REST_Request $request
* @param WP_POST $post
*/
protected function update_order( $request ) {
try {
$subscription = $this->prepare_item_for_database( $request );
// If any line items have changed, recalculate subscription totals.
if ( isset( $request['line_items'] ) || isset( $request['shipping_lines'] ) || isset( $request['fee_lines'] ) || isset( $request['coupon_lines'] ) ) {
$subscription->calculate_totals();
}
// allow the order total to be overriden (i.e. if you want to have a subscription with no order items but a flat $10.00 recurring payment )
if ( isset( $request['order_total'] ) ) {
$subscription->set_total( wc_format_decimal( $request['order_total'], get_option( 'woocommerce_price_num_decimals' ) ) );
}
$subscription->save();
// Update the post meta on the subscription after it's saved, this is to avoid compat. issue with the filters in WC_Subscription::set_payment_method_meta() expecting the $subscription to have an ID (therefore it needs to be called after the WC_Subscription has been saved)
$payment_data = ( ! empty( $request['payment_details'] ) ) ? $request['payment_details'] : array();
$existing_payment_method_id = $subscription->get_payment_method();
if ( empty( $payment_data['method_id'] ) && isset( $request['payment_method'] ) ) {
$payment_data['method_id'] = $request['payment_method'];
} elseif ( ! empty( $existing_payment_method_id ) ) {
$payment_data['method_id'] = $existing_payment_method_id;
}
if ( isset( $payment_data['method_id'] ) ) {
$this->update_payment_method( $subscription, $payment_data, true );
}
// Handle set paid.
if ( $subscription->needs_payment() && true === $request['set_paid'] ) {
$subscription->payment_complete();
}
do_action( 'wcs_api_subscription_updated', $subscription->get_id() );
return $subscription->get_id();
} catch ( WC_Data_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), $e->getErrorData() );
} catch ( WC_REST_Exception $e ) {
return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) );
}
}
/**
* Get subscription orders
*
* @since 2.1
* @param WP_REST_Request $request
* @return WP_Error|WP_REST_Response $response
*/
public function get_subscription_orders( $request ) {
$id = (int) $request['id'];
if ( empty( $id ) || ! wcs_is_subscription( $id ) ) {
return new WP_Error( 'woocommerce_rest_invalid_shop_subscription_id', __( 'Invalid subscription id.', 'woocommerce-subscriptions' ), array( 'status' => 404 ) );
}
$this->post_type = 'shop_order';
$subscription = wcs_get_subscription( $id );
$subscription_orders = $subscription->get_related_orders();
$orders = array();
foreach ( $subscription_orders as $order_id ) {
$post = get_post( $order_id );
// Validate that the order can be loaded before trying to generate a response object for it.
$order = wc_get_order( $order_id );
if ( ! $order || ! wc_rest_check_post_permissions( $this->post_type, 'read', $post->ID ) ) {
continue;
}
$response = $this->prepare_item_for_response( $post, $request );
foreach ( array( 'parent', 'renewal', 'switch' ) as $order_type ) {
if ( wcs_order_contains_subscription( $order_id, $order_type ) ) {
$response->data['order_type'] = $order_type . '_order';
break;
}
}
$orders[] = $this->prepare_response_for_collection( $response );
}
$response = rest_ensure_response( $orders );
$response->header( 'X-WP-Total', count( $orders ) );
$response->header( 'X-WP-TotalPages', 1 );
return apply_filters( 'wcs_rest_subscription_orders_response', $response, $request );
}
/**
* Get subscription statuses
*
* @since 2.1
*/
public function get_statuses() {
return rest_ensure_response( wcs_get_subscription_statuses() );
}
/**
* Overrides WC_REST_Orders_Controller::get_order_statuses() so that subscription statuses are
* validated correctly in WC_REST_Orders_Controller::get_collection_params()
*
* @since 2.1
*/
protected function get_order_statuses() {
$subscription_statuses = array();
foreach ( array_keys( wcs_get_subscription_statuses() ) as $status ) {
$subscription_statuses[] = str_replace( 'wc-', '', $status );
}
return $subscription_statuses;
}
/**
* Validate and update payment method on a subscription
*
* @since 2.1
* @param WC_Subscription $subscription
* @param array $data
* @param bool $updating
*/
public function update_payment_method( $subscription, $data, $updating = false ) {
$payment_method = ( ! empty( $data['method_id'] ) ) ? $data['method_id'] : '';
try {
if ( $updating && ! array_key_exists( $payment_method, WCS_Change_Payment_Method_Admin::get_valid_payment_methods( $subscription ) ) ) {
throw new Exception( __( 'Gateway does not support admin changing the payment method on a Subscription.', 'woocommerce-subscriptions' ) );
}
$payment_method_meta = apply_filters( 'woocommerce_subscription_payment_meta', array(), $subscription );
// Reload the subscription to update the meta values.
// In particular, the update_post_meta() called while _stripe_card_id is updated to _stripe_source_id
$subscription = wcs_get_subscription( $subscription->get_id() );
if ( isset( $payment_method_meta[ $payment_method ] ) ) {
$payment_method_meta = $payment_method_meta[ $payment_method ];
if ( ! empty( $payment_method_meta ) ) {
foreach ( $payment_method_meta as $meta_table => &$meta ) {
if ( ! is_array( $meta ) ) {
continue;
}
foreach ( $meta as $meta_key => &$meta_data ) {
if ( isset( $data[ $meta_table ][ $meta_key ] ) ) {
$meta_data['value'] = $data[ $meta_table ][ $meta_key ];
}
}
}
}
}
$subscription->set_payment_method( $payment_method, $payment_method_meta );
// Save the subscription to reflect the new values
$subscription->save();
} catch ( Exception $e ) {
$subscription->set_payment_method();
$subscription->save();
// translators: 1$: gateway id, 2$: error message
throw new WC_REST_Exception( 'woocommerce_rest_invalid_payment_data', sprintf( __( 'Subscription payment method could not be set to %1$s with error message: %2$s', 'woocommerce-subscriptions' ), $payment_method, $e->getMessage() ), 400 );
}
}
/**
* Prepare a single subscription for create.
*
* @param WP_REST_Request $request Request object.
* @return WP_Error|WC_Subscription $data Object.
*/
protected function prepare_item_for_database( $request ) {
$id = isset( $request['id'] ) ? absint( $request['id'] ) : 0;
$subscription = new WC_Subscription( $id );
$schema = $this->get_item_schema();
$data_keys = array_keys( array_filter( $schema['properties'], array( $this, 'filter_writable_props' ) ) );
$dates_to_update = array();
// Handle all writable props
foreach ( $data_keys as $key ) {
$value = $request[ $key ];
if ( ! is_null( $value ) ) {
switch ( $key ) {
case 'billing':
case 'shipping':
$this->update_address( $subscription, $value, $key );
break;
case 'line_items':
case 'shipping_lines':
case 'fee_lines':
case 'coupon_lines':
if ( is_array( $value ) ) {
foreach ( $value as $item ) {
if ( is_array( $item ) ) {
if ( $this->item_is_null( $item ) || ( isset( $item['quantity'] ) && 0 === $item['quantity'] ) ) {
$subscription->remove_item( $item['id'] );
} else {
$this->set_item( $subscription, $key, $item );
}
}
}
}
break;
case 'transition_status':
$subscription->update_status( $value );
break;
case 'start_date':
case 'trial_end_date':
case 'next_payment_date':
case 'end_date':
$dates_to_update[ $key ] = $value;
break;
default:
if ( is_callable( array( $subscription, "set_{$key}" ) ) ) {
$subscription->{"set_{$key}"}( $value );
}
break;
}
}
}
$subscription->save();
try {
if ( ! empty( $dates_to_update ) ) {
$subscription->update_dates( $dates_to_update );
}
} catch ( Exception $e ) {
// translators: placeholder is an error message.
throw new WC_REST_Exception( 'woocommerce_rest_cannot_update_subscription_dates', sprintf( __( 'Updating subscription dates errored with message: %s', 'woocommerce-subscriptions' ), $e->getMessage() ), 400 );
}
/**
* Filter the data for the insert.
*
* The dynamic portion of the hook name, $this->post_type, refers to post_type of the post being
* prepared for the response.
*
* @param WC_Subscription $subscription The subscription object.
* @param WP_REST_Request $request Request object.
*/
return apply_filters( "woocommerce_rest_pre_insert_{$this->post_type}", $subscription, $request );
}
/**
* Adds additional item schema information for subscription requests
*
* @since 2.1
*/
public function get_item_schema() {
$schema = parent::get_item_schema();
$subscriptions_schema = array(
'transition_status' => array(
'description' => __( 'The status to transition the subscription to. Unlike the "status" param, this will calculate and update the subscription dates.', 'woocommerce-subscriptions' ),
'type' => 'string',
'enum' => $this->get_order_statuses(),
'context' => array( 'edit' ),
),
'billing_interval' => array(
'description' => __( 'The number of billing periods between subscription renewals.', 'woocommerce-subscriptions' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
'billing_period' => array(
'description' => __( 'Billing period for the subscription.', 'woocommerce-subscriptions' ),
'type' => 'string',
'enum' => array_keys( wcs_get_subscription_period_strings() ),
'context' => array( 'view', 'edit' ),
),
'payment_details' => array(
'description' => __( 'Subscription payment details.', 'woocommerce-subscriptions' ),
'type' => 'object',
'context' => array( 'edit' ),
'properties' => array(
'method_id' => array(
'description' => __( 'Payment gateway ID.', 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'edit' ),
),
),
),
'start_date' => array(
'description' => __( "The subscription's start date.", 'woocommerce-subscriptions' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
),
'trial_end_date' => array(
'description' => __( "The subscription's trial date", 'woocommerce-subscriptions' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
),
'next_payment_date' => array(
'description' => __( "The subscription's next payment date.", 'woocommerce-subscriptions' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
),
'end_date' => array(
'description' => __( "The subscription's end date.", 'woocommerce-subscriptions' ),
'type' => 'date-time',
'context' => array( 'view', 'edit' ),
),
'resubscribed_from' => array(
'description' => __( "The subscription's original subscription ID if this is a resubscribed subscription.", 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view' ),
'readonly' => true,
),
'resubscribed_subscription' => array(
'description' => __( "The subscription's resubscribed subscription ID.", 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view' ),
'readonly' => true,
),
'date_completed_gmt' => array(
'description' => __( "The date the subscription's latest order was completed, in GMT.", 'woocommerce-subscriptions' ),
'type' => 'date-time',
'context' => array( 'view' ),
'readonly' => true,
),
'date_paid_gmt' => array(
'description' => __( "The date the subscription's latest order was paid, in GMT.", 'woocommerce-subscriptions' ),
'type' => 'date-time',
'context' => array( 'view' ),
'readonly' => true,
),
'removed_line_items' => array(
'description' => __( 'Removed line items data.', 'woocommerce-subscriptions' ),
'type' => 'array',
'context' => array( 'view', 'edit' ),
'items' => array(
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'Item ID.', 'woocommerce-subscriptions' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'name' => array(
'description' => __( 'Product name.', 'woocommerce-subscriptions' ),
'type' => 'mixed',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'sku' => array(
'description' => __( 'Product SKU.', 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'product_id' => array(
'description' => __( 'Product ID.', 'woocommerce-subscriptions' ),
'type' => 'mixed',
'context' => array( 'view', 'edit' ),
),
'variation_id' => array(
'description' => __( 'Variation ID, if applicable.', 'woocommerce-subscriptions' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
'quantity' => array(
'description' => __( 'Quantity ordered.', 'woocommerce-subscriptions' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
),
'tax_class' => array(
'description' => __( 'Tax class of product.', 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'price' => array(
'description' => __( 'Product price.', 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'subtotal' => array(
'description' => __( 'Line subtotal (before discounts).', 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'subtotal_tax' => array(
'description' => __( 'Line subtotal tax (before discounts).', 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'total' => array(
'description' => __( 'Line total (after discounts).', 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'total_tax' => array(
'description' => __( 'Line total tax (after discounts).', 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
'taxes' => array(
'description' => __( 'Line taxes.', 'woocommerce-subscriptions' ),
'type' => 'array',
'context' => array( 'view', 'edit' ),
'readonly' => true,
'items' => array(
'type' => 'object',
'properties' => array(
'id' => array(
'description' => __( 'Tax rate ID.', 'woocommerce-subscriptions' ),
'type' => 'integer',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'total' => array(
'description' => __( 'Tax total.', 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'subtotal' => array(
'description' => __( 'Tax subtotal.', 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
),
),
),
'meta' => array(
'description' => __( 'Removed line item meta data.', 'woocommerce-subscriptions' ),
'type' => 'array',
'context' => array( 'view', 'edit' ),
'readonly' => true,
'items' => array(
'type' => 'object',
'properties' => array(
'key' => array(
'description' => __( 'Meta key.', 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'label' => array(
'description' => __( 'Meta label.', 'woocommerce-subscriptions' ),
'type' => 'string',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
'value' => array(
'description' => __( 'Meta value.', 'woocommerce-subscriptions' ),
'type' => 'mixed',
'context' => array( 'view', 'edit' ),
'readonly' => true,
),
),
),
),
),
),
),
);
$schema['properties'] += $subscriptions_schema;
return $schema;
}
/**
* Deprecated functions
*/
/**
* Prepare subscription data for create.
*
* Now that we override WC_REST_Orders_V1_Controller::prepare_item_for_database() function,
* we no longer need to prepare these args
*
* @since 2.1
* @param stdClass $data
* @param WP_REST_Request $request Request object.
* @return stdClass
* @deprecated 2.2
*/
public function prepare_subscription_args( $data, $request ) {
wcs_deprecated_function( __METHOD__, '2.2' );
$data->billing_interval = $request['billing_interval'];
$data->billing_period = $request['billing_period'];
foreach ( array( 'start', 'trial_end', 'end', 'next_payment' ) as $date_type ) {
if ( ! empty( $request[ $date_type . '_date' ] ) ) {
$date_type_key = ( 'start' === $date_type ) ? 'date_created' : $date_type . '_date';
$data->{$date_type_key} = $request[ $date_type . '_date' ];
}
}
$data->payment_details = ! empty( $request['payment_details'] ) ? $request['payment_details'] : '';
$data->payment_method = ! empty( $request['payment_method'] ) ? $request['payment_method'] : '';
return $data;
}
/**
* Update or set the subscription schedule with the request data.
*
*
* @since 2.1
* @param WC_Subscription $subscription
* @param array $data
* @deprecated 2.2
*/
public function update_schedule( $subscription, $data ) {
wcs_deprecated_function( __METHOD__, '2.2', 'WC_REST_Subscriptions_Controller::prepare_item_for_database() now prepares the billing interval/period and dates' );
if ( isset( $data['billing_interval'] ) ) {
$subscription->set_billing_interval( absint( $data['billing_interval'] ) );
}
if ( ! empty( $data['billing_period'] ) ) {
$subscription->set_billing_period( $data['billing_period'] );
}
try {
$dates_to_update = array();
foreach ( array( 'start', 'trial_end', 'end', 'next_payment' ) as $date_type ) {
if ( isset( $data[ $date_type . '_date' ] ) ) {
$date_type_key = ( 'start' === $date_type ) ? 'date_created' : $date_type;
$dates_to_update[ $date_type_key ] = $data[ $date_type . '_date' ];
}
}
if ( ! empty( $dates_to_update ) ) {
$subscription->update_dates( $dates_to_update );
}
} catch ( Exception $e ) {
// translators: placeholder is an error message.
throw new WC_REST_Exception( 'woocommerce_rest_cannot_update_subscription_dates', sprintf( __( 'Updating subscription dates errored with message: %s', 'woocommerce-subscriptions' ), $e->getMessage() ), 400 );
}
}
}

View File

@@ -0,0 +1,223 @@
<?php
/**
* WooCommerce Subscriptions setup
*
* @package WooCommerce Subscriptions
* @since 4.0.0
*/
defined( 'ABSPATH' ) || exit;
class WC_Subscriptions_Plugin extends WC_Subscriptions_Core_Plugin {
/**
* Initialise the WC Subscriptions plugin.
*
* @since 4.0.0
*/
public function init() {
parent::init();
WC_Subscriptions_Switcher::init();
new WCS_Cart_Switch();
WCS_Manual_Renewal_Manager::init();
WCS_Customer_Suspension_Manager::init();
WCS_Drip_Downloads_Manager::init();
WCS_Zero_Initial_Payment_Checkout_Manager::init();
WCS_Retry_Manager::init();
WCS_Early_Renewal_Modal_Handler::init();
WCS_Limited_Recurring_Coupon_Manager::init();
WCS_Call_To_Action_Button_Text_Manager::init();
WCS_Subscriber_Role_Manager::init();
WCS_Upgrade_Notice_Manager::init();
add_action( 'admin_enqueue_scripts', array( $this, 'maybe_show_welcome_message' ) );
}
/**
* Initialises classes which need to be loaded after other plugins have loaded.
*
* Hooked onto 'plugins_loaded' by @see WC_Subscriptions_Core_Plugin::init()
*
* @since 4.0.0
*/
public function init_version_dependant_classes() {
parent::init_version_dependant_classes();
WCS_API::init();
new WCS_Auth();
WCS_Webhooks::init();
new WCS_Admin_Reports();
new WCS_Report_Cache_Manager();
if ( class_exists( 'WCS_Early_Renewal' ) ) {
$notice = new WCS_Admin_Notice( 'error' );
// translators: 1-2: opening/closing <b> tags, 3: Subscriptions version.
$notice->set_simple_content( sprintf( __( '%1$sWarning!%2$s We can see the %1$sWooCommerce Subscriptions Early Renewal%2$s plugin is active. Version %3$s of %1$sWooCommerce Subscriptions%2$s comes with that plugin\'s functionality packaged into the core plugin. Please deactivate WooCommerce Subscriptions Early Renewal to avoid any conflicts.', 'woocommerce-subscriptions' ), '<b>', '</b>', $this->get_plugin_version() ) );
$notice->set_actions(
array(
array(
'name' => __( 'Installed Plugins', 'woocommerce-subscriptions' ),
'url' => admin_url( 'plugins.php' ),
),
)
);
$notice->display();
} else {
WCS_Early_Renewal_Manager::init();
require_once $this->get_plugin_directory( 'includes/early-renewal/wcs-early-renewal-functions.php' );
if ( WCS_Early_Renewal_Manager::is_early_renewal_enabled() ) {
new WCS_Cart_Early_Renewal();
}
}
}
/**
* Gets the plugin's directory url.
*
* @since 4.0.0
* @param string $path Optional. The path to append.
* @return string
*/
public function get_plugin_directory_url( $path = '' ) {
return plugin_dir_url( WC_Subscriptions::$plugin_file ) . $path;
}
/**
* Gets the plugin's directory.
*
* @since 4.0.0
* @param string $path Optional. The path to append.
* @return string
*/
public function get_plugin_directory( $path = '' ) {
return plugin_dir_path( WC_Subscriptions::$plugin_file ) . $path;
}
/**
* Gets the activation transient name.
*
* @since 4.0.0
* @return string The transient name used to record when the plugin was activated.
*/
public function get_activation_transient() {
return WC_Subscriptions::$activation_transient;
}
/**
* Gets the product type name.
*
* @since 4.0.0
* @return string The product type name.
*/
public function get_product_type_name() {
return WC_Subscriptions::$name;
}
/**
* Gets the plugin's version
*
* @since 4.0.0
* @return string The plugin version.
*/
public function get_plugin_version() {
return WC_Subscriptions::$version;
}
/**
* Gets the plugin file name
*
* @since 4.0.0
* @return string The plugin file
*/
public function get_plugin_file() {
return WC_Subscriptions::$plugin_file;
}
/**
* Gets the Payment Gateways handler class
*
* @since 4.0.0
* @return string
*/
public function get_gateways_handler_class() {
return 'WC_Subscriptions_Payment_Gateways';
}
/**
* Adds welcome message after activating the plugin
*/
public function maybe_show_welcome_message() {
$plugin_has_just_been_activated = (bool) get_transient( WC_Subscriptions_Core_Plugin::instance()->get_activation_transient() );
// Maybe add the admin notice.
if ( $plugin_has_just_been_activated ) {
$woocommerce_plugin_dir_file = WC_Subscriptions_Admin::get_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',
)
);
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 ), [], WC_Subscriptions_Core_Plugin::instance()->get_plugin_version() );
if ( ! isset( $_GET['page'] ) || 'wcs-about' !== $_GET['page'] ) {
add_action( 'admin_notices', array( $this, 'admin_installed_notice' ) );
}
}
delete_transient( WC_Subscriptions_Core_Plugin::instance()->get_activation_transient() );
}
}
/**
* Outputs a welcome message. Called when the Subscriptions extension is activated.
*
* @since 1.0
*/
public function admin_installed_notice() {
?>
<div id="message" class="updated woocommerce-message wc-connect woocommerce-subscriptions-activated">
<div class="squeezer">
<h4>
<?php
echo wp_kses(
sprintf(
// translators: $1-$2: opening and closing <strong> tags, $3-$4: opening and closing <em> tags.
__(
'%1$sWooCommerce Subscriptions Installed%2$s &#8211; %3$sYou\'re ready to start selling subscriptions!%4$s',
'woocommerce-subscriptions'
),
'<strong>',
'</strong>',
'<em>',
'</em>'
),
[
'strong' => true,
'em' => true,
]
);
?>
</h4>
<p class="submit">
<a href="<?php echo esc_url( WC_Subscriptions_Admin::add_subscription_url() ); ?>" class="button button-primary"><?php esc_html_e( 'Add a Subscription Product', 'woocommerce-subscriptions' ); ?></a>
<a href="<?php echo esc_url( WC_Subscriptions_Admin::settings_tab_url() ); ?>" class="docs button button-primary"><?php esc_html_e( 'Settings', 'woocommerce-subscriptions' ); ?></a>
<a href="https://twitter.com/share" class="twitter-share-button" data-url="http://www.woocommerce.com/products/woocommerce-subscriptions/" data-text="Woot! I can sell subscriptions with #WooCommerce" data-via="WooCommerce" data-size="large">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</p>
</div>
</div>
<?php
}
}

View File

@@ -15,9 +15,9 @@ if ( ! defined( 'ABSPATH' ) ) {
class WCS_API { class WCS_API {
public static function init() { public static function init() {
add_filter( 'woocommerce_api_classes', __CLASS__ . '::includes' ); add_filter( 'woocommerce_api_classes', array( __CLASS__, 'includes' ) );
add_action( 'rest_api_init', array( __CLASS__, 'register_routes' ), 15 );
add_action( 'rest_api_init', __CLASS__ . '::register_routes', 15 ); add_action( 'rest_api_init', array( __CLASS__, 'register_route_overrides' ), 15 );
} }
/** /**
@@ -44,16 +44,47 @@ class WCS_API {
* @since 2.1 * @since 2.1
*/ */
public static function register_routes() { public static function register_routes() {
global $wp_version;
if ( version_compare( $wp_version, 4.4, '<' ) || WC_Subscriptions::is_woocommerce_pre( '2.6' ) ) { if ( ! self::is_wp_compatible() ) {
return; return;
} }
foreach ( array( 'WC_REST_Subscriptions_Controller', 'WC_REST_Subscription_Notes_Controller' ) as $api_class ) { $endpoint_classes = array(
$controller = new $api_class(); // V1
'WC_REST_Subscriptions_V1_Controller',
'WC_REST_Subscription_Notes_V1_Controller',
// V3 (latest)
'WC_REST_Subscriptions_Controller',
'WC_REST_Subscription_notes_Controller',
);
foreach ( $endpoint_classes as $class ) {
$controller = new $class();
$controller->register_routes(); $controller->register_routes();
} }
} }
/**
* Register classes which override base endpoints.
*
* @since 3.1.0
*/
public static function register_route_overrides() {
if ( ! self::is_wp_compatible() ) {
return;
}
WC_REST_Subscription_System_Status_Manager::init();
}
/**
* Determines if a WP version compatible with REST API requests.
*
* @since 3.1.0
* @return boolean
*/
protected static function is_wp_compatible() {
global $wp_version;
return version_compare( $wp_version, '4.4', '>=' );
}
} }

View File

@@ -1,23 +1,14 @@
<?php <?php
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
die();
}
/** /**
* WooCommerce Subscriptions Autoloader. * WooCommerce Subscriptions Autoloader.
* *
* @class WCS_Autoloader * @package WC_Subscriptions
*/ */
class WCS_Autoloader {
/** // Exit if accessed directly.
* The base path for autoloading. defined( 'ABSPATH' ) || exit;
*
* @var string class WCS_Autoloader extends WCS_Core_Autoloader {
*/
protected $base_path = '';
/** /**
* Whether to use the legacy API classes. * Whether to use the legacy API classes.
@@ -27,246 +18,173 @@ class WCS_Autoloader {
protected $legacy_api = false; protected $legacy_api = false;
/** /**
* WCS_Autoloader constructor. * The classes the Subscriptions plugin has ownership of.
* *
* @param string $base_path * Note: needs to be lowercase.
*
* @var array
*/ */
public function __construct( $base_path ) { private $classes = array(
$this->base_path = untrailingslashit( $base_path ); 'wc_subscriptions_plugin' => true,
} 'wc_subscriptions_switcher' => true,
'wcs_cart_switch' => true,
/** 'wcs_switch_totals_calculator' => true,
* Destructor. 'wcs_switch_cart_item' => true,
*/ 'wcs_add_cart_item' => true,
public function __destruct() { 'wc_order_item_pending_switch' => true,
$this->unregister(); 'wcs_manual_renewal_manager' => true,
} 'wcs_customer_suspension_manager' => true,
'wcs_drip_downloads_manager' => true,
/** 'wcs_zero_initial_payment_checkout_manager' => true,
* Register the autoloader. 'wcs_meta_box_payment_retries' => true,
* 'wcs_limited_recurring_coupon_manager' => true,
* @author Jeremy Pry 'wcs_call_to_action_button_text_manager' => true,
*/ 'wcs_subscriber_role_manager' => true,
public function register() { 'wc_subscriptions_payment_gateways' => true,
spl_autoload_register( array( $this, 'autoload' ) ); 'wcs_api' => true,
} 'wcs_webhooks' => true,
'wcs_auth' => true,
/** 'wcs_upgrade_notice_manager' => true,
* Unregister the autoloader.
*/
public function unregister() {
spl_autoload_unregister( array( $this, 'autoload' ) );
}
/**
* Autoload a class.
*
* @author Jeremy Pry
*
* @param string $class The class name to autoload.
*/
public function autoload( $class ) {
$class = strtolower( $class );
if ( ! $this->should_autoload( $class ) ) {
return;
}
$full_path = $this->base_path . $this->get_relative_class_path( $class ) . $this->get_file_name( $class );
if ( is_readable( $full_path ) ) {
require_once( $full_path );
}
}
/**
* Determine whether we should autoload a given class.
*
* @author Jeremy Pry
*
* @param string $class The class name.
*
* @return bool
*/
protected function should_autoload( $class ) {
// We're not using namespaces, so if the class has namespace separators, skip.
if ( false !== strpos( $class, '\\' ) ) {
return false;
}
// There are some legacy classes without WCS or Subscription in the name.
static $legacy = array(
'wc_order_item_pending_switch' => 1,
'wc_report_retention_rate' => 1,
'wc_report_upcoming_recurring_revenue' => 1,
);
if ( isset( $legacy[ $class ] ) ) {
return true;
}
return false !== strpos( $class, 'wcs_' ) || 0 === strpos( $class, 'wc_subscription' ) || ( false !== strpos( $class, 'wc_' ) && false !== strpos( $class, 'subscription' ) );
}
/**
* Convert the class name into an appropriate file name.
*
* @author Jeremy Pry
*
* @param string $class The class name.
*
* @return string The file name.
*/
protected function get_file_name( $class ) {
$file_prefix = 'class-';
if ( $this->is_class_abstract( $class ) ) {
$file_prefix = 'abstract-';
} elseif ( $this->is_class_interface( $class ) ) {
$file_prefix = 'interface-';
}
return $file_prefix . str_replace( '_', '-', $class ) . '.php';
}
/**
* Determine if the class is one of our abstract classes.
*
* @author Jeremy Pry
*
* @param string $class The class name.
*
* @return bool
*/
protected function is_class_abstract( $class ) {
static $abstracts = array(
'wcs_background_repairer' => true,
'wcs_background_updater' => true,
'wcs_background_upgrader' => true,
'wcs_cache_manager' => true,
'wcs_debug_tool' => true,
'wcs_debug_tool_cache_updater' => true,
'wcs_dynamic_hook_deprecator' => true,
'wcs_hook_deprecator' => true,
'wcs_retry_store' => true,
'wcs_scheduler' => true,
'wcs_sv_api_base' => true,
'wcs_customer_store' => true,
'wcs_related_order_store' => true,
'wcs_migrator' => true,
'wcs_table_maker' => true,
); );
return isset( $abstracts[ $class ] );
}
/** /**
* Determine if the class is one of our class interfaces. * The substrings of the classes that the Subscriptions plugin has ownership of.
* *
* @param string $class The class name. * @var array
* @return bool
*/ */
protected function is_class_interface( $class ) { private $class_substrings = array(
static $interfaces = array( 'wc_reports',
'wcs_cache_updater' => true, 'report',
'retry',
'early_renewal',
'rest_subscription',
'wc_api_subscriptions',
); );
return isset( $interfaces[ $class ] ); /**
* Gets the class's base path.
*
* If the a class is one the plugin is responsible for, we return the plugin's path. Otherwise we let the library handle it.
*
* @since 4.0.0
* @return string
*/
public function get_class_base_path( $class ) {
if ( $this->is_plugin_class( $class ) ) {
return dirname( WC_Subscriptions::$plugin_file );
} }
/** return parent::get_class_base_path( $class );
* Determine if the class is one of our data stores.
*
* @param string $class The class name.
* @return bool
*/
protected function is_class_data_store( $class ) {
static $data_stores = array(
'wcs_related_order_store_cached_cpt' => true,
'wcs_related_order_store_cpt' => true,
'wcs_customer_store_cached_cpt' => true,
'wcs_customer_store_cpt' => true,
'wcs_product_variable_data_store_cpt' => true,
'wcs_subscription_data_store_cpt' => true,
);
return isset( $data_stores[ $class ] );
} }
/** /**
* Get the relative path for the class location. * Get the relative path for the class location.
* *
* This handles all of the special class locations and exceptions.
*
* @author Jeremy Pry
*
* @param string $class The class name. * @param string $class The class name.
*
* @return string The relative path (from the plugin root) to the class file. * @return string The relative path (from the plugin root) to the class file.
*/ */
protected function get_relative_class_path( $class ) { protected function get_relative_class_path( $class ) {
$path = '/includes'; if ( ! $this->is_plugin_class( $class ) ) {
$is_admin = ( false !== strpos( $class, 'admin' ) ); return parent::get_relative_class_path( $class );
}
if ( $this->is_class_abstract( $class ) ) { $path = '/includes';
if ( 'wcs_sv_api_base' === $class ) {
$path .= '/gateways/paypal/includes/abstracts'; if ( stripos( $class, 'switch' ) !== false || 'wcs_add_cart_item' === $class ) {
} else { $path .= '/switching';
$path .= '/abstracts';
}
} elseif ( $this->is_class_interface( $class ) ) {
$path .= '/interfaces';
} elseif ( false !== strpos( $class, 'paypal' ) ) {
$path .= '/gateways/paypal';
if ( 'wcs_paypal' === $class ) {
$path .= '';
} elseif ( 'wcs_repair_suspended_paypal_subscriptions' === $class ) {
// Deliberately avoid concatenation for this class, using the base path.
$path = '/includes/upgrades';
} elseif ( $is_admin ) {
$path .= '/includes/admin';
} elseif ( 'wc_paypal_standard_subscriptions' === $class ) {
$path .= '/includes/deprecated';
} else {
$path .= '/includes';
}
} elseif ( 0 === strpos( $class, 'wcs_retry' ) && 'wcs_retry_manager' !== $class ) {
$path .= '/payment-retry';
} elseif ( $is_admin && 'wcs_change_payment_method_admin' !== $class ) {
$path .= '/admin';
} elseif ( false !== strpos( $class, 'meta_box' ) ) {
$path .= '/admin/meta-boxes';
} elseif ( false !== strpos( $class, 'wc_report' ) ) { } elseif ( false !== strpos( $class, 'wc_report' ) ) {
$path .= '/admin/reports/deprecated'; $path .= '/admin/reports/deprecated';
} elseif ( false !== strpos( $class, 'report' ) ) { } elseif ( false !== strpos( $class, 'wcs_report' ) ) {
$path .= '/admin/reports'; $path .= '/admin/reports';
} elseif ( false !== strpos( $class, 'debug_tool' ) ) { } elseif ( false !== strpos( $class, 'retry' ) || false !== strpos( $class, 'retries' ) ) {
$path .= '/admin/debug-tools'; $path .= $this->get_payment_retry_class_relative_path( $class );
} elseif ( false !== strpos( $class, 'rest' ) ) { } elseif ( false !== strpos( $class, 'admin' ) ) {
$path .= $this->legacy_api ? '/api/legacy' : '/api'; $path .= '/admin';
} elseif ( false !== strpos( $class, 'api' ) && 'wcs_api' !== $class ) {
$path .= '/api/legacy';
} elseif ( $this->is_class_data_store( $class ) ) {
$path .= '/data-stores';
} elseif ( false !== strpos( $class, 'deprecat' ) ) {
$path .= '/deprecated';
} elseif ( false !== strpos( $class, 'email' ) && 'wc_subscriptions_email' !== $class ) {
$path .= '/emails';
} elseif ( false !== strpos( $class, 'gateway' ) && 'wc_subscriptions_change_payment_gateway' !== $class ) {
$path .= '/gateways';
} elseif ( false !== strpos( $class, 'legacy' ) || 'wcs_array_property_post_meta_black_magic' === $class ) {
$path .= '/legacy';
} elseif ( false !== strpos( $class, 'privacy' ) ) {
$path .= '/privacy';
} elseif ( false !== strpos( $class, 'upgrade' ) || false !== strpos( $class, 'repair' ) ) {
$path .= '/upgrades';
} elseif ( false !== strpos( $class, 'early' ) ) { } elseif ( false !== strpos( $class, 'early' ) ) {
$path .= '/early-renewal'; $path .= '/early-renewal';
} elseif ( false !== strpos( $class, 'gateways' ) ) {
$path .= '/gateways';
} elseif ( false !== strpos( $class, 'rest' ) ) {
$path .= $this->legacy_api ? '/api/legacy' : $this->get_rest_api_directory( $class );
} elseif ( false !== strpos( $class, 'api' ) && 'wcs_api' !== $class ) {
$path .= '/api/legacy';
} }
return trailingslashit( $path ); return trailingslashit( $path );
} }
/**
* Determine whether we should autoload a given class.
*
* @param string $class The class name.
* @return bool
*/
protected function should_autoload( $class ) {
static $legacy = array(
'wc_order_item_pending_switch' => 1,
'wc_report_retention_rate' => 1,
'wc_report_upcoming_recurring_revenue' => 1,
);
return isset( $legacy[ $class ] ) ? true : parent::should_autoload( $class );
}
/**
* Is the given class found in the Subscriptions plugin
*
* @since 4.0.0
* @param string $class
* @return bool
*/
private function is_plugin_class( $class ) {
if ( isset( $this->classes[ $class ] ) ) {
return true;
}
foreach ( $this->class_substrings as $substring ) {
if ( false !== stripos( $class, $substring ) ) {
return true;
}
}
return false;
}
/**
* Gets a retry class's relative path.
*
* @param string $class The retry class being loaded.
* @return string The relative path to the retry class.
*/
private function get_payment_retry_class_relative_path( $class ) {
$relative_path = '/payment-retry';
if ( false !== strpos( $class, 'admin' ) || false !== strpos( $class, 'meta_box' ) ) {
$relative_path .= '/admin';
} elseif ( false !== strpos( $class, 'email' ) ) {
$relative_path .= '/emails';
} elseif ( false !== strpos( $class, 'store' ) ) {
$relative_path .= '/data-stores';
}
return $relative_path;
}
/**
* Determine if the class is one of our abstract classes.
*
* @param string $class The class name.
* @return bool
*/
protected function is_class_abstract( $class ) {
static $abstracts = array(
'wcs_retry_store' => true,
);
return isset( $abstracts[ $class ] ) || parent::is_class_abstract( $class );
}
/** /**
* Set whether the legacy API should be used. * Set whether the legacy API should be used.
* *
@@ -281,4 +199,23 @@ class WCS_Autoloader {
return $this; return $this;
} }
/**
* Gets the correct subdirectory for a version of the a REST API class.
*
* @param string $class The rest API class name.
* @return string The subdirectory for a rest API class.
*/
protected function get_rest_api_directory( $class ) {
$directory = '/api';
// Check for an API version in the class name.
preg_match( '/v\d/', $class, $matches );
if ( ! empty( $matches ) ) {
$directory .= "/{$matches[0]}";
}
return $directory;
}
} }

View File

@@ -0,0 +1,94 @@
<?php
/**
* A class for managing the place order and add to cart button text for subscription products.
*
* @package WooCommerce Subscriptions
* @since 4.0.0
*/
defined( 'ABSPATH' ) || exit;
class WCS_Call_To_Action_Button_Text_Manager {
/**
* Initialise the class's callbacks.
*/
public static function init() {
add_filter( 'woocommerce_subscription_settings', array( __CLASS__, 'add_settings' ), 5 );
add_filter( 'wc_subscription_product_add_to_cart_text', array( __CLASS__, 'filter_add_to_cart_text' ), 10, 2 );
add_filter( 'wcs_place_subscription_order_text', array( __CLASS__, 'filter_place_subscription_order_text' ) );
}
/**
* Adds the subscription add to cart and place order button text settings.
*
* @since 4.0.0
*
* @param array $settings The WC Subscriptions settings.
* @return array $settings
*/
public static function add_settings( $settings ) {
$button_text_settings = array(
array(
'name' => __( 'Button Text', 'woocommerce-subscriptions' ),
'type' => 'title',
'desc' => '',
'id' => WC_Subscriptions_Admin::$option_prefix . '_button_text',
),
array(
'name' => __( 'Add to Cart Button Text', 'woocommerce-subscriptions' ),
'desc' => __( 'A product displays a button with the text "Add to cart". By default, a subscription changes this to "Sign up now". You can customise the button text for subscriptions here.', 'woocommerce-subscriptions' ),
'tip' => '',
'id' => WC_Subscriptions_Admin::$option_prefix . '_add_to_cart_button_text',
'css' => 'min-width:150px;',
'default' => __( 'Sign up now', 'woocommerce-subscriptions' ),
'type' => 'text',
'desc_tip' => true,
'placeholder' => __( 'Sign up now', 'woocommerce-subscriptions' ),
),
array(
'name' => __( 'Place Order Button Text', 'woocommerce-subscriptions' ),
'desc' => __( 'Use this field to customise the text displayed on the checkout button when an order contains a subscription. Normally the checkout submission button displays "Place order". When the cart contains a subscription, this is changed to "Sign up now".', 'woocommerce-subscriptions' ),
'tip' => '',
'id' => WC_Subscriptions_Admin::$option_prefix . '_order_button_text',
'css' => 'min-width:150px;',
'default' => __( 'Sign up now', 'woocommerce-subscriptions' ),
'type' => 'text',
'desc_tip' => true,
'placeholder' => __( 'Sign up now', 'woocommerce-subscriptions' ),
),
array(
'type' => 'sectionend',
'id' => WC_Subscriptions_Admin::$option_prefix . '_button_text',
),
);
return array_merge( $button_text_settings, $settings );
}
/**
* Filters subscription products add to cart text to honour the setting.
*
* @since 4.0.0
*
* @param string $add_to_cart_text The product's add to cart text.
* @param WC_Abstract_Product $product The product.
*
* @return string
*/
public static function filter_add_to_cart_text( $add_to_cart_text ) {
return get_option( WC_Subscriptions_Admin::$option_prefix . '_add_to_cart_button_text', $add_to_cart_text );
}
/**
* Filters the place order text while there's a subscription in the cart.
*
* @since 4.0.0
*
* @param string $button_text The default place order button text.
* @return string The button text.
*/
public static function filter_place_subscription_order_text( $button_text ) {
return get_option( WC_Subscriptions_Admin::$option_prefix . '_order_button_text', $button_text );
}
}

View File

@@ -0,0 +1,126 @@
<?php
/**
* A class for managing the customer suspension feature.
*
* @package WooCommerce Subscriptions
* @since 4.0.0
*/
defined( 'ABSPATH' ) || exit;
class WCS_Customer_Suspension_Manager {
/**
* Initialise the class.
*/
public static function init() {
add_filter( 'woocommerce_subscription_settings', array( __CLASS__, 'add_settings' ), 5 );
add_filter( 'wcs_can_user_put_subscription_on_hold', array( __CLASS__, 'can_customer_put_subscription_on_hold' ), 0, 3 );
add_filter( 'wcs_view_subscription_actions', array( __CLASS__, 'add_customer_suspension_action' ), 0, 3 );
}
/**
* Adds the customer suspension setting.
*
* @since 4.0.0
*
* @param array $settings Subscriptions settings.
* @return array Subscriptions settings.
*/
public static function add_settings( $settings ) {
$suspension_setting = array(
'name' => __( 'Customer Suspensions', 'woocommerce-subscriptions' ),
'desc' => _x( 'suspensions per billing period.', 'there\'s a number immediately in front of this text', 'woocommerce-subscriptions' ),
'id' => WC_Subscriptions_Admin::$option_prefix . '_max_customer_suspensions',
'css' => 'min-width:50px;',
'default' => 0,
'type' => 'select',
'options' => apply_filters( 'woocommerce_subscriptions_max_customer_suspension_range', array_merge( range( 0, 12 ), array( 'unlimited' => 'Unlimited' ) ) ),
'desc_tip' => __( 'Set a maximum number of times a customer can suspend their account for each billing period. For example, for a value of 3 and a subscription billed yearly, if the customer has suspended their account 3 times, they will not be presented with the option to suspend their account until the next year. Store managers will always be able to suspend an active subscription. Set this to 0 to turn off the customer suspension feature completely.', 'woocommerce-subscriptions' ),
);
WC_Subscriptions_Admin::insert_setting_after( $settings, WC_Subscriptions_Admin::$option_prefix . '_miscellaneous', $suspension_setting );
return $settings;
}
/**
* Filters whether the current user can suspend the subscription.
*
* Allows the customer to suspend the subscription if the _max_customer_suspensions setting hasn't been reached.
*
* @since 4.0.0
*
* @param bool $can_user_suspend Whether the current user can suspend the subscrption determined by @see wcs_can_user_put_subscription_on_hold().
* @param WC_Subscription $subscription The subscription.
* @param WP_User $user The current user.
*
* @return bool Whether the subscription can be suspended by the user.
*/
public static function can_customer_put_subscription_on_hold( $can_user_suspend, $subscription, $user ) {
// Exit early if the customer can already suspend the subscription.
if ( $can_user_suspend ) {
return $can_user_suspend;
}
// We're only interested in the customer who owns the subscription.
if ( $subscription->get_user_id() !== $user->ID ) {
return $can_user_suspend;
}
// Make sure subscription suspension count hasn't been reached
$suspension_count = intval( $subscription->get_suspension_count() );
$allowed_suspensions = self::get_allowed_customer_suspensions();
if ( 'unlimited' === $allowed_suspensions || $allowed_suspensions > $suspension_count ) { // 0 not > anything so prevents a customer ever being able to suspend
$can_user_suspend = true;
}
return $can_user_suspend;
}
/**
* Adds the customer suspension action, if allowed.
*
* @since 4.0.0
*
* @param array $actions The actions a customer/user can make with a subscription.
* @param WC_Subscription $subscription The subscription.
* @param int $user_id The user viewing the subscription.
*
* @return array The customer's subscription actions.
*/
public static function add_customer_suspension_action( $actions, $subscription, $user_id ) {
if ( ! $subscription->can_be_updated_to( 'on-hold' ) ) {
return $actions;
}
if ( ! user_can( $user_id, 'edit_shop_subscription_status', $subscription->get_id() ) ) {
return $actions;
}
if ( '0' === self::get_allowed_customer_suspensions() ) {
return $actions;
}
if ( current_user_can( 'manage_woocommerce' ) || wcs_can_user_put_subscription_on_hold( $subscription, $user_id ) ) {
$actions['suspend'] = array(
'url' => wcs_get_users_change_status_link( $subscription->get_id(), 'on-hold', $subscription->get_status() ),
'name' => __( 'Suspend', 'woocommerce-subscriptions' ),
);
}
return $actions;
}
/**
* Gets the number of suspensions a customer can make per billing period.
*
* @since 4.0.0
* @return string The number of suspensions a customer can make per billing period. Can 'unlimited' or the number of suspensions allowed.
*/
public static function get_allowed_customer_suspensions() {
return get_option( WC_Subscriptions_Admin::$option_prefix . '_max_customer_suspensions', '0' );
}
}

View File

@@ -0,0 +1,76 @@
<?php
/**
* A class for managing the drip downloads feature.
*
* @package WooCommerce Subscriptions
* @since 4.0.0
*/
defined( 'ABSPATH' ) || exit;
class WCS_Drip_Downloads_Manager {
/**
* Initialise the class.
*
* @since 4.0.0
*/
public static function init() {
add_filter( 'woocommerce_process_product_file_download_paths_grant_access_to_new_file', array( __CLASS__, 'maybe_revoke_immediate_access' ), 10, 4 );
add_filter( 'woocommerce_subscription_settings', array( __CLASS__, 'add_setting' ) );
}
/**
* Checks if the drip downloads feature is enabled.
*
* @since 4.0.0
* @return bool Whether download dripping is enabled or not.
*/
public static function are_drip_downloads_enabled() {
return 'yes' === get_option( WC_Subscriptions_Admin::$option_prefix . '_drip_downloadable_content_on_renewal', 'no' );
}
/**
* Prevent granting download permissions to subscriptions and related-orders when new files are added to a product.
*
* @since 4.0.0
*
* @param bool $grant_access Whether to grant access to the file/download ID.
* @param string $download_id The ID of the download being added.
* @param int $product_id The ID of the downloadable product.
* @param WC_Order $order The order/subscription's ID.
*
* @return bool Whether to grant access to the file/download ID.
*/
public static function maybe_revoke_immediate_access( $grant_access, $download_id, $product_id, $order ) {
if ( self::are_drip_downloads_enabled() && ( wcs_is_subscription( $order->get_id() ) || wcs_order_contains_subscription( $order, 'any' ) ) ) {
$grant_access = false;
}
return $grant_access;
}
/**
* Adds the Drip Downloadable Content setting.
*
* @since 4.0.0
*
* @param array $settings The WC Subscriptions settings array.
* @return array Settings.
*/
public static function add_setting( $settings ) {
$setting = array(
'name' => __( 'Drip Downloadable Content', 'woocommerce-subscriptions' ),
'desc' => __( 'Enable dripping for downloadable content on subscription products.', 'woocommerce-subscriptions' ),
'id' => WC_Subscriptions_Admin::$option_prefix . '_drip_downloadable_content_on_renewal',
'default' => 'no',
'type' => 'checkbox',
// translators: %s is a line break.
'desc_tip' => sprintf( __( 'Enabling this grants access to new downloadable files added to a product only after the next renewal is processed.%sBy default, access to new downloadable files added to a product is granted immediately to any customer that has an active subscription with that product.', 'woocommerce-subscriptions' ), '<br />' ),
);
WC_Subscriptions_Admin::insert_setting_after( $settings, WC_Subscriptions_Admin::$option_prefix . '_miscellaneous', $setting );
return $settings;
}
}

View File

@@ -0,0 +1,415 @@
<?php
/**
* A class for managing the limited payment recurring coupon feature.
*
* @package WooCommerce Subscriptions
* @since 4.0.0
*/
defined( 'ABSPATH' ) || exit;
class WCS_Limited_Recurring_Coupon_Manager {
/**
* The meta key used for the number of renewals.
*
* @var string
*/
private static $coupons_renewals = '_wcs_number_payments';
/**
* Initialize the class hooks and callbacks.
*/
public static function init() {
// Add custom coupon fields.
add_action( 'woocommerce_coupon_options', array( __CLASS__, 'add_coupon_fields' ), 10 );
add_action( 'woocommerce_coupon_options_save', array( __CLASS__, 'save_coupon_fields' ), 10 );
// Filter the available payment gateways.
add_filter( 'woocommerce_available_payment_gateways', array( __CLASS__, 'gateways_subscription_amount_changes' ), 20 );
// Check coupons when a subscription is renewed.
add_action( 'woocommerce_subscription_payment_complete', array( __CLASS__, 'check_coupon_usages' ) );
// Add info to the Coupons list table.
add_action( 'manage_shop_coupon_posts_custom_column', array( __CLASS__, 'add_limit_to_list_table' ), 20, 2 );
// Must be hooked later to honour early callbacks choosing to bypass the coupon removal.
add_filter( 'wcs_bypass_coupon_removal', array( __CLASS__, 'maybe_remove_coupons_from_recurring_cart' ), 1000, 5 );
}
/**
* Adds custom fields to the coupon data form.
*
* @since 4.0.0
*/
public static function add_coupon_fields( $id ) {
$coupon = new WC_Coupon( $id );
woocommerce_wp_text_input( array(
'id' => 'wcs_number_payments',
'label' => __( 'Active for x payments', 'woocommerce-subscriptions' ),
'placeholder' => __( 'Unlimited payments', 'woocommerce-subscriptions' ),
'description' => __( 'Coupon will be limited to the given number of payments. It will then be automatically removed from the subscription. "Payments" also includes the initial subscription payment.', 'woocommerce-subscriptions' ),
'desc_tip' => true,
'data_type' => 'decimal',
'value' => $coupon->get_meta( self::$coupons_renewals ),
) );
}
/**
* Saves our custom coupon fields.
*
* @since 4.0.0
* @param int $id The coupon's ID.
*/
public static function save_coupon_fields( $id ) {
// Check the nonce (again).
if ( empty( $_POST['woocommerce_meta_nonce'] ) || ! wp_verify_nonce( $_POST['woocommerce_meta_nonce'], 'woocommerce_save_data' ) ) {
return;
}
$coupon = new WC_Coupon( $id );
$coupon->add_meta_data( self::$coupons_renewals, wc_clean( $_POST['wcs_number_payments'] ), true );
$coupon->save();
}
/**
* Get the number of renewals for a limited coupon.
*
* @since 4.0.0
* @param string $code The coupon code.
* @return false|int False for non-recurring coupons, or the limit number for recurring coupons.
* A value of 0 is for unlimited usage.
*/
public static function get_coupon_limit( $code ) {
if ( wcs_is_woocommerce_pre( '3.2' ) ) {
return false;
}
// Retrieve the coupon data.
$coupon = new WC_Coupon( $code );
$coupon_type = $coupon->get_discount_type();
// If we have a virtual coupon, attempt to get the original coupon.
if ( WC_Subscriptions_Coupon::is_renewal_cart_coupon( $coupon_type ) ) {
$coupon = WC_Subscriptions_Coupon::map_virtual_coupon( $code );
$coupon_type = $coupon->get_discount_type();
}
$limited = $coupon->get_meta( self::$coupons_renewals );
return WC_Subscriptions_Coupon::is_recurring_coupon( $coupon_type ) ? intval( $limited ) : false;
}
/**
* Determines if a given coupon is limited to a certain number of renewals.
*
* @since 4.0.0
*
* @param string $code The coupon code.
* @return bool
*/
public static function coupon_is_limited( $code ) {
return (bool) self::get_coupon_limit( $code );
}
/**
* Determines whether the cart contains a recurring coupon with set number of renewals.
*
* @since 4.0.0
* @return bool Whether the cart contains a limited recurring coupon.
*/
public static function cart_contains_limited_recurring_coupon() {
$has_coupon = false;
$applied_coupons = isset( WC()->cart->applied_coupons ) ? WC()->cart->applied_coupons : array();
foreach ( $applied_coupons as $code ) {
if ( self::coupon_is_limited( $code ) ) {
$has_coupon = true;
break;
}
}
return $has_coupon;
}
/**
* Determines if a given order has a limited use coupon.
*
* @since 4.0.0
* @param WC_Order|WC_Subscription $order
*
* @return bool Whether the order contains a limited recurring coupon.
*/
public static function order_has_limited_recurring_coupon( $order ) {
$has_coupon = false;
foreach ( wcs_get_used_coupon_codes( $order ) as $code ) {
if ( self::coupon_is_limited( $code ) ) {
$has_coupon = true;
break;
}
}
return $has_coupon;
}
/**
* Limits payment gateways to those that support changing subscription amounts.
*
* @since 4.0.0
* @param WC_Payment_Gateway[] $gateways The current available gateways.
* @return WC_Payment_Gateway[]
*/
private static function limit_gateways_subscription_amount_changes( $gateways ) {
foreach ( $gateways as $index => $gateway ) {
if ( $gateway->supports( 'subscriptions' ) && ! $gateway->supports( 'subscription_amount_changes' ) ) {
unset( $gateways[ $index ] );
}
}
return $gateways;
}
/**
* Determines how many subscription renewals the coupon has been applied to and removes coupons which have reached their expiry.
*
* @since 4.0.0
* @param WC_Subscription $subscription The current subscription.
*/
public static function check_coupon_usages( $subscription ) {
// If there aren't any coupons, there's nothing to do.
$coupons = wcs_get_used_coupon_codes( $subscription );
if ( empty( $coupons ) ) {
return;
}
// Set up the coupons we're looking for, and an initial count.
$limited_coupons = array();
foreach ( $coupons as $code ) {
if ( self::coupon_is_limited( $code ) ) {
$limited_coupons[ $code ] = array(
'code' => $code,
'count' => 0,
);
}
}
// Don't continue if we have no limited use coupons.
if ( empty( $limited_coupons ) ) {
return;
}
// Get all related orders, and count the number of uses for each coupon.
$related = $subscription->get_related_orders( 'all' );
/** @var WC_Order $order */
foreach ( $related as $id => $order ) {
// Unpaid orders don't count as usages.
if ( $order->needs_payment() ) {
continue;
}
/*
* If the order has been refunded, treat coupon as unused. We'll consider the order to be
* refunded when there is a non-null refund amount, and the order total equals the refund amount.
*
* The use of == instead of === is deliberate, to account for differences in amount formatting.
*/
$refunded = $order->get_total_refunded();
$total = $order->get_total();
if ( $refunded && $total == $refunded ) {
continue;
}
// If there was nothing discounted, then consider the coupon unused.
if ( ! $order->get_discount_total() ) {
continue;
}
// Check for limited coupons, and add them to the count if the provide a discount.
$used_coupons = $order->get_items( 'coupon' );
/** @var WC_Order_Item_Coupon $used_coupon */
foreach ( $used_coupons as $used_coupon ) {
if ( isset( $limited_coupons[ $used_coupon->get_code() ] ) && $used_coupon->get_discount() ) {
$limited_coupons[ $used_coupon->get_code() ]['count']++;
}
}
}
// Check each coupon to see if it needs to be removed.
foreach ( $limited_coupons as $limited_coupon ) {
if ( self::get_coupon_limit( $limited_coupon['code'] ) <= $limited_coupon['count'] ) {
$subscription->remove_coupon( $limited_coupon['code'] );
$subscription->add_order_note( sprintf(
/* translators: %1$s is the coupon code, %2$d is the number of payment usages */
_n(
'Limited use coupon "%1$s" removed from subscription. It has been used %2$d time.',
'Limited use coupon "%1$s" removed from subscription. It has been used %2$d times.',
$limited_coupon['count'],
'woocommerce-subscriptions'
),
$limited_coupon['code'],
number_format_i18n( $limited_coupon['count'] )
) );
}
}
}
/**
* Add our limited coupon data to the Coupon list table.
*
* @since 4.0.0
*
* @param string $column_name The name of the current column in the table.
* @param int $id The coupon ID.
*/
public static function add_limit_to_list_table( $column_name, $id ) {
if ( 'usage' !== $column_name ) {
return;
}
$limit = self::get_coupon_limit( wc_get_coupon_code_by_id( $id ) );
if ( false === $limit ) {
return;
}
echo '<br>';
if ( $limit ) {
echo esc_html( sprintf(
/* translators: %d refers to the number of payments the coupon can be used for. */
_n( 'Active for %d payment', 'Active for %d payments', $limit, 'woocommerce-subscriptions' ),
number_format_i18n( $limit )
) );
} else {
esc_html_e( 'Active for unlimited payments', 'woocommerce-subscriptions' );
}
}
/**
* Determines if a given recurring cart contains a limited use coupon which when applied to a subscription will reach its usage limit within the subscription's length.
*
* @since 4.0.0
*
* @param WC_Cart $recurring_cart The recurring cart object.
* @return bool
*/
public static function recurring_cart_contains_expiring_coupon( $recurring_cart ) {
$limited_recurring_coupons = array();
if ( isset( $recurring_cart->applied_coupons ) ) {
$limited_recurring_coupons = array_filter( $recurring_cart->applied_coupons, array( __CLASS__, 'coupon_is_limited' ) );
}
// Bail early if there are no limited coupons applied to the recurring cart or if there is no discount provided.
if ( empty( $limited_recurring_coupons ) || ! $recurring_cart->discount_cart ) {
return false;
}
$has_expiring_coupon = false;
$subscription_length = wcs_cart_pluck( $recurring_cart, 'subscription_length' );
$subscription_payments = $subscription_length / wcs_cart_pluck( $recurring_cart, 'subscription_period_interval' );
// Limited recurring coupons will always expire at some point on subscriptions with no length.
if ( empty( $subscription_length ) ) {
$has_expiring_coupon = true;
} else {
foreach ( $limited_recurring_coupons as $code ) {
if ( WC_Subscriptions_Coupon::get_coupon_limit( $code ) < $subscription_payments ) {
$has_expiring_coupon = true;
break;
}
}
}
return $has_expiring_coupon;
}
/**
* Filters the available gateways when there is a recurring coupon.
*
* @since 4.0.0
*
* @param WC_Payment_Gateway[] $gateways The available payment gateways.
* @return WC_Payment_Gateway[] The filtered payment gateways.
*/
public static function gateways_subscription_amount_changes( $gateways ) {
// If there are already no gateways or we're on the order-pay screen, bail early.
if ( empty( $gateways ) || is_wc_endpoint_url( 'order-pay' ) ) {
return $gateways;
}
// See if this is a request to change payment for an existing subscription.
$change_payment = isset( $_GET['change_payment_method'] ) ? wc_clean( $_GET['change_payment_method'] ) : 0;
$has_limited_coupon = false;
if ( $change_payment && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'] ) ) {
$subscription = wcs_get_subscription( $change_payment );
$has_limited_coupon = self::order_has_limited_recurring_coupon( $subscription );
}
// If the cart doesn't have a limited coupon, and a change payment doesn't have a limited coupon, bail early.
if ( ! self::cart_contains_limited_recurring_coupon() && ! $has_limited_coupon ) {
return $gateways;
}
// If we got this far, we should limit the gateways as needed.
$gateways = self::limit_gateways_subscription_amount_changes( $gateways );
// If there are no gateways now, it's because of the coupon. Filter the 'no available payment methods' message.
if ( empty( $gateways ) ) {
add_filter( 'woocommerce_no_available_payment_methods_message', array( __CLASS__, 'no_available_payment_methods_message' ), 20 );
}
return $gateways;
}
/**
* Filter the message for when no payment gateways are available.
*
* @since 4.0.0
*
* @param string $message The current message indicating there are no payment methods available..
* @return string The filtered message indicating there are no payment methods available.
*/
public static function no_available_payment_methods_message() {
return __( 'Sorry, it seems there are no available payment methods which support the recurring coupon you are using. Please contact us if you require assistance or wish to make alternate arrangements.', 'woocommerce-subscriptions' );
}
/**
* Removes limited coupons from the recurring cart if the coupons limit is reached in the initial cart.
*
* @since 4.0.0
*
* @param bool $bypass_default_checks Whether to bypass WC Subscriptions default conditions for removing a coupon.
* @param WC_Coupon $coupon The coupon to check.
* @param string $coupon_type The coupon's type.
* @param string $calculation_type The WC Subscriptions cart calculation mode. Can be 'recurring_total' or 'none'. @see WC_Subscriptions_Cart::get_calculation_type()
*
* @return bool Whether to bypass WC Subscriptions default conditions for removing a coupon.
*/
public static function maybe_remove_coupons_from_recurring_cart( $bypass_default_checks, $coupon, $coupon_type, $calculation_type, $cart ) {
// Bypass this check if a third-party has already opted to bypass default conditions.
if ( $bypass_default_checks ) {
return $bypass_default_checks;
}
if ( 'recurring_total' !== $calculation_type ) {
return $bypass_default_checks;
}
if ( ! WC_Subscriptions_Coupon::is_recurring_coupon( $coupon_type ) ) {
return $bypass_default_checks;
}
// Special handling for a single payment coupon.
if ( 1 === self::get_coupon_limit( $coupon->get_code() ) && 0 < WC()->cart->get_coupon_discount_amount( $coupon->get_code() ) ) {
$cart->remove_coupon( $coupon->get_code() );
}
return $bypass_default_checks;
}
}

View File

@@ -0,0 +1,91 @@
<?php
/**
* A class for managing the manual renewal feature.
*
* @package WooCommerce Subscriptions
* @since 4.0.0
*/
defined( 'ABSPATH' ) || exit;
class WCS_Manual_Renewal_Manager {
/**
* Initalise the class and attach callbacks.
*/
public static function init() {
add_filter( 'woocommerce_subscription_settings', array( __CLASS__, 'add_settings' ), 5 );
}
/**
* Adds the manual renewal settings.
*
* @since 4.0.0
* @param $settings The full subscription settings array.
* @return $settings.
*/
public static function add_settings( $settings ) {
$manual_renewal_settings = array(
array(
'name' => _x( 'Renewals', 'option section heading', 'woocommerce-subscriptions' ),
'type' => 'title',
'desc' => '',
'id' => WC_Subscriptions_Admin::$option_prefix . '_renewal_options',
),
array(
'name' => __( 'Manual Renewal Payments', 'woocommerce-subscriptions' ),
'desc' => __( 'Accept Manual Renewals', 'woocommerce-subscriptions' ),
'id' => WC_Subscriptions_Admin::$option_prefix . '_accept_manual_renewals',
'default' => 'no',
'type' => 'checkbox',
// translators: placeholders are opening and closing link tags
'desc_tip' => sprintf( __( 'With manual renewals, a customer\'s subscription is put on-hold until they login and pay to renew it. %1$sLearn more%2$s.', 'woocommerce-subscriptions' ), '<a href="http://docs.woocommerce.com/document/subscriptions/store-manager-guide/#accept-manual-renewals">', '</a>' ),
'checkboxgroup' => 'start',
'show_if_checked' => 'option',
),
array(
'desc' => __( 'Turn off Automatic Payments', 'woocommerce-subscriptions' ),
'id' => WC_Subscriptions_Admin::$option_prefix . '_turn_off_automatic_payments',
'default' => 'no',
'type' => 'checkbox',
// translators: placeholders are opening and closing link tags
'desc_tip' => sprintf( __( 'If you don\'t want new subscription purchases to automatically charge renewal payments, you can turn off automatic payments. Existing automatic subscriptions will continue to charge customers automatically. %1$sLearn more%2$s.', 'woocommerce-subscriptions' ), '<a href="http://docs.woocommerce.com/document/subscriptions/store-manager-guide/#turn-off-automatic-payments">', '</a>' ),
'checkboxgroup' => 'end',
'show_if_checked' => 'yes',
),
array(
'type' => 'sectionend',
'id' => WC_Subscriptions_Admin::$option_prefix . '_renewal_options',
),
);
if ( ! WC_Subscriptions_Admin::insert_setting_after( $settings, WC_Subscriptions_Admin::$option_prefix . '_role_options', $manual_renewal_settings, 'multiple_settings', 'sectionend' ) ) {
$settings = array_merge( $settings, $manual_renewal_settings );
}
return $settings;
}
/**
* Checks if manual renewals are required - automatic renewals are disabled.
*
* @since 4.0.0
* @return bool Weather manual renewal is required.
*/
public static function is_manual_renewal_required() {
return 'yes' === get_option( WC_Subscriptions_Admin::$option_prefix . '_turn_off_automatic_payments', 'no' );
}
/**
* Checks if manual renewals are enabled.
*
* @since 4.0.0
* @return bool Weather manual renewal is enabled.
*/
public static function is_manual_renewal_enabled() {
return 'yes' === get_option( WC_Subscriptions_Admin::$option_prefix . '_accept_manual_renewals', 'no' );
}
}

View File

@@ -1,99 +0,0 @@
<?php
/**
* WooCommerce Subscriptions staging mode handler.
*
* @package WooCommerce Subscriptions
* @author Prospress
* @since 2.3.0
*/
class WCS_Staging {
/**
* Attach callbacks.
*/
public static function init() {
add_action( 'woocommerce_generated_manual_renewal_order', array( __CLASS__, 'maybe_record_staging_site_renewal' ) );
add_filter( 'woocommerce_register_post_type_subscription', array( __CLASS__, 'maybe_add_menu_badge' ) );
add_action( 'wp_loaded', array( __CLASS__, 'maybe_reset_admin_notice' ) );
add_action( 'woocommerce_admin_order_data_after_billing_address', array( __CLASS__, 'maybe_add_payment_method_note' ) );
}
/**
* Add an order note to a renewal order to record when it was created under staging site conditions.
*
* @param int $renewal_order_id The renewal order ID.
* @since 2.3.0
*/
public static function maybe_record_staging_site_renewal( $renewal_order_id ) {
if ( ! WC_Subscriptions::is_duplicate_site() ) {
return;
}
$renewal_order = wc_get_order( $renewal_order_id );
if ( $renewal_order ) {
$wp_site_url = WC_Subscriptions::get_site_url_from_source( 'current_wp_site' );
$wcs_site_url = WC_Subscriptions::get_site_url_from_source( 'subscriptions_install' );
// translators: 1-2: opening/closing <a> tags - linked to staging site, 3: link to live site.
$message = sprintf( __( 'Payment processing skipped - renewal order created on %1$sstaging site%2$s under staging site lock. Live site is at %3$s', 'woocommerce-subscriptions' ), '<a href="' . $wp_site_url . '">', '</a>', '<a href="' . $wcs_site_url . '">' . $wcs_site_url . '</a>' );
$renewal_order->add_order_note( $message );
}
}
/**
* Add a badge to the Subscriptions submenu when a site is operating under a staging site lock.
*
* @param array $subscription_order_type_data The WC_Subscription register order type data.
* @since 2.3.0
*/
public static function maybe_add_menu_badge( $subscription_order_type_data ) {
if ( isset( $subscription_order_type_data['labels']['menu_name'] ) && WC_Subscriptions::is_duplicate_site() ) {
$subscription_order_type_data['labels']['menu_name'] .= '<span class="update-plugins">' . esc_html__( 'staging', 'woocommerce-subscriptions' ) . '</span>';
}
return $subscription_order_type_data;
}
/**
* Handles admin requests to redisplay the staging site admin notice.
*
* @since 2.5.5
*/
public static function maybe_reset_admin_notice() {
if ( isset( $_REQUEST['wcs_display_staging_notice'] ) && is_admin() && current_user_can( 'manage_options' ) ) {
delete_option( 'wcs_ignore_duplicate_siteurl_notice' );
wp_safe_redirect( remove_query_arg( array( 'wcs_display_staging_notice' ) ) );
}
}
/**
* Displays a note under the edit subscription payment method field to explain why the subscription is set to Manual Renewal.
*
* @param WC_Subscription $subscription
* @since 2.6.0
*/
public static function maybe_add_payment_method_note( $subscription ) {
if ( wcs_is_subscription( $subscription ) && WC_Subscriptions::is_duplicate_site() && $subscription->has_payment_gateway() && ! $subscription->get_requires_manual_renewal() ) {
printf(
'<p>%s</p>',
esc_html__( 'Subscription locked to Manual Renewal while the store is in staging mode. Payment method changes will take effect in live mode.', 'woocommerce-subscriptions' )
);
}
}
/**
* Returns the content for a tooltip explaining a subscription's payment method while in staging mode.
*
* @param WC_Subscription $subscription
* @return string HTML content for a tooltip.
* @since 2.6.0
*/
public static function get_payment_method_tooltip( $subscription ) {
// translators: placeholder is a payment method title.
return '<div class="woocommerce-help-tip" data-tip="' . sprintf( esc_attr__( 'Subscription locked to Manual Renewal while the store is in staging mode. Live payment method: %s', 'woocommerce-subscriptions' ), $subscription->get_payment_method_title() ) . '"></div>';
}
}

View File

@@ -0,0 +1,98 @@
<?php
/**
* A class for managing custom active and inactive subscriber roles via a setting.
*
* @package WooCommerce Subscriptions
* @since 4.0.0
*/
defined( 'ABSPATH' ) || exit;
class WCS_Subscriber_Role_Manager {
/**
* Initialise the class.
*/
public static function init() {
add_filter( 'woocommerce_subscription_settings', array( __CLASS__, 'add_settings' ), 20 );
}
/**
* Adds the subscription customer role setting.
*
* @since 4.0.0
*
* @param array $settings Subscriptions settings.
* @return array Subscriptions settings.
*/
public static function add_settings( $settings ) {
if ( ! function_exists( 'get_editable_roles' ) ) {
require_once( ABSPATH . 'wp-admin/includes/user.php' );
}
foreach ( get_editable_roles() as $role => $details ) {
$roles_options[ $role ] = translate_user_role( $details['name'] );
}
$role_settings = array(
array(
'name' => __( 'Roles', 'woocommerce-subscriptions' ),
'type' => 'title',
// translators: placeholders are <em> tags
'desc' => sprintf( __( 'Choose the default roles to assign to active and inactive subscribers. For record keeping purposes, a user account must be created for subscribers. Users with the %1$sadministrator%2$s role, such as yourself, will never be allocated these roles to prevent locking out administrators.', 'woocommerce-subscriptions' ), '<em>', '</em>' ),
'id' => WC_Subscriptions_Admin::$option_prefix . '_role_options',
),
array(
'name' => __( 'Subscriber Default Role', 'woocommerce-subscriptions' ),
'desc' => __( 'When a subscription is activated, either manually or after a successful purchase, new users will be assigned this role.', 'woocommerce-subscriptions' ),
'tip' => '',
'id' => WC_Subscriptions_Admin::$option_prefix . '_subscriber_role',
'css' => 'min-width:150px;',
'default' => 'subscriber',
'type' => 'select',
'options' => $roles_options,
'desc_tip' => true,
),
array(
'name' => __( 'Inactive Subscriber Role', 'woocommerce-subscriptions' ),
'desc' => __( 'If a subscriber\'s subscription is manually cancelled or expires, she will be assigned this role.', 'woocommerce-subscriptions' ),
'tip' => '',
'id' => WC_Subscriptions_Admin::$option_prefix . '_cancelled_role',
'css' => 'min-width:150px;',
'default' => 'customer',
'type' => 'select',
'options' => $roles_options,
'desc_tip' => true,
),
array(
'type' => 'sectionend',
'id' => WC_Subscriptions_Admin::$option_prefix . '_role_options',
),
);
WC_Subscriptions_Admin::insert_setting_after( $settings, WC_Subscriptions_Admin::$option_prefix . '_button_text', $role_settings, 'multiple_settings', 'sectionend' );
return $settings;
}
/**
* Gets the subscriber role.
*
* @since 4.0.0
*
* @return string The role to apply to subscribers.
*/
public static function get_subscriber_role() {
return get_option( WC_Subscriptions_Admin::$option_prefix . '_subscriber_role', 'subscriber' );
}
/**
* Gets the inactive subscriber role.
*
* @since 4.0.0
*
* @return string The role to apply to inactive subscribers.
*/
public static function get_inactive_subscriber_role() {
return get_option( WC_Subscriptions_Admin::$option_prefix . '_cancelled_role', 'customer' );
}
}

View File

@@ -1,117 +0,0 @@
<?php
/**
* WC Subscriptions Template Loader
*
* @version 2.0
* @author Prospress
*/
class WCS_Template_Loader {
public static function init() {
add_action( 'woocommerce_account_view-subscription_endpoint', array( __CLASS__, 'get_view_subscription_template' ) );
add_action( 'woocommerce_subscription_details_table', array( __CLASS__, 'get_subscription_details_template' ) );
add_action( 'woocommerce_subscription_totals_table', array( __CLASS__, 'get_subscription_totals_template' ) );
add_action( 'woocommerce_subscription_totals_table', array( __CLASS__, 'get_order_downloads_template' ), 20 );
add_action( 'woocommerce_subscription_totals', array( __CLASS__, 'get_subscription_totals_table_template' ), 10, 4 );
}
/**
* Get the view subscription template.
*
* @param int $subscription_id Subscription ID.
* @since 2.0.17
*/
public static function get_view_subscription_template( $subscription_id ) {
$subscription = wcs_get_subscription( absint( $subscription_id ) );
if ( ! $subscription || ! current_user_can( 'view_order', $subscription->get_id() ) ) {
echo '<div class="woocommerce-error">' . esc_html__( 'Invalid Subscription.', 'woocommerce-subscriptions' ) . ' <a href="' . esc_url( wc_get_page_permalink( 'myaccount' ) ) . '" class="wc-forward">' . esc_html__( 'My Account', 'woocommerce-subscriptions' ) . '</a>' . '</div>';
return;
}
wc_get_template( 'myaccount/view-subscription.php', compact( 'subscription' ), '', plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'templates/' );
}
/**
* Get the subscription details template, which is part of the view subscription page.
*
* @param WC_Subscription $subscription Subscription object
* @since 2.2.19
*/
public static function get_subscription_details_template( $subscription ) {
wc_get_template( 'myaccount/subscription-details.php', array( 'subscription' => $subscription ), '', plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'templates/' );
}
/**
* Get the subscription totals template, which is part of the view subscription page.
*
* @param WC_Subscription $subscription Subscription object
* @since 2.2.19
*/
public static function get_subscription_totals_template( $subscription ) {
wc_get_template( 'myaccount/subscription-totals.php', array( 'subscription' => $subscription ), '', plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'templates/' );
}
/**
* Get the order downloads template, which is part of the view subscription page.
*
* @param WC_Subscription $subscription Subscription object
* @since 2.5.0
*/
public static function get_order_downloads_template( $subscription ) {
if ( $subscription->has_downloadable_item() && $subscription->is_download_permitted() ) {
wc_get_template(
'order/order-downloads.php',
array(
'downloads' => $subscription->get_downloadable_items(),
'show_title' => true,
)
);
}
}
/**
* Gets the subscription totals table.
*
* @since 2.6.0
*
* @param WC_Subscription $subscription The subscription to print the totals table for.
* @param bool $include_item_removal_links Whether the remove line item links should be included.
* @param array $totals The subscription totals rows to be displayed.
* @param bool $include_switch_links Whether the line item switch links should be included.
*/
public static function get_subscription_totals_table_template( $subscription, $include_item_removal_links, $totals, $include_switch_links = true ) {
// If the switch links shouldn't be printed, remove the callback which prints them.
if ( false === $include_switch_links ) {
$callback_detached = remove_action( 'woocommerce_order_item_meta_end', 'WC_Subscriptions_Switcher::print_switch_link' );
}
wc_get_template(
'myaccount/subscription-totals-table.php',
array(
'subscription' => $subscription,
'allow_item_removal' => $include_item_removal_links,
'totals' => $totals,
),
'',
plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'templates/'
);
// Reattach the callback if it was successfully removed.
if ( false === $include_switch_links && $callback_detached ) {
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

@@ -19,7 +19,7 @@ class WCS_Upgrade_Notice_Manager {
* *
* @var string * @var string
*/ */
protected static $version = '3.0.0'; protected static $version = '3.1.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,34 +77,40 @@ class WCS_Upgrade_Notice_Manager {
return; return;
} }
$version = _x( '3.0', 'plugin version number used in admin notice', 'woocommerce-subscriptions' ); $version = _x( '3.1', '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 scheduled action data storage', 'woocommerce-subscriptions' ), 'title' => __( 'v3 REST API endpoint support', 'woocommerce-subscriptions' ),
'description' => __( 'Scheduled action data, which was previously stored in the WordPress post tables, has been moved to a custom database table. Amongst other benefits, this will greatly improve the performance of processing scheduled actions such as subscription payments.', 'woocommerce-subscriptions' ), 'description' => sprintf(
// translators: 1-3: opening/closing <a> tags - link to documentation.
__( 'Webhook and REST API users can now use v3 subscription endpoints. Click here to %1$slearn more%2$s about the REST API and check out the technical API docs %3$shere%2$s.', 'woocommerce-subscriptions' ),
'<a href="https://docs.woocommerce.com/document/woocommerce-rest-api/">',
'</a>',
'<a href="https://woocommerce.github.io/subscriptions-rest-api-docs/">'
),
), ),
array( array(
'title' => __( 'Increased processing rate for scheduled payments', 'woocommerce-subscriptions' ), 'title' => __( 'WooCommerce checkout and cart blocks integration', 'woocommerce-subscriptions' ),
'description' => sprintf( 'description' => sprintf(
// translators: 1-2: opening/closing <a> tags - link to documentation. // translators: 1-2: opening/closing <a> tags - link to documentation.
__( 'Previous versions of Subscriptions relied on %1$sWP Cron%2$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' ), __( 'Subscriptions is now compatible with the WooCommerce cart and checkout blocks. You can learn more about the compatibility status of the cart & checkout blocks %1$shere%2$s.', 'woocommerce-subscriptions' ),
'<a href="https://docs.woocommerce.com/document/subscriptions/develop/complete-guide-to-scheduled-events-with-subscriptions/#section-2">', '</a>' '<a href="https://docs.woocommerce.com/document/cart-checkout-blocks-support-status/">', '</a>'
), ),
), ),
); );
// translators: placeholder is Subscription version string ('2.3') // translators: placeholder is Subscription version string ('3.1')
$notice->set_heading( sprintf( __( 'Welcome to WooCommerce Subscriptions %s!', 'woocommerce-subscriptions' ), $version ) ); $notice->set_heading( sprintf( __( 'Welcome to WooCommerce Subscriptions %s!', 'woocommerce-subscriptions' ), $version ) );
$notice->set_content_template( 'update-welcome-notice.php', plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'includes/upgrades/templates/', array( $notice->set_content_template( 'update-welcome-notice.php', WC_Subscriptions_Core_Plugin::instance()->get_subscriptions_core_directory() . '/includes/upgrades/templates/', array(
'version' => $version, 'version' => $version,
'features' => $features, 'features' => $features,
) ); ) );
$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-3-0/', 'url' => 'https://docs.woocommerce.com/document/subscriptions/whats-new-in-subscriptions-3-1/',
), ),
) ); ) );

View File

@@ -107,10 +107,10 @@ class WCS_Webhooks {
public static function add_topics_admin_menu( $topics ) { public static function add_topics_admin_menu( $topics ) {
$front_end_topics = array( $front_end_topics = array(
'subscription.created' => __( ' Subscription Created', 'woocommerce-subscriptions' ), 'subscription.created' => __( ' Subscription created', 'woocommerce-subscriptions' ),
'subscription.updated' => __( ' Subscription Updated', 'woocommerce-subscriptions' ), 'subscription.updated' => __( ' Subscription updated', 'woocommerce-subscriptions' ),
'subscription.deleted' => __( ' Subscription Deleted', 'woocommerce-subscriptions' ), 'subscription.deleted' => __( ' Subscription deleted', 'woocommerce-subscriptions' ),
'subscription.switched' => __( ' Subscription Switched', 'woocommerce-subscriptions' ), 'subscription.switched' => __( ' Subscription switched', 'woocommerce-subscriptions' ),
); );
return array_merge( $topics, $front_end_topics ); return array_merge( $topics, $front_end_topics );
@@ -125,27 +125,28 @@ class WCS_Webhooks {
if ( 'subscription' == $resource && empty( $payload ) && wcs_is_subscription( $resource_id ) ) { if ( 'subscription' == $resource && empty( $payload ) && wcs_is_subscription( $resource_id ) ) {
$webhook = new WC_Webhook( $id ); $webhook = new WC_Webhook( $id );
$event = $webhook->get_event();
$current_user = get_current_user_id(); $current_user = get_current_user_id();
wp_set_current_user( $webhook->get_user_id() ); wp_set_current_user( $webhook->get_user_id() );
$webhook_api_version = ( method_exists( $webhook, 'get_api_version' ) ) ? $webhook->get_api_version() : 'legacy_v3'; switch ( $webhook->get_api_version() ) {
switch ( $webhook_api_version ) {
case 'legacy_v3': case 'legacy_v3':
WC()->api->WC_API_Subscriptions->register_routes( array() ); WC()->api->WC_API_Subscriptions->register_routes( array() );
$payload = WC()->api->WC_API_Subscriptions->get_subscription( $resource_id ); $payload = WC()->api->WC_API_Subscriptions->get_subscription( $resource_id );
break; break;
case 'wp_api_v1': case 'wp_api_v1':
case 'wp_api_v2': case 'wp_api_v2':
case 'wp_api_v3': // There is no v2 subscritpion endpoint support so they fall back to v1.
$request = new WP_REST_Request( 'GET' ); $request = new WP_REST_Request( 'GET' );
$controller = new WC_REST_Subscriptions_Controller; $controller = new WC_REST_Subscriptions_v1_Controller();
$request->set_param( 'id', $resource_id ); $request->set_param( 'id', $resource_id );
$result = $controller->get_item( $request ); $result = $controller->get_item( $request );
$payload = isset( $result->data ) ? $result->data : array(); $payload = isset( $result->data ) ? $result->data : array();
break;
case 'wp_api_v3':
$payload = wc()->api->get_endpoint_data( "/wc/v3/subscriptions/{$resource_id}" );
break; break;
} }

View File

@@ -0,0 +1,85 @@
<?php
/**
* A class for managing the zero initial payment feature requiring payment.
*
* @package WooCommerce Subscriptions
* @since 4.0.0
*/
defined( 'ABSPATH' ) || exit;
class WCS_Zero_Initial_Payment_Checkout_Manager {
/**
* Initialise the class.
*/
public static function init() {
add_filter( 'woocommerce_subscription_settings', array( __CLASS__, 'add_settings' ) );
add_filter( 'woocommerce_cart_needs_payment', array( __CLASS__, 'cart_needs_payment' ), 5 );
add_filter( 'woocommerce_order_needs_payment', array( __CLASS__, 'order_needs_payment' ), 5 );
}
/**
* Adds the $0 initial checkout setting.
*
* @since 4.0.0
* @return array WC Subscriptions settings.
*/
public static function add_settings( $settings ) {
$setting = array(
'name' => __( '$0 Initial Checkout', 'woocommerce-subscriptions' ),
'desc' => __( 'Allow $0 initial checkout without a payment method.', 'woocommerce-subscriptions' ),
'id' => WC_Subscriptions_Admin::$option_prefix . '_zero_initial_payment_requires_payment',
'default' => 'no',
'type' => 'checkbox',
'desc_tip' => __( 'Allow a subscription product with a $0 initial payment to be purchased without providing a payment method. The customer will be required to provide a payment method at the end of the initial period to keep the subscription active.', 'woocommerce-subscriptions' ),
);
WC_Subscriptions_Admin::insert_setting_after( $settings, WC_Subscriptions_Admin::$option_prefix . '_miscellaneous', $setting );
return $settings;
}
/**
* Checks if a $0 checkout requires a payment method.
*
* @since 4.0.0
* @return bool Whether a $0 initial checkout requires a payment method.
*/
public static function zero_initial_checkout_requires_payment() {
return 'yes' !== get_option( WC_Subscriptions_Admin::$option_prefix . '_zero_initial_payment_requires_payment', 'no' );
}
/**
* Unhooks core Subscriptions functionality that requires payment on checkout for $0 subscription purchases,
* if the store has opted to bypass that via this feature.
*
* @since 4.0.0
*
* @param bool $cart_needs_payment Whether the cart requires payment.
* @return bool
*/
public static function cart_needs_payment( $cart_needs_payment ) {
if ( ! self::zero_initial_checkout_requires_payment() ) {
remove_filter( 'woocommerce_cart_needs_payment', 'WC_Subscriptions_Cart::cart_needs_payment', 10, 2 );
}
return $cart_needs_payment;
}
/**
* Unhooks core Subscriptions functionality that requires payment for a $0 subscription order,
* if the store has opted to bypass that via this feature.
*
* @since 4.0.0
*
* @param bool $needs_payment
* @return bool
*/
public static function order_needs_payment( $needs_payment ) {
if ( ! self::zero_initial_checkout_requires_payment() ) {
remove_filter( 'woocommerce_order_needs_payment', 'WC_Subscriptions_Order::order_needs_payment', 10, 3 );
}
return $needs_payment;
}
}

View File

@@ -27,10 +27,19 @@ class WCS_Cart_Early_Renewal extends WCS_Cart_Renewal {
add_action( 'woocommerce_checkout_create_order', array( $this, 'copy_subscription_meta_to_order' ), 90 ); add_action( 'woocommerce_checkout_create_order', array( $this, 'copy_subscription_meta_to_order' ), 90 );
// Record early renewal payments. // Record early renewal payments.
if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) { if ( wcs_is_woocommerce_pre( '3.0' ) ) {
add_action( 'woocommerce_checkout_order_processed', array( $this, 'maybe_record_early_renewal' ), 100, 2 ); add_action( 'woocommerce_checkout_order_processed', array( $this, 'maybe_record_early_renewal' ), 100, 2 );
} else { } else {
add_action( 'woocommerce_checkout_create_order', array( $this, 'add_early_renewal_metadata_to_order' ), 100, 2 ); add_action( 'woocommerce_checkout_create_order', array( $this, 'add_early_renewal_metadata_to_order' ), 100, 2 );
if ( class_exists( 'Automattic\WooCommerce\Blocks\Package' ) ) {
if ( version_compare( \Automattic\WooCommerce\Blocks\Package::get_version(), '7.2.0', '>=' ) ) {
add_action( 'woocommerce_store_api_checkout_update_order_meta', array( $this, 'add_early_renewal_metadata_to_order' ), 100, 1 );
} elseif ( version_compare( \Automattic\WooCommerce\Blocks\Package::get_version(), '6.3.0', '>=' ) ) {
add_action( 'woocommerce_blocks_checkout_update_order_meta', array( $this, 'add_early_renewal_metadata_to_order' ), 100, 1 );
} else {
add_action( '__experimental_woocommerce_blocks_checkout_update_order_meta', array( $this, 'add_early_renewal_metadata_to_order' ), 100, 1 );
}
}
} }
// Process early renewal by making sure subscription's dates are updated. // Process early renewal by making sure subscription's dates are updated.
@@ -127,7 +136,7 @@ class WCS_Cart_Early_Renewal extends WCS_Cart_Renewal {
* @since 2.3.0 * @since 2.3.0
*/ */
public function maybe_record_early_renewal( $order_id, $posted_data ) { public function maybe_record_early_renewal( $order_id, $posted_data ) {
if ( ! WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) { if ( ! wcs_is_woocommerce_pre( '3.0' ) ) {
wcs_deprecated_function( __METHOD__, '2.0', 'WCS_Cart_Early_Renewal::add_early_renewal_metadata_to_order( $order, $posted_data )' ); wcs_deprecated_function( __METHOD__, '2.0', 'WCS_Cart_Early_Renewal::add_early_renewal_metadata_to_order( $order, $posted_data )' );
} }
@@ -178,7 +187,7 @@ class WCS_Cart_Early_Renewal extends WCS_Cart_Renewal {
* @param array $data The data posted on checkout. * @param array $data The data posted on checkout.
* @since 2.3.0 * @since 2.3.0
*/ */
public function add_early_renewal_metadata_to_order( $order, $data ) { public function add_early_renewal_metadata_to_order( $order, $data = array() ) {
$cart_item = $this->cart_contains(); $cart_item = $this->cart_contains();
if ( ! $cart_item ) { if ( ! $cart_item ) {

View File

@@ -45,6 +45,7 @@ class WCS_Early_Renewal_Modal_Handler {
'process_early_renewal' => true, 'process_early_renewal' => true,
'wcs_nonce' => wp_create_nonce( 'wcs-renew-early-modal-' . $subscription->get_id() ), 'wcs_nonce' => wp_create_nonce( 'wcs-renew-early-modal-' . $subscription->get_id() ),
) ), ) ),
'data-payment-method' => $subscription->get_payment_method(),
), ),
); );
@@ -88,7 +89,7 @@ class WCS_Early_Renewal_Modal_Handler {
'new_next_payment_date' => $new_next_payment_date, 'new_next_payment_date' => $new_next_payment_date,
), ),
'', '',
plugin_dir_path( WC_Subscriptions::$plugin_file ) . '/templates/' WC_Subscriptions_Plugin::instance()->get_plugin_directory( 'templates/' )
); );
} }
@@ -146,6 +147,9 @@ class WCS_Early_Renewal_Modal_Handler {
wp_redirect( wcs_get_early_renewal_url( $subscription ) ); wp_redirect( wcs_get_early_renewal_url( $subscription ) );
exit(); exit();
} else { } else {
// Trigger the subscription payment complete hooks and reset suspension counts and user roles.
$subscription->payment_complete();
wcs_update_dates_after_early_renewal( $subscription, $renewal_order ); wcs_update_dates_after_early_renewal( $subscription, $renewal_order );
wc_add_notice( __( 'Your early renewal order was successful.', 'woocommerce-subscriptions' ), 'success' ); wc_add_notice( __( 'Your early renewal order was successful.', 'woocommerce-subscriptions' ), 'success' );
} }

View File

@@ -95,32 +95,6 @@ function wcs_can_user_renew_early( $subscription, $user_id = 0 ) {
return apply_filters( 'woocommerce_subscriptions_can_user_renew_early', $can_renew_early, $subscription, $user_id, $reason ); return apply_filters( 'woocommerce_subscriptions_can_user_renew_early', $can_renew_early, $subscription, $user_id, $reason );
} }
/**
* Check if a given order is a subscription renewal order.
*
* @param WC_Order|int $order The WC_Order object or ID of a WC_Order order.
* @since 2.3.0
* @return bool True if the order contains an early renewal, otherwise false.
*/
function wcs_order_contains_early_renewal( $order ) {
if ( ! is_object( $order ) ) {
$order = wc_get_order( $order );
}
$subscription_id = absint( wcs_get_objects_property( $order, 'subscription_renewal_early' ) );
$is_early_renewal = wcs_is_order( $order ) && $subscription_id > 0;
/**
* Allow third-parties to filter whether this order contains the early renewal flag.
*
* @since 2.3.0
* @param bool $is_renewal True if early renewal meta was found on the order, otherwise false.
* @param WC_Order $order The WC_Order object.
*/
return apply_filters( 'woocommerce_subscriptions_is_early_renewal_order', $is_early_renewal, $order );
}
/** /**
* Returns a URL for early renewal of a subscription. * Returns a URL for early renewal of a subscription.
* *

View File

@@ -10,67 +10,27 @@
* @author Brent Shepherd * @author Brent Shepherd
* @since 1.0 * @since 1.0
*/ */
class WC_Subscriptions_Payment_Gateways { class WC_Subscriptions_Payment_Gateways extends WC_Subscriptions_Core_Payment_Gateways {
protected static $one_gateway_supports = array();
/** /**
* Bootstraps the class and hooks required actions & filters. * Init WC_Subscriptions_Payment_Gateways actions & filters.
* *
* @since 1.0 * @since 4.0.0
*/ */
public static function init() { public static function init() {
parent::init();
add_action( 'init', __CLASS__ . '::init_paypal', 5 ); // run before default priority 10 in case the site is using ALTERNATE_WP_CRON to avoid https://core.trac.wordpress.org/ticket/24160.
add_filter( 'woocommerce_available_payment_gateways', __CLASS__ . '::get_available_payment_gateways' );
add_filter( 'woocommerce_no_available_payment_methods_message', __CLASS__ . '::no_available_payment_methods_message' );
add_filter( 'woocommerce_payment_gateways_renewal_support_status_html', __CLASS__ . '::payment_gateways_support_tooltip', 11, 2 );
// Trigger a hook for gateways to charge recurring payments. // Trigger a hook for gateways to charge recurring payments.
add_action( 'woocommerce_scheduled_subscription_payment', __CLASS__ . '::gateway_scheduled_subscription_payment', 10, 1 ); add_action( 'woocommerce_scheduled_subscription_payment', array( __CLASS__, 'gateway_scheduled_subscription_payment' ), 10, 1 );
// Create a gateway specific hooks for subscription events. add_filter( 'woocommerce_subscriptions_admin_recurring_payment_information', array( __CLASS__, 'add_recurring_payment_gateway_information' ), 10, 2 );
add_action( 'woocommerce_subscription_status_updated', __CLASS__ . '::trigger_gateway_status_updated_hook', 10, 2 );
} }
/** /**
* Instantiate our custom PayPal class * Display the gateways which support subscriptions if manual payments are not allowed.
*
* @since 2.0
*/
public static function init_paypal() {
WCS_PayPal::init();
}
/**
* Returns a payment gateway object by gateway's ID, or false if it could not find the gateway.
*
* @since 1.2.4
*/
public static function get_payment_gateway( $gateway_id ) {
$found_gateway = false;
if ( WC()->payment_gateways ) {
foreach ( WC()->payment_gateways->payment_gateways() as $gateway ) {
if ( $gateway_id == $gateway->id ) {
$found_gateway = $gateway;
}
}
}
return $found_gateway;
}
/**
* Only display the gateways which support subscriptions if manual payments are not allowed.
* *
* @since 1.0 * @since 1.0
*/ */
public static function get_available_payment_gateways( $available_gateways ) { public static function get_available_payment_gateways( $available_gateways ) {
// We don't want to filter the available payment methods while the customer is paying for a standard order via the order-pay screen. // We don't want to filter the available payment methods while the customer is paying for a standard order via the order-pay screen.
if ( is_wc_endpoint_url( 'order-pay' ) ) { if ( is_wc_endpoint_url( 'order-pay' ) ) {
return $available_gateways; return $available_gateways;
@@ -80,7 +40,7 @@ class WC_Subscriptions_Payment_Gateways {
return $available_gateways; return $available_gateways;
} }
$accept_manual_renewals = ( 'no' !== get_option( WC_Subscriptions_Admin::$option_prefix . '_accept_manual_renewals', 'no' ) ); $accept_manual_renewals = wcs_is_manual_renewal_enabled();
$subscriptions_in_cart = is_array( WC()->cart->recurring_carts ) ? count( WC()->cart->recurring_carts ) : 0; $subscriptions_in_cart = is_array( WC()->cart->recurring_carts ) ? count( WC()->cart->recurring_carts ) : 0;
foreach ( $available_gateways as $gateway_id => $gateway ) { foreach ( $available_gateways as $gateway_id => $gateway ) {
@@ -101,79 +61,25 @@ class WC_Subscriptions_Payment_Gateways {
} }
/** /**
* Helper function to check if at least one payment gateway on the site supports a certain subscription feature. * Fire a gateway specific hook for when a subscription payment is due.
* *
* @since 2.0 * @since 1.0
*/ */
public static function one_gateway_supports( $supports_flag ) { public static function gateway_scheduled_subscription_payment( $subscription_id, $deprecated = null ) {
if ( ! is_object( $subscription_id ) ) {
// Only check if we haven't already run the check $subscription = wcs_get_subscription( $subscription_id );
if ( ! isset( self::$one_gateway_supports[ $supports_flag ] ) ) {
self::$one_gateway_supports[ $supports_flag ] = false;
foreach ( WC()->payment_gateways->get_available_payment_gateways() as $gateway ) {
if ( $gateway->supports( $supports_flag ) ) {
self::$one_gateway_supports[ $supports_flag ] = true;
break;
}
}
}
return self::$one_gateway_supports[ $supports_flag ];
}
/**
* Improve message displayed on checkout when a subscription is in the cart but not gateways support subscriptions.
*
* @since 1.5.2
*/
public static function no_available_payment_methods_message( $no_gateways_message ) {
if ( WC_Subscriptions_Cart::cart_contains_subscription() && 'no' == get_option( WC_Subscriptions_Admin::$option_prefix . '_accept_manual_renewals', 'no' ) ) {
if ( current_user_can( 'manage_woocommerce' ) ) {
// translators: 1-2: opening/closing tags - link to documentation.
$no_gateways_message = sprintf( __( 'Sorry, it seems there are no available payment methods which support subscriptions. Please see %1$sEnabling Payment Gateways for Subscriptions%2$s if you require assistance.', 'woocommerce-subscriptions' ), '<a href="https://docs.woocommerce.com/document/subscriptions/enabling-payment-gateways-for-subscriptions/">', '</a>' );
} else { } else {
$no_gateways_message = __( 'Sorry, it seems there are no available payment methods which support subscriptions. Please contact us if you require assistance or wish to make alternate arrangements.', 'woocommerce-subscriptions' ); $subscription = $subscription_id;
}
} }
return $no_gateways_message; if ( false === $subscription ) {
// translators: %d: subscription ID.
throw new InvalidArgumentException( sprintf( __( 'Subscription doesn\'t exist in scheduled action: %d', 'woocommerce-subscriptions' ), $subscription_id ) );
} }
/** if ( ! $subscription->is_manual() && ! $subscription->has_status( wcs_get_subscription_ended_statuses() ) ) {
* Fire a gateway specific whenever a subscription's status is changed. self::trigger_gateway_renewal_payment_hook( $subscription->get_last_order( 'all', 'renewal' ) );
*
* @since 2.0
*/
public static function trigger_gateway_status_updated_hook( $subscription, $new_status ) {
if ( $subscription->is_manual() ) {
return;
} }
switch ( $new_status ) {
case 'active':
$hook_prefix = 'woocommerce_subscription_activated_';
break;
case 'on-hold':
$hook_prefix = 'woocommerce_subscription_on-hold_';
break;
case 'pending-cancel':
$hook_prefix = 'woocommerce_subscription_pending-cancel_';
break;
case 'cancelled':
$hook_prefix = 'woocommerce_subscription_cancelled_';
break;
case 'expired':
$hook_prefix = 'woocommerce_subscription_expired_';
break;
default:
$hook_prefix = apply_filters( 'woocommerce_subscriptions_gateway_status_updated_hook_prefix', 'woocommerce_subscription_status_updated_', $subscription, $new_status );
break;
}
do_action( $hook_prefix . $subscription->get_payment_method(), $subscription );
} }
/** /**
@@ -193,147 +99,37 @@ class WC_Subscriptions_Payment_Gateways {
} }
/** /**
* Fire a gateway specific hook for when a subscription payment is due. * Returns whether the subscription payment gateway has an available gateway.
* *
* @since 1.0 * @since 4.0.0
* @param WC_Subscription $subscription Subscription to check if the gateway is available.
* @return bool
*/ */
public static function gateway_scheduled_subscription_payment( $subscription_id, $deprecated = null ) { public static function has_available_payment_method( $subscription ) {
return wc_get_payment_gateway_by_order( $subscription ) ? true : false;
// Passing the old $user_id/$subscription_key parameters
if ( null != $deprecated ) {
_deprecated_argument( __METHOD__, '2.0', 'Second parameter is deprecated' );
$subscription = wcs_get_subscription_from_key( $deprecated );
} elseif ( ! is_object( $subscription_id ) ) {
$subscription = wcs_get_subscription( $subscription_id );
} else {
// Support receiving a full subscription object for unit testing
$subscription = $subscription_id;
}
if ( false === $subscription ) {
// translators: %d: subscription ID.
throw new InvalidArgumentException( sprintf( __( 'Subscription doesn\'t exist in scheduled action: %d', 'woocommerce-subscriptions' ), $subscription_id ) );
}
if ( ! $subscription->is_manual() && ! $subscription->has_status( wcs_get_subscription_ended_statuses() ) ) {
self::trigger_gateway_renewal_payment_hook( $subscription->get_last_order( 'all', 'renewal' ) );
}
} }
/** /**
* Display a list of each gateway supported features in a tooltip * Returns whether the gateway supports subscriptions and automatic renewals.
* *
* @since 2.5.0 * @since 4.0.0
* @param WC_Gateway $gateway Gateway to check if it supports subscriptions.
* @return bool
*/ */
public static function payment_gateways_support_tooltip( $status_html, $gateway ) { public static function gateway_supports_subscriptions( $gateway ) {
return ( is_array( $gateway->supports ) && in_array( 'subscriptions', $gateway->supports, true ) ) || 'paypal' === $gateway->id;
if ( ( ! is_array( $gateway->supports ) || ! in_array( 'subscriptions', $gateway->supports ) ) && 'paypal' !== $gateway->id ) {
return $status_html;
}
$core_features = (array) apply_filters( 'woocommerce_subscriptions_payment_gateway_features_list', $gateway->supports, $gateway );
$subscription_features = $change_payment_method_features = array();
foreach ( $core_features as $key => $feature ) {
// Skip any non-subscription related features.
if ( 'gateway_scheduled_payments' !== $feature && false === strpos( $feature, 'subscription' ) ) {
continue;
}
$feature = str_replace( 'subscription_', '', $feature );
if ( 0 === strpos( $feature, 'payment_method' ) ) {
switch ( $feature ) {
case 'payment_method_change':
$change_payment_method_features[] = 'payment method change';
break;
case 'payment_method_change_customer':
$change_payment_method_features[] = 'customer change payment';
break;
case 'payment_method_change_admin':
$change_payment_method_features[] = 'admin change payment';
break;
default:
$change_payment_method_features[] = str_replace( 'payment_method', ' ', $feature );
break;
}
} else {
$subscription_features[] = $feature;
}
unset( $core_features[ $key ] );
}
$status_html .= '<span class="payment-method-features-info tips" data-tip="';
$status_html .= esc_attr( '<strong><u>' . __( 'Supported features:', 'woocommerce-subscriptions' ) . '</u></strong></br>' . implode( '<br />', str_replace( '_', ' ', $core_features ) ) );
if ( ! empty( $subscription_features ) ) {
$status_html .= esc_attr( '</br><strong><u>' . __( 'Subscription features:', 'woocommerce-subscriptions' ) . '</u></strong></br>' . implode( '<br />', str_replace( '_', ' ', $subscription_features ) ) );
}
if ( ! empty( $change_payment_method_features ) ) {
$status_html .= esc_attr( '</br><strong><u>' . __( 'Change payment features:', 'woocommerce-subscriptions' ) . '</u></strong></br>' . implode( '<br />', str_replace( '_', ' ', $change_payment_method_features ) ) );
}
$status_html .= '"></span>';
$allowed_html = wp_kses_allowed_html( 'post' );
$allowed_html['span']['data-tip'] = true;
return wp_kses( $status_html, $allowed_html );
} }
/** /**
* Fire a gateway specific hook for when a subscription is activated. * Add links to find additional payment gateways to information after the Settings->Payments->Payment Methods table.
*
* @since 1.0
*/ */
public static function trigger_gateway_activated_subscription_hook( $user_id, $subscription_key ) { public static function add_recurring_payment_gateway_information( $settings, $option_prefix ) {
_deprecated_function( __METHOD__, '2.0', __CLASS__ . '::trigger_gateway_status_updated_hook()' ); $settings[] = array(
self::trigger_gateway_status_updated_hook( wcs_get_subscription_from_key( $subscription_key ), 'active' ); // translators: $1-$2: opening and closing tags. Link to documents->payment gateways, 3$-4$: opening and closing tags. Link to WooCommerce extensions shop page
} 'desc' => sprintf( __( 'Find new gateways that %1$ssupport automatic subscription payments%2$s in the official %3$sWooCommerce Marketplace%4$s.', 'woocommerce-subscriptions' ), '<a href="' . esc_url( 'http://docs.woocommerce.com/document/subscriptions/payment-gateways/' ) . '">', '</a>', '<a href="' . esc_url( 'http://www.woocommerce.com/product-category/woocommerce-extensions/' ) . '">', '</a>' ),
'id' => $option_prefix . '_payment_gateways_additional',
/** 'type' => 'informational',
* Fire a gateway specific hook for when a subscription is activated. );
* return $settings;
* @since 1.0
*/
public static function trigger_gateway_reactivated_subscription_hook( $user_id, $subscription_key ) {
_deprecated_function( __METHOD__, '2.0', __CLASS__ . '::trigger_gateway_status_updated_hook()' );
self::trigger_gateway_status_updated_hook( wcs_get_subscription_from_key( $subscription_key ), 'active' );
}
/**
* Fire a gateway specific hook for when a subscription is on-hold.
*
* @since 1.2
*/
public static function trigger_gateway_subscription_put_on_hold_hook( $user_id, $subscription_key ) {
_deprecated_function( __METHOD__, '2.0', __CLASS__ . '::trigger_gateway_status_updated_hook()' );
self::trigger_gateway_status_updated_hook( wcs_get_subscription_from_key( $subscription_key ), 'on-hold' );
}
/**
* Fire a gateway specific when a subscription is cancelled.
*
* @since 1.0
*/
public static function trigger_gateway_cancelled_subscription_hook( $user_id, $subscription_key ) {
_deprecated_function( __METHOD__, '2.0', __CLASS__ . '::trigger_gateway_status_updated_hook()' );
self::trigger_gateway_status_updated_hook( wcs_get_subscription_from_key( $subscription_key ), 'cancelled' );
}
/**
* Fire a gateway specific hook when a subscription expires.
*
* @since 1.0
*/
public static function trigger_gateway_subscription_expired_hook( $user_id, $subscription_key ) {
_deprecated_function( __METHOD__, '2.0', __CLASS__ . '::trigger_gateway_status_updated_hook()' );
self::trigger_gateway_status_updated_hook( wcs_get_subscription_from_key( $subscription_key ), 'expired' );
} }
} }

View File

@@ -1,53 +0,0 @@
<?php
/*
* Plugin Name: Action Scheduler
* Plugin URI: https://actionscheduler.org
* Description: A robust scheduling library for use in WordPress plugins.
* Author: Automattic
* Author URI: https://automattic.com/
* Version: 3.0.1
* License: GPLv3
*
* Copyright 2019 Automattic, Inc. (https://automattic.com/contact/)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
if ( ! function_exists( 'action_scheduler_register_3_dot_0_dot_1' ) ) {
if ( ! class_exists( 'ActionScheduler_Versions' ) ) {
require_once( 'classes/ActionScheduler_Versions.php' );
add_action( 'plugins_loaded', array( 'ActionScheduler_Versions', 'initialize_latest_version' ), 1, 0 );
}
add_action( 'plugins_loaded', 'action_scheduler_register_3_dot_0_dot_1', 0, 0 );
function action_scheduler_register_3_dot_0_dot_1() {
$versions = ActionScheduler_Versions::instance();
$versions->register( '3.0.1', 'action_scheduler_initialize_3_dot_0_dot_1' );
}
function action_scheduler_initialize_3_dot_0_dot_1() {
require_once( 'classes/abstracts/ActionScheduler.php' );
ActionScheduler::init( __FILE__ );
}
// Support usage in themes - load this version if no plugin has loaded a version yet.
if ( did_action( 'plugins_loaded' ) && ! class_exists( 'ActionScheduler' ) ) {
action_scheduler_register_3_dot_0_dot_1();
do_action( 'action_scheduler_pre_theme_init' );
ActionScheduler_Versions::initialize_latest_version();
}
}

View File

@@ -1,23 +0,0 @@
<?php
/**
* Class ActionScheduler_ActionClaim
*/
class ActionScheduler_ActionClaim {
private $id = '';
private $action_ids = array();
public function __construct( $id, array $action_ids ) {
$this->id = $id;
$this->action_ids = $action_ids;
}
public function get_id() {
return $this->id;
}
public function get_actions() {
return $this->action_ids;
}
}

View File

@@ -1,179 +0,0 @@
<?php
/**
* Class ActionScheduler_ActionFactory
*/
class ActionScheduler_ActionFactory {
/**
* @param string $status The action's status in the data store
* @param string $hook The hook to trigger when this action runs
* @param array $args Args to pass to callbacks when the hook is triggered
* @param ActionScheduler_Schedule $schedule The action's schedule
* @param string $group A group to put the action in
*
* @return ActionScheduler_Action An instance of the stored action
*/
public function get_stored_action( $status, $hook, array $args = array(), ActionScheduler_Schedule $schedule = null, $group = '' ) {
switch ( $status ) {
case ActionScheduler_Store::STATUS_PENDING :
$action_class = 'ActionScheduler_Action';
break;
case ActionScheduler_Store::STATUS_CANCELED :
$action_class = 'ActionScheduler_CanceledAction';
if ( ! is_null( $schedule ) && ! is_a( $schedule, 'ActionScheduler_CanceledSchedule' ) ) {
$schedule = new ActionScheduler_CanceledSchedule( $schedule->get_date() );
}
break;
default :
$action_class = 'ActionScheduler_FinishedAction';
break;
}
$action_class = apply_filters( 'action_scheduler_stored_action_class', $action_class, $status, $hook, $args, $schedule, $group );
$action = new $action_class( $hook, $args, $schedule, $group );
/**
* Allow 3rd party code to change the instantiated action for a given hook, args, schedule and group.
*
* @param ActionScheduler_Action $action The instantiated action.
* @param string $hook The instantiated action's hook.
* @param array $args The instantiated action's args.
* @param ActionScheduler_Schedule $schedule The instantiated action's schedule.
* @param string $group The instantiated action's group.
*/
return apply_filters( 'action_scheduler_stored_action_instance', $action, $hook, $args, $schedule, $group );
}
/**
* Enqueue an action to run one time, as soon as possible (rather a specific scheduled time).
*
* This method creates a new action with the NULLSchedule. This schedule maps to a MySQL datetime string of
* 0000-00-00 00:00:00. This is done to create a psuedo "async action" type that is fully backward compatible.
* Existing queries to claim actions claim by date, meaning actions scheduled for 0000-00-00 00:00:00 will
* always be claimed prior to actions scheduled for a specific date. This makes sure that any async action is
* given priority in queue processing. This has the added advantage of making sure async actions can be
* claimed by both the existing WP Cron and WP CLI runners, as well as a new async request runner.
*
* @param string $hook The hook to trigger when this action runs
* @param array $args Args to pass when the hook is triggered
* @param string $group A group to put the action in
*
* @return string The ID of the stored action
*/
public function async( $hook, $args = array(), $group = '' ) {
$schedule = new ActionScheduler_NullSchedule();
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
return $this->store( $action );
}
/**
* @param string $hook The hook to trigger when this action runs
* @param array $args Args to pass when the hook is triggered
* @param int $when Unix timestamp when the action will run
* @param string $group A group to put the action in
*
* @return string The ID of the stored action
*/
public function single( $hook, $args = array(), $when = null, $group = '' ) {
$date = as_get_datetime_object( $when );
$schedule = new ActionScheduler_SimpleSchedule( $date );
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
return $this->store( $action );
}
/**
* Create the first instance of an action recurring on a given interval.
*
* @param string $hook The hook to trigger when this action runs
* @param array $args Args to pass when the hook is triggered
* @param int $first Unix timestamp for the first run
* @param int $interval Seconds between runs
* @param string $group A group to put the action in
*
* @return string The ID of the stored action
*/
public function recurring( $hook, $args = array(), $first = null, $interval = null, $group = '' ) {
if ( empty($interval) ) {
return $this->single( $hook, $args, $first, $group );
}
$date = as_get_datetime_object( $first );
$schedule = new ActionScheduler_IntervalSchedule( $date, $interval );
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
return $this->store( $action );
}
/**
* Create the first instance of an action recurring on a Cron schedule.
*
* @param string $hook The hook to trigger when this action runs
* @param array $args Args to pass when the hook is triggered
* @param int $base_timestamp The first instance of the action will be scheduled
* to run at a time calculated after this timestamp matching the cron
* expression. This can be used to delay the first instance of the action.
* @param int $schedule A cron definition string
* @param string $group A group to put the action in
*
* @return string The ID of the stored action
*/
public function cron( $hook, $args = array(), $base_timestamp = null, $schedule = null, $group = '' ) {
if ( empty($schedule) ) {
return $this->single( $hook, $args, $base_timestamp, $group );
}
$date = as_get_datetime_object( $base_timestamp );
$cron = CronExpression::factory( $schedule );
$schedule = new ActionScheduler_CronSchedule( $date, $cron );
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
return $this->store( $action );
}
/**
* Create a successive instance of a recurring or cron action.
*
* Importantly, the action will be rescheduled to run based on the current date/time.
* That means when the action is scheduled to run in the past, the next scheduled date
* will be pushed forward. For example, if a recurring action set to run every hour
* was scheduled to run 5 seconds ago, it will be next scheduled for 1 hour in the
* future, which is 1 hour and 5 seconds from when it was last scheduled to run.
*
* Alternatively, if the action is scheduled to run in the future, and is run early,
* likely via manual intervention, then its schedule will change based on the time now.
* For example, if a recurring action set to run every day, and is run 12 hours early,
* it will run again in 24 hours, not 36 hours.
*
* This slippage is less of an issue with Cron actions, as the specific run time can
* be set for them to run, e.g. 1am each day. In those cases, and entire period would
* need to be missed before there was any change is scheduled, e.g. in the case of an
* action scheduled for 1am each day, the action would need to run an entire day late.
*
* @param ActionScheduler_Action $action The existing action.
*
* @return string The ID of the stored action
* @throws InvalidArgumentException If $action is not a recurring action.
*/
public function repeat( $action ) {
$schedule = $action->get_schedule();
$next = $schedule->get_next( as_get_datetime_object() );
if ( is_null( $next ) || ! $schedule->is_recurring() ) {
throw new InvalidArgumentException( __( 'Invalid action - must be a recurring action.', 'action-scheduler' ) );
}
$schedule_class = get_class( $schedule );
$new_schedule = new $schedule( $next, $schedule->get_recurrence(), $schedule->get_first_date() );
$new_action = new ActionScheduler_Action( $action->get_hook(), $action->get_args(), $new_schedule, $action->get_group() );
return $this->store( $new_action );
}
/**
* @param ActionScheduler_Action $action
*
* @return string The ID of the stored action
*/
protected function store( ActionScheduler_Action $action ) {
$store = ActionScheduler_Store::instance();
return $store->save_action( $action );
}
}

View File

@@ -1,137 +0,0 @@
<?php
/**
* Class ActionScheduler_AdminView
* @codeCoverageIgnore
*/
class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {
private static $admin_view = NULL;
private static $screen_id = 'tools_page_action-scheduler';
/**
* @return ActionScheduler_AdminView
* @codeCoverageIgnore
*/
public static function instance() {
if ( empty( self::$admin_view ) ) {
$class = apply_filters('action_scheduler_admin_view_class', 'ActionScheduler_AdminView');
self::$admin_view = new $class();
}
return self::$admin_view;
}
/**
* @codeCoverageIgnore
*/
public function init() {
if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || false == DOING_AJAX ) ) {
if ( class_exists( 'WooCommerce' ) ) {
add_action( 'woocommerce_admin_status_content_action-scheduler', array( $this, 'render_admin_ui' ) );
add_action( 'woocommerce_system_status_report', array( $this, 'system_status_report' ) );
add_filter( 'woocommerce_admin_status_tabs', array( $this, 'register_system_status_tab' ) );
}
add_action( 'admin_menu', array( $this, 'register_menu' ) );
add_action( 'current_screen', array( $this, 'add_help_tabs' ) );
}
}
public function system_status_report() {
$table = new ActionScheduler_wcSystemStatus( ActionScheduler::store() );
$table->render();
}
/**
* Registers action-scheduler into WooCommerce > System status.
*
* @param array $tabs An associative array of tab key => label.
* @return array $tabs An associative array of tab key => label, including Action Scheduler's tabs
*/
public function register_system_status_tab( array $tabs ) {
$tabs['action-scheduler'] = __( 'Scheduled Actions', 'action-scheduler' );
return $tabs;
}
/**
* Include Action Scheduler's administration under the Tools menu.
*
* A menu under the Tools menu is important for backward compatibility (as that's
* where it started), and also provides more convenient access than the WooCommerce
* System Status page, and for sites where WooCommerce isn't active.
*/
public function register_menu() {
$hook_suffix = add_submenu_page(
'tools.php',
__( 'Scheduled Actions', 'action-scheduler' ),
__( 'Scheduled Actions', 'action-scheduler' ),
'manage_options',
'action-scheduler',
array( $this, 'render_admin_ui' )
);
add_action( 'load-' . $hook_suffix , array( $this, 'process_admin_ui' ) );
}
/**
* Triggers processing of any pending actions.
*/
public function process_admin_ui() {
$table = new ActionScheduler_ListTable( ActionScheduler::store(), ActionScheduler::logger(), ActionScheduler::runner() );
$table->process_actions();
}
/**
* Renders the Admin UI
*/
public function render_admin_ui() {
$table = new ActionScheduler_ListTable( ActionScheduler::store(), ActionScheduler::logger(), ActionScheduler::runner() );
$table->display_page();
}
/**
* Provide more information about the screen and its data in the help tab.
*/
public function add_help_tabs() {
$screen = get_current_screen();
if ( ! $screen || self::$screen_id != $screen->id ) {
return;
}
$screen->add_help_tab(
array(
'id' => 'action_scheduler_about',
'title' => __( 'About', 'action-scheduler' ),
'content' =>
'<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

@@ -1,96 +0,0 @@
<?php
/**
* ActionScheduler_AsyncRequest_QueueRunner
*/
defined( 'ABSPATH' ) || exit;
/**
* ActionScheduler_AsyncRequest_QueueRunner class.
*/
class ActionScheduler_AsyncRequest_QueueRunner extends WP_Async_Request {
/**
* Data store for querying actions
*
* @var ActionScheduler_Store
* @access protected
*/
protected $store;
/**
* Prefix for ajax hooks
*
* @var string
* @access protected
*/
protected $prefix = 'as';
/**
* Action for ajax hooks
*
* @var string
* @access protected
*/
protected $action = 'async_request_queue_runner';
/**
* Initiate new async request
*/
public function __construct( ActionScheduler_Store $store ) {
parent::__construct();
$this->store = $store;
}
/**
* Handle async requests
*
* Run a queue, and maybe dispatch another async request to run another queue
* if there are still pending actions after completing a queue in this request.
*/
protected function handle() {
do_action( 'action_scheduler_run_queue', 'Async Request' ); // run a queue in the same way as WP Cron, but declare the Async Request context
$sleep_seconds = $this->get_sleep_seconds();
if ( $sleep_seconds ) {
sleep( $sleep_seconds );
}
$this->maybe_dispatch();
}
/**
* If the async request runner is needed and allowed to run, dispatch a request.
*/
public function maybe_dispatch() {
if ( ! $this->allow() ) {
return;
}
$this->dispatch();
}
/**
* 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,99 +0,0 @@
<?php
/**
* Class ActionScheduler_Compatibility
*/
class ActionScheduler_Compatibility {
/**
* Converts a shorthand byte value to an integer byte value.
*
* Wrapper for wp_convert_hr_to_bytes(), moved to load.php in WordPress 4.6 from media.php
*
* @link https://secure.php.net/manual/en/function.ini-get.php
* @link https://secure.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
*
* @param string $value A (PHP ini) byte value, either shorthand or ordinary.
* @return int An integer byte value.
*/
public static function convert_hr_to_bytes( $value ) {
if ( function_exists( 'wp_convert_hr_to_bytes' ) ) {
return wp_convert_hr_to_bytes( $value );
}
$value = strtolower( trim( $value ) );
$bytes = (int) $value;
if ( false !== strpos( $value, 'g' ) ) {
$bytes *= GB_IN_BYTES;
} elseif ( false !== strpos( $value, 'm' ) ) {
$bytes *= MB_IN_BYTES;
} elseif ( false !== strpos( $value, 'k' ) ) {
$bytes *= KB_IN_BYTES;
}
// Deal with large (float) values which run into the maximum integer size.
return min( $bytes, PHP_INT_MAX );
}
/**
* Attempts to raise the PHP memory limit for memory intensive processes.
*
* Only allows raising the existing limit and prevents lowering it.
*
* Wrapper for wp_raise_memory_limit(), added in WordPress v4.6.0
*
* @return bool|int|string The limit that was set or false on failure.
*/
public static function raise_memory_limit() {
if ( function_exists( 'wp_raise_memory_limit' ) ) {
return wp_raise_memory_limit( 'admin' );
}
$current_limit = @ini_get( 'memory_limit' );
$current_limit_int = self::convert_hr_to_bytes( $current_limit );
if ( -1 === $current_limit_int ) {
return false;
}
$wp_max_limit = WP_MAX_MEMORY_LIMIT;
$wp_max_limit_int = self::convert_hr_to_bytes( $wp_max_limit );
$filtered_limit = apply_filters( 'admin_memory_limit', $wp_max_limit );
$filtered_limit_int = self::convert_hr_to_bytes( $filtered_limit );
if ( -1 === $filtered_limit_int || ( $filtered_limit_int > $wp_max_limit_int && $filtered_limit_int > $current_limit_int ) ) {
if ( false !== @ini_set( 'memory_limit', $filtered_limit ) ) {
return $filtered_limit;
} else {
return false;
}
} elseif ( -1 === $wp_max_limit_int || $wp_max_limit_int > $current_limit_int ) {
if ( false !== @ini_set( 'memory_limit', $wp_max_limit ) ) {
return $wp_max_limit;
} else {
return false;
}
}
return false;
}
/**
* Attempts to raise the PHP timeout for time intensive processes.
*
* Only allows raising the existing limit and prevents lowering it. Wrapper for wc_set_time_limit(), when available.
*
* @param int The time limit in seconds.
*/
public static function raise_time_limit( $limit = 0 ) {
if ( $limit < ini_get( 'max_execution_time' ) ) {
return;
}
if ( function_exists( 'wc_set_time_limit' ) ) {
wc_set_time_limit( $limit );
} elseif ( function_exists( 'set_time_limit' ) && false === strpos( ini_get( 'disable_functions' ), 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
@set_time_limit( $limit );
}
}
}

View File

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

@@ -1,76 +0,0 @@
<?php
/**
* ActionScheduler DateTime class.
*
* This is a custom extension to DateTime that
*/
class ActionScheduler_DateTime extends DateTime {
/**
* UTC offset.
*
* Only used when a timezone is not set. When a timezone string is
* used, this will be set to 0.
*
* @var int
*/
protected $utcOffset = 0;
/**
* Get the unix timestamp of the current object.
*
* Missing in PHP 5.2 so just here so it can be supported consistently.
*
* @return int
*/
public function getTimestamp() {
return method_exists( 'DateTime', 'getTimestamp' ) ? parent::getTimestamp() : $this->format( 'U' );
}
/**
* Set the UTC offset.
*
* This represents a fixed offset instead of a timezone setting.
*
* @param $offset
*/
public function setUtcOffset( $offset ) {
$this->utcOffset = intval( $offset );
}
/**
* Returns the timezone offset.
*
* @return int
* @link http://php.net/manual/en/datetime.getoffset.php
*/
public function getOffset() {
return $this->utcOffset ? $this->utcOffset : parent::getOffset();
}
/**
* Set the TimeZone associated with the DateTime
*
* @param DateTimeZone $timezone
*
* @return static
* @link http://php.net/manual/en/datetime.settimezone.php
*/
public function setTimezone( $timezone ) {
$this->utcOffset = 0;
parent::setTimezone( $timezone );
return $this;
}
/**
* Get the timestamp with the WordPress timezone offset added or subtracted.
*
* @since 3.0.0
* @return int
*/
public function getOffsetTimestamp() {
return $this->getTimestamp() + $this->getOffset();
}
}

View File

@@ -1,11 +0,0 @@
<?php
/**
* ActionScheduler Exception Interface.
*
* Facilitates catching Exceptions unique to Action Scheduler.
*
* @package ActionScheduler
* @since %VERSION%
*/
interface ActionScheduler_Exception {}

View File

@@ -1,55 +0,0 @@
<?php
/**
* Class ActionScheduler_FatalErrorMonitor
*/
class ActionScheduler_FatalErrorMonitor {
/** @var ActionScheduler_ActionClaim */
private $claim = NULL;
/** @var ActionScheduler_Store */
private $store = NULL;
private $action_id = 0;
public function __construct( ActionScheduler_Store $store ) {
$this->store = $store;
}
public function attach( ActionScheduler_ActionClaim $claim ) {
$this->claim = $claim;
add_action( 'shutdown', array( $this, 'handle_unexpected_shutdown' ) );
add_action( 'action_scheduler_before_execute', array( $this, 'track_current_action' ), 0, 1 );
add_action( 'action_scheduler_after_execute', array( $this, 'untrack_action' ), 0, 0 );
add_action( 'action_scheduler_execution_ignored', array( $this, 'untrack_action' ), 0, 0 );
add_action( 'action_scheduler_failed_execution', array( $this, 'untrack_action' ), 0, 0 );
}
public function detach() {
$this->claim = NULL;
$this->untrack_action();
remove_action( 'shutdown', array( $this, 'handle_unexpected_shutdown' ) );
remove_action( 'action_scheduler_before_execute', array( $this, 'track_current_action' ), 0 );
remove_action( 'action_scheduler_after_execute', array( $this, 'untrack_action' ), 0 );
remove_action( 'action_scheduler_execution_ignored', array( $this, 'untrack_action' ), 0 );
remove_action( 'action_scheduler_failed_execution', array( $this, 'untrack_action' ), 0 );
}
public function track_current_action( $action_id ) {
$this->action_id = $action_id;
}
public function untrack_action() {
$this->action_id = 0;
}
public function handle_unexpected_shutdown() {
if ( $error = error_get_last() ) {
if ( in_array( $error['type'], array( E_ERROR, E_PARSE, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR ) ) ) {
if ( !empty($this->action_id) ) {
$this->store->mark_failure( $this->action_id );
do_action( 'action_scheduler_unexpected_shutdown', $this->action_id, $error );
}
}
$this->store->release_claim( $this->claim );
}
}
}

View File

@@ -1,47 +0,0 @@
<?php
/**
* InvalidAction Exception.
*
* Used for identifying actions that are invalid in some way.
*
* @package ActionScheduler
*/
class ActionScheduler_InvalidActionException extends \InvalidArgumentException implements ActionScheduler_Exception {
/**
* Create a new exception when the action's schedule cannot be fetched.
*
* @param string $action_id The action ID with bad args.
* @return static
*/
public static function from_schedule( $action_id, $schedule ) {
$message = sprintf(
/* translators: 1: action ID 2: schedule */
__( 'Action [%1$s] has an invalid schedule: %2$s', 'action-scheduler' ),
$action_id,
var_export( $schedule, true )
);
return new static( $message );
}
/**
* Create a new exception when the action's args cannot be decoded to an array.
*
* @author Jeremy Pry
*
* @param string $action_id The action ID with bad args.
* @return static
*/
public static function from_decoding_args( $action_id, $args = array() ) {
$message = sprintf(
/* translators: 1: action ID 2: arguments */
__( 'Action [%1$s] has invalid arguments. It cannot be JSON decoded to an array. $args = %2$s', 'action-scheduler' ),
$action_id,
var_export( $args, true )
);
return new static( $message );
}
}

View File

@@ -1,559 +0,0 @@
<?php
/**
* Implements the admin view of the actions.
* @codeCoverageIgnore
*/
class ActionScheduler_ListTable extends ActionScheduler_Abstract_ListTable {
/**
* The package name.
*
* @var string
*/
protected $package = 'action-scheduler';
/**
* Columns to show (name => label).
*
* @var array
*/
protected $columns = array();
/**
* Actions (name => label).
*
* @var array
*/
protected $row_actions = array();
/**
* The active data stores
*
* @var ActionScheduler_Store
*/
protected $store;
/**
* A logger to use for getting action logs to display
*
* @var ActionScheduler_Logger
*/
protected $logger;
/**
* A ActionScheduler_QueueRunner runner instance (or child class)
*
* @var ActionScheduler_QueueRunner
*/
protected $runner;
/**
* Bulk actions. The key of the array is the method name of the implementation:
*
* bulk_<key>(array $ids, string $sql_in).
*
* See the comments in the parent class for further details
*
* @var array
*/
protected $bulk_actions = array();
/**
* Flag variable to render our notifications, if any, once.
*
* @var bool
*/
protected static $did_notification = false;
/**
* Array of seconds for common time periods, like week or month, alongside an internationalised string representation, i.e. "Day" or "Days"
*
* @var array
*/
private static $time_periods;
/**
* Sets the current data store object into `store->action` and initialises the object.
*
* @param ActionScheduler_Store $store
* @param ActionScheduler_Logger $logger
* @param ActionScheduler_QueueRunner $runner
*/
public function __construct( ActionScheduler_Store $store, ActionScheduler_Logger $logger, ActionScheduler_QueueRunner $runner ) {
$this->store = $store;
$this->logger = $logger;
$this->runner = $runner;
$this->table_header = __( 'Scheduled Actions', 'action-scheduler' );
$this->bulk_actions = array(
'delete' => __( 'Delete', 'action-scheduler' ),
);
$this->columns = array(
'hook' => __( 'Hook', 'action-scheduler' ),
'status' => __( 'Status', 'action-scheduler' ),
'args' => __( 'Arguments', 'action-scheduler' ),
'group' => __( 'Group', 'action-scheduler' ),
'recurrence' => __( 'Recurrence', 'action-scheduler' ),
'schedule' => __( 'Scheduled Date', 'action-scheduler' ),
'log_entries' => __( 'Log', 'action-scheduler' ),
);
$this->sort_by = array(
'schedule',
'hook',
'group',
);
$this->search_by = array(
'hook',
'args',
'claim_id',
);
$request_status = $this->get_request_status();
if ( empty( $request_status ) ) {
$this->sort_by[] = 'status';
} elseif ( in_array( $request_status, array( 'in-progress', 'failed' ) ) ) {
$this->columns += array( 'claim_id' => __( 'Claim ID', 'action-scheduler' ) );
$this->sort_by[] = 'claim_id';
}
$this->row_actions = array(
'hook' => array(
'run' => array(
'name' => __( 'Run', 'action-scheduler' ),
'desc' => __( 'Process the action now as if it were run as part of a queue', 'action-scheduler' ),
),
'cancel' => array(
'name' => __( 'Cancel', 'action-scheduler' ),
'desc' => __( 'Cancel the action now to avoid it being run in future', 'action-scheduler' ),
'class' => 'cancel trash',
),
),
);
self::$time_periods = array(
array(
'seconds' => YEAR_IN_SECONDS,
/* translators: %s: amount of time */
'names' => _n_noop( '%s year', '%s years', 'action-scheduler' ),
),
array(
'seconds' => MONTH_IN_SECONDS,
/* translators: %s: amount of time */
'names' => _n_noop( '%s month', '%s months', 'action-scheduler' ),
),
array(
'seconds' => WEEK_IN_SECONDS,
/* translators: %s: amount of time */
'names' => _n_noop( '%s week', '%s weeks', 'action-scheduler' ),
),
array(
'seconds' => DAY_IN_SECONDS,
/* translators: %s: amount of time */
'names' => _n_noop( '%s day', '%s days', 'action-scheduler' ),
),
array(
'seconds' => HOUR_IN_SECONDS,
/* translators: %s: amount of time */
'names' => _n_noop( '%s hour', '%s hours', 'action-scheduler' ),
),
array(
'seconds' => MINUTE_IN_SECONDS,
/* translators: %s: amount of time */
'names' => _n_noop( '%s minute', '%s minutes', 'action-scheduler' ),
),
array(
'seconds' => 1,
/* translators: %s: amount of time */
'names' => _n_noop( '%s second', '%s seconds', 'action-scheduler' ),
),
);
parent::__construct( array(
'singular' => 'action-scheduler',
'plural' => 'action-scheduler',
'ajax' => false,
) );
}
/**
* Convert an interval of seconds into a two part human friendly string.
*
* The WordPress human_time_diff() function only calculates the time difference to one degree, meaning
* even if an action is 1 day and 11 hours away, it will display "1 day". This function goes one step
* further to display two degrees of accuracy.
*
* Inspired by the Crontrol::interval() function by Edward Dale: https://wordpress.org/plugins/wp-crontrol/
*
* @param int $interval A interval in seconds.
* @param int $periods_to_include Depth of time periods to include, e.g. for an interval of 70, and $periods_to_include of 2, both minutes and seconds would be included. With a value of 1, only minutes would be included.
* @return string A human friendly string representation of the interval.
*/
private static function human_interval( $interval, $periods_to_include = 2 ) {
if ( $interval <= 0 ) {
return __( 'Now!', 'action-scheduler' );
}
$output = '';
for ( $time_period_index = 0, $periods_included = 0, $seconds_remaining = $interval; $time_period_index < count( self::$time_periods ) && $seconds_remaining > 0 && $periods_included < $periods_to_include; $time_period_index++ ) {
$periods_in_interval = floor( $seconds_remaining / self::$time_periods[ $time_period_index ]['seconds'] );
if ( $periods_in_interval > 0 ) {
if ( ! empty( $output ) ) {
$output .= ' ';
}
$output .= sprintf( _n( self::$time_periods[ $time_period_index ]['names'][0], self::$time_periods[ $time_period_index ]['names'][1], $periods_in_interval, 'action-scheduler' ), $periods_in_interval );
$seconds_remaining -= $periods_in_interval * self::$time_periods[ $time_period_index ]['seconds'];
$periods_included++;
}
}
return $output;
}
/**
* Returns the recurrence of an action or 'Non-repeating'. The output is human readable.
*
* @param ActionScheduler_Action $action
*
* @return string
*/
protected function get_recurrence( $action ) {
$schedule = $action->get_schedule();
if ( $schedule->is_recurring() ) {
$recurrence = $schedule->get_recurrence();
if ( is_numeric( $recurrence ) ) {
/* translators: %s: time interval */
return sprintf( __( 'Every %s', 'action-scheduler' ), self::human_interval( $recurrence ) );
} else {
return $recurrence;
}
}
return __( 'Non-repeating', 'action-scheduler' );
}
/**
* Serializes the argument of an action to render it in a human friendly format.
*
* @param array $row The array representation of the current row of the table
*
* @return string
*/
public function column_args( array $row ) {
if ( empty( $row['args'] ) ) {
return '';
}
$row_html = '<ul>';
foreach ( $row['args'] as $key => $value ) {
$row_html .= sprintf( '<li><code>%s => %s</code></li>', esc_html( var_export( $key, true ) ), esc_html( var_export( $value, true ) ) );
}
$row_html .= '</ul>';
return apply_filters( 'action_scheduler_list_table_column_args', $row_html, $row );
}
/**
* Prints the logs entries inline. We do so to avoid loading Javascript and other hacks to show it in a modal.
*
* @param array $row Action array.
* @return string
*/
public function column_log_entries( array $row ) {
$log_entries_html = '<ol>';
$timezone = new DateTimezone( 'UTC' );
foreach ( $row['log_entries'] as $log_entry ) {
$log_entries_html .= $this->get_log_entry_html( $log_entry, $timezone );
}
$log_entries_html .= '</ol>';
return $log_entries_html;
}
/**
* Prints the logs entries inline. We do so to avoid loading Javascript and other hacks to show it in a modal.
*
* @param ActionScheduler_LogEntry $log_entry
* @param DateTimezone $timezone
* @return string
*/
protected function get_log_entry_html( ActionScheduler_LogEntry $log_entry, DateTimezone $timezone ) {
$date = $log_entry->get_date();
$date->setTimezone( $timezone );
return sprintf( '<li><strong>%s</strong><br/>%s</li>', esc_html( $date->format( 'Y-m-d H:i:s O' ) ), esc_html( $log_entry->get_message() ) );
}
/**
* Only display row actions for pending actions.
*
* @param array $row Row to render
* @param string $column_name Current row
*
* @return string
*/
protected function maybe_render_actions( $row, $column_name ) {
if ( 'pending' === strtolower( $row['status'] ) ) {
return parent::maybe_render_actions( $row, $column_name );
}
return '';
}
/**
* Renders admin notifications
*
* Notifications:
* 1. When the maximum number of tasks are being executed simultaneously
* 2. Notifications when a task us manually executed
*/
public function display_admin_notices() {
if ( $this->runner->has_maximum_concurrent_batches() ) {
$this->admin_notices[] = array(
'class' => 'updated',
'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,
);
}
$notification = get_transient( 'action_scheduler_admin_notice' );
if ( is_array( $notification ) ) {
delete_transient( 'action_scheduler_admin_notice' );
$action = $this->store->fetch_action( $notification['action_id'] );
$action_hook_html = '<strong><code>' . $action->get_hook() . '</code></strong>';
if ( 1 == $notification['success'] ) {
$class = 'updated';
switch ( $notification['row_action_type'] ) {
case 'run' :
/* translators: %s: action HTML */
$action_message_html = sprintf( __( 'Successfully executed action: %s', 'action-scheduler' ), $action_hook_html );
break;
case 'cancel' :
/* translators: %s: action HTML */
$action_message_html = sprintf( __( 'Successfully canceled action: %s', 'action-scheduler' ), $action_hook_html );
break;
default :
/* translators: %s: action HTML */
$action_message_html = sprintf( __( 'Successfully processed change for action: %s', 'action-scheduler' ), $action_hook_html );
break;
}
} else {
$class = 'error';
/* translators: 1: action HTML 2: action ID 3: error message */
$action_message_html = sprintf( __( 'Could not process change for action: "%1$s" (ID: %2$d). Error: %3$s', 'action-scheduler' ), $action_hook_html, esc_html( $notification['action_id'] ), esc_html( $notification['error_message'] ) );
}
$action_message_html = apply_filters( 'action_scheduler_admin_notice_html', $action_message_html, $action, $notification );
$this->admin_notices[] = array(
'class' => $class,
'message' => $action_message_html,
);
}
parent::display_admin_notices();
}
/**
* Prints the scheduled date in a human friendly format.
*
* @param array $row The array representation of the current row of the table
*
* @return string
*/
public function column_schedule( $row ) {
return $this->get_schedule_display_string( $row['schedule'] );
}
/**
* Get the scheduled date in a human friendly format.
*
* @param ActionScheduler_Schedule $schedule
* @return string
*/
protected function get_schedule_display_string( ActionScheduler_Schedule $schedule ) {
$schedule_display_string = '';
if ( ! $schedule->get_date() ) {
return '0000-00-00 00:00:00';
}
$next_timestamp = $schedule->get_date()->getTimestamp();
$schedule_display_string .= $schedule->get_date()->format( 'Y-m-d H:i:s O' );
$schedule_display_string .= '<br/>';
if ( gmdate( 'U' ) > $next_timestamp ) {
/* translators: %s: date interval */
$schedule_display_string .= sprintf( __( ' (%s ago)', 'action-scheduler' ), self::human_interval( gmdate( 'U' ) - $next_timestamp ) );
} else {
/* translators: %s: date interval */
$schedule_display_string .= sprintf( __( ' (%s)', 'action-scheduler' ), self::human_interval( $next_timestamp - gmdate( 'U' ) ) );
}
return $schedule_display_string;
}
/**
* Bulk delete
*
* Deletes actions based on their ID. This is the handler for the bulk delete. It assumes the data
* properly validated by the callee and it will delete the actions without any extra validation.
*
* @param array $ids
* @param string $ids_sql Inherited and unused
*/
protected function bulk_delete( array $ids, $ids_sql ) {
foreach ( $ids as $id ) {
$this->store->delete_action( $id );
}
}
/**
* Implements the logic behind running an action. ActionScheduler_Abstract_ListTable validates the request and their
* parameters are valid.
*
* @param int $action_id
*/
protected function row_action_cancel( $action_id ) {
$this->process_row_action( $action_id, 'cancel' );
}
/**
* Implements the logic behind running an action. ActionScheduler_Abstract_ListTable validates the request and their
* parameters are valid.
*
* @param int $action_id
*/
protected function row_action_run( $action_id ) {
$this->process_row_action( $action_id, 'run' );
}
/**
* Implements the logic behind processing an action once an action link is clicked on the list table.
*
* @param int $action_id
* @param string $row_action_type The type of action to perform on the action.
*/
protected function process_row_action( $action_id, $row_action_type ) {
try {
switch ( $row_action_type ) {
case 'run' :
$this->runner->process_action( $action_id, 'Admin List Table' );
break;
case 'cancel' :
$this->store->cancel_action( $action_id );
break;
}
$success = 1;
$error_message = '';
} catch ( Exception $e ) {
$success = 0;
$error_message = $e->getMessage();
}
set_transient( 'action_scheduler_admin_notice', compact( 'action_id', 'success', 'error_message', 'row_action_type' ), 30 );
}
/**
* {@inheritDoc}
*/
public function prepare_items() {
$this->prepare_column_headers();
$per_page = $this->get_items_per_page( $this->package . '_items_per_page', $this->items_per_page );
$query = array(
'per_page' => $per_page,
'offset' => $this->get_items_offset(),
'status' => $this->get_request_status(),
'orderby' => $this->get_request_orderby(),
'order' => $this->get_request_order(),
'search' => $this->get_request_search_query(),
);
$this->items = array();
$total_items = $this->store->query_actions( $query, 'count' );
$status_labels = $this->store->get_status_labels();
foreach ( $this->store->query_actions( $query ) as $action_id ) {
try {
$action = $this->store->fetch_action( $action_id );
} catch ( Exception $e ) {
continue;
}
$this->items[ $action_id ] = array(
'ID' => $action_id,
'hook' => $action->get_hook(),
'status' => $status_labels[ $this->store->get_status( $action_id ) ],
'args' => $action->get_args(),
'group' => $action->get_group(),
'log_entries' => $this->logger->get_logs( $action_id ),
'claim_id' => $this->store->get_claim_id( $action_id ),
'recurrence' => $this->get_recurrence( $action ),
'schedule' => $action->get_schedule(),
);
}
$this->set_pagination_args( array(
'total_items' => $total_items,
'per_page' => $per_page,
'total_pages' => ceil( $total_items / $per_page ),
) );
}
/**
* Prints the available statuses so the user can click to filter.
*/
protected function display_filter_by_status() {
$this->status_counts = $this->store->action_counts();
parent::display_filter_by_status();
}
/**
* Get the text to display in the search box on the list table.
*/
protected function get_search_box_button_text() {
return __( 'Search hook, args and claim ID', 'action-scheduler' );
}
}

View File

@@ -1,67 +0,0 @@
<?php
/**
* Class ActionScheduler_LogEntry
*/
class ActionScheduler_LogEntry {
/**
* @var int $action_id
*/
protected $action_id = '';
/**
* @var string $message
*/
protected $message = '';
/**
* @var Datetime $date
*/
protected $date;
/**
* Constructor
*
* @param mixed $action_id Action ID
* @param string $message Message
* @param Datetime $date Datetime object with the time when this log entry was created. If this parameter is
* not provided a new Datetime object (with current time) will be created.
*/
public function __construct( $action_id, $message, $date = null ) {
/*
* ActionScheduler_wpCommentLogger::get_entry() previously passed a 3rd param of $comment->comment_type
* to ActionScheduler_LogEntry::__construct(), goodness knows why, and the Follow-up Emails plugin
* hard-codes loading its own version of ActionScheduler_wpCommentLogger with that out-dated method,
* goodness knows why, so we need to guard against that here instead of using a DateTime type declaration
* for the constructor's 3rd param of $date and causing a fatal error with older versions of FUE.
*/
if ( null !== $date && ! is_a( $date, 'DateTime' ) ) {
_doing_it_wrong( __METHOD__, 'The third parameter must be a valid DateTime instance, or null.', '2.0.0' );
$date = null;
}
$this->action_id = $action_id;
$this->message = $message;
$this->date = $date ? $date : new Datetime;
}
/**
* Returns the date when this log entry was created
*
* @return Datetime
*/
public function get_date() {
return $this->date;
}
public function get_action_id() {
return $this->action_id;
}
public function get_message() {
return $this->message;
}
}

View File

@@ -1,11 +0,0 @@
<?php
/**
* Class ActionScheduler_NullLogEntry
*/
class ActionScheduler_NullLogEntry extends ActionScheduler_LogEntry {
public function __construct( $action_id = '', $message = '' ) {
// nothing to see here
}
}

View File

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

View File

@@ -1,155 +0,0 @@
<?php
/**
* Class ActionScheduler_QueueCleaner
*/
class ActionScheduler_QueueCleaner {
/** @var int */
protected $batch_size;
/** @var ActionScheduler_Store */
private $store = null;
/**
* 31 days in seconds.
*
* @var int
*/
private $month_in_seconds = 2678400;
/**
* ActionScheduler_QueueCleaner constructor.
*
* @param ActionScheduler_Store $store The store instance.
* @param int $batch_size The batch size.
*/
public function __construct( ActionScheduler_Store $store = null, $batch_size = 20 ) {
$this->store = $store ? $store : ActionScheduler_Store::instance();
$this->batch_size = $batch_size;
}
public function delete_old_actions() {
$lifespan = apply_filters( 'action_scheduler_retention_period', $this->month_in_seconds );
$cutoff = as_get_datetime_object($lifespan.' seconds ago');
$statuses_to_purge = array(
ActionScheduler_Store::STATUS_COMPLETE,
ActionScheduler_Store::STATUS_CANCELED,
);
foreach ( $statuses_to_purge as $status ) {
$actions_to_delete = $this->store->query_actions( array(
'status' => $status,
'modified' => $cutoff,
'modified_compare' => '<=',
'per_page' => $this->get_batch_size(),
) );
foreach ( $actions_to_delete as $action_id ) {
try {
$this->store->delete_action( $action_id );
} catch ( Exception $e ) {
/**
* Notify 3rd party code of exceptions when deleting a completed action older than the retention period
*
* This hook provides a way for 3rd party code to log or otherwise handle exceptions relating to their
* actions.
*
* @since 2.0.0
*
* @param int $action_id The scheduled actions ID in the data store
* @param Exception $e The exception thrown when attempting to delete the action from the data store
* @param int $lifespan The retention period, in seconds, for old actions
* @param int $count_of_actions_to_delete The number of old actions being deleted in this batch
*/
do_action( 'action_scheduler_failed_old_action_deletion', $action_id, $e, $lifespan, count( $actions_to_delete ) );
}
}
}
}
/**
* Unclaim pending actions that have not been run within a given time limit.
*
* When called by ActionScheduler_Abstract_QueueRunner::run_cleanup(), the time limit passed
* as a parameter is 10x the time limit used for queue processing.
*
* @param int $time_limit The number of seconds to allow a queue to run before unclaiming its pending actions. Default 300 (5 minutes).
*/
public function reset_timeouts( $time_limit = 300 ) {
$timeout = apply_filters( 'action_scheduler_timeout_period', $time_limit );
if ( $timeout < 0 ) {
return;
}
$cutoff = as_get_datetime_object($timeout.' seconds ago');
$actions_to_reset = $this->store->query_actions( array(
'status' => ActionScheduler_Store::STATUS_PENDING,
'modified' => $cutoff,
'modified_compare' => '<=',
'claimed' => true,
'per_page' => $this->get_batch_size(),
) );
foreach ( $actions_to_reset as $action_id ) {
$this->store->unclaim_action( $action_id );
do_action( 'action_scheduler_reset_action', $action_id );
}
}
/**
* Mark actions that have been running for more than a given time limit as failed, based on
* the assumption some uncatachable and unloggable fatal error occurred during processing.
*
* When called by ActionScheduler_Abstract_QueueRunner::run_cleanup(), the time limit passed
* as a parameter is 10x the time limit used for queue processing.
*
* @param int $time_limit The number of seconds to allow an action to run before it is considered to have failed. Default 300 (5 minutes).
*/
public function mark_failures( $time_limit = 300 ) {
$timeout = apply_filters( 'action_scheduler_failure_period', $time_limit );
if ( $timeout < 0 ) {
return;
}
$cutoff = as_get_datetime_object($timeout.' seconds ago');
$actions_to_reset = $this->store->query_actions( array(
'status' => ActionScheduler_Store::STATUS_RUNNING,
'modified' => $cutoff,
'modified_compare' => '<=',
'per_page' => $this->get_batch_size(),
) );
foreach ( $actions_to_reset as $action_id ) {
$this->store->mark_failure( $action_id );
do_action( 'action_scheduler_failed_action', $action_id, $timeout );
}
}
/**
* Do all of the cleaning actions.
*
* @param int $time_limit The number of seconds to use as the timeout and failure period. Default 300 (5 minutes).
* @author Jeremy Pry
*/
public function clean( $time_limit = 300 ) {
$this->delete_old_actions();
$this->reset_timeouts( $time_limit );
$this->mark_failures( $time_limit );
}
/**
* Get the batch size for cleaning the queue.
*
* @author Jeremy Pry
* @return int
*/
protected function get_batch_size() {
/**
* Filter the batch size when cleaning the queue.
*
* @param int $batch_size The number of actions to clean in one batch.
*/
return absint( apply_filters( 'action_scheduler_cleanup_batch_size', $this->batch_size ) );
}
}

View File

@@ -1,185 +0,0 @@
<?php
/**
* Class ActionScheduler_QueueRunner
*/
class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
const WP_CRON_HOOK = 'action_scheduler_run_queue';
const WP_CRON_SCHEDULE = 'every_minute';
/** @var ActionScheduler_AsyncRequest_QueueRunner */
protected $async_request;
/** @var ActionScheduler_QueueRunner */
private static $runner = null;
/**
* @return ActionScheduler_QueueRunner
* @codeCoverageIgnore
*/
public static function instance() {
if ( empty(self::$runner) ) {
$class = apply_filters('action_scheduler_queue_runner_class', 'ActionScheduler_QueueRunner');
self::$runner = new $class();
}
return self::$runner;
}
/**
* ActionScheduler_QueueRunner constructor.
*
* @param ActionScheduler_Store $store
* @param ActionScheduler_FatalErrorMonitor $monitor
* @param ActionScheduler_QueueCleaner $cleaner
*/
public function __construct( ActionScheduler_Store $store = null, ActionScheduler_FatalErrorMonitor $monitor = null, ActionScheduler_QueueCleaner $cleaner = null, ActionScheduler_AsyncRequest_QueueRunner $async_request = null ) {
parent::__construct( $store, $monitor, $cleaner );
if ( is_null( $async_request ) ) {
$async_request = new ActionScheduler_AsyncRequest_QueueRunner( $this->store );
}
$this->async_request = $async_request;
}
/**
* @codeCoverageIgnore
*/
public function init() {
add_filter( 'cron_schedules', array( self::instance(), 'add_wp_cron_schedule' ) );
$cron_context = array( 'WP Cron' );
if ( ! wp_next_scheduled( self::WP_CRON_HOOK, $cron_context ) ) {
// Check for and remove any WP Cron hook scheduled by Action Scheduler < 3.0.0, which didn't include the $context param
$next_timestamp = wp_next_scheduled( self::WP_CRON_HOOK );
if ( $next_timestamp ) {
wp_unschedule_event( $next_timestamp, self::WP_CRON_HOOK );
}
$schedule = apply_filters( 'action_scheduler_run_schedule', self::WP_CRON_SCHEDULE );
wp_schedule_event( time(), $schedule, self::WP_CRON_HOOK, $cron_context );
}
add_action( self::WP_CRON_HOOK, array( self::instance(), 'run' ) );
add_filter( 'shutdown', array( $this, 'maybe_dispatch_async_request' ) );
}
/**
* Check if we should dispatch an async request to process actions.
*
* This method is attached to 'shutdown', so is called frequently. To avoid slowing down
* the site, it mitigates the work performed in each request by:
* 1. checking if it's in the admin context and then
* 2. haven't run on the 'shutdown' hook within the lock time (60 seconds by default)
* 3. haven't exceeded the number of allowed batches.
*
* The order of these checks is important, because they run from a check on a value:
* 1. in memory - is_admin() maps to $GLOBALS or the WP_ADMIN constant
* 2. in memory - transients use autoloaded options by default
* 3. from a database query - has_maximum_concurrent_batches() run the query
* $this->store->get_claim_count() to find the current number of claims in the DB.
*
* If all of these conditions are met, then we request an async runner check whether it
* should dispatch a request to process pending actions.
*/
public function maybe_dispatch_async_request() {
if ( is_admin() && ! ActionScheduler::lock()->is_locked( 'async-request-runner' ) ) {
// Only start an async queue at most once every 60 seconds
ActionScheduler::lock()->set( 'async-request-runner' );
$this->async_request->maybe_dispatch();
}
}
/**
* Process actions in the queue. Attached to self::WP_CRON_HOOK i.e. 'action_scheduler_run_queue'
*
* The $context param of this method defaults to 'WP Cron', because prior to Action Scheduler 3.0.0
* that was the only context in which this method was run, and the self::WP_CRON_HOOK hook had no context
* passed along with it. New code calling this method directly, or by triggering the self::WP_CRON_HOOK,
* should set a context as the first parameter. For an example of this, refer to the code seen in
* @see ActionScheduler_AsyncRequest_QueueRunner::handle()
*
* @param string $context Optional identifer for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
* Generally, this should be capitalised and not localised as it's a proper noun.
* @return int The number of actions processed.
*/
public function run( $context = 'WP Cron' ) {
ActionScheduler_Compatibility::raise_memory_limit();
ActionScheduler_Compatibility::raise_time_limit( $this->get_time_limit() );
do_action( 'action_scheduler_before_process_queue' );
$this->run_cleanup();
$processed_actions = 0;
if ( false === $this->has_maximum_concurrent_batches() ) {
$batch_size = apply_filters( 'action_scheduler_queue_runner_batch_size', 25 );
do {
$processed_actions_in_batch = $this->do_batch( $batch_size, $context );
$processed_actions += $processed_actions_in_batch;
} while ( $processed_actions_in_batch > 0 && ! $this->batch_limits_exceeded( $processed_actions ) ); // keep going until we run out of actions, time, or memory
}
do_action( 'action_scheduler_after_process_queue' );
return $processed_actions;
}
/**
* Process a batch of actions pending in the queue.
*
* Actions are processed by claiming a set of pending actions then processing each one until either the batch
* size is completed, or memory or time limits are reached, defined by @see $this->batch_limits_exceeded().
*
* @param int $size The maximum number of actions to process in the batch.
* @param string $context Optional identifer for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
* Generally, this should be capitalised and not localised as it's a proper noun.
* @return int The number of actions processed.
*/
protected function do_batch( $size = 100, $context = '' ) {
$claim = $this->store->stake_claim($size);
$this->monitor->attach($claim);
$processed_actions = 0;
foreach ( $claim->get_actions() as $action_id ) {
// bail if we lost the claim
if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $claim->get_id() ) ) ) {
break;
}
$this->process_action( $action_id, $context );
$processed_actions++;
if ( $this->batch_limits_exceeded( $processed_actions ) ) {
break;
}
}
$this->store->release_claim($claim);
$this->monitor->detach();
$this->clear_caches();
return $processed_actions;
}
/**
* Running large batches can eat up memory, as WP adds data to its object cache.
*
* If using a persistent object store, this has the side effect of flushing that
* as well, so this is disabled by default. To enable:
*
* add_filter( 'action_scheduler_queue_runner_flush_cache', '__return_true' );
*/
protected function clear_caches() {
if ( ! wp_using_ext_object_cache() || apply_filters( 'action_scheduler_queue_runner_flush_cache', false ) ) {
wp_cache_flush();
}
}
public function add_wp_cron_schedule( $schedules ) {
$schedules['every_minute'] = array(
'interval' => 60, // in seconds
'display' => __( 'Every minute', 'action-scheduler' ),
);
return $schedules;
}
}

View File

@@ -1,62 +0,0 @@
<?php
/**
* Class ActionScheduler_Versions
*/
class ActionScheduler_Versions {
/**
* @var ActionScheduler_Versions
*/
private static $instance = NULL;
private $versions = array();
public function register( $version_string, $initialization_callback ) {
if ( isset($this->versions[$version_string]) ) {
return FALSE;
}
$this->versions[$version_string] = $initialization_callback;
return TRUE;
}
public function get_versions() {
return $this->versions;
}
public function latest_version() {
$keys = array_keys($this->versions);
if ( empty($keys) ) {
return false;
}
uasort( $keys, 'version_compare' );
return end($keys);
}
public function latest_version_callback() {
$latest = $this->latest_version();
if ( empty($latest) || !isset($this->versions[$latest]) ) {
return '__return_null';
}
return $this->versions[$latest];
}
/**
* @return ActionScheduler_Versions
* @codeCoverageIgnore
*/
public static function instance() {
if ( empty(self::$instance) ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* @codeCoverageIgnore
*/
public static function initialize_latest_version() {
$self = self::instance();
call_user_func($self->latest_version_callback());
}
}

View File

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

@@ -1,147 +0,0 @@
<?php
/**
* Class ActionScheduler_wcSystemStatus
*/
class ActionScheduler_wcSystemStatus {
/**
* The active data stores
*
* @var ActionScheduler_Store
*/
protected $store;
function __construct( $store ) {
$this->store = $store;
}
/**
* Display action data, including number of actions grouped by status and the oldest & newest action in each status.
*
* Helpful to identify issues, like a clogged queue.
*/
public function render() {
$action_counts = $this->store->action_counts();
$status_labels = $this->store->get_status_labels();
$oldest_and_newest = $this->get_oldest_and_newest( array_keys( $status_labels ) );
$this->get_template( $status_labels, $action_counts, $oldest_and_newest );
}
/**
* Get oldest and newest scheduled dates for a given set of statuses.
*
* @param array $status_keys Set of statuses to find oldest & newest action for.
* @return array
*/
protected function get_oldest_and_newest( $status_keys ) {
$oldest_and_newest = array();
foreach ( $status_keys as $status ) {
$oldest_and_newest[ $status ] = array(
'oldest' => '&ndash;',
'newest' => '&ndash;',
);
if ( 'in-progress' === $status ) {
continue;
}
$oldest_and_newest[ $status ]['oldest'] = $this->get_action_status_date( $status, 'oldest' );
$oldest_and_newest[ $status ]['newest'] = $this->get_action_status_date( $status, 'newest' );
}
return $oldest_and_newest;
}
/**
* Get oldest or newest scheduled date for a given status.
*
* @param string $status Action status label/name string.
* @param string $date_type Oldest or Newest.
* @return DateTime
*/
protected function get_action_status_date( $status, $date_type = 'oldest' ) {
$order = 'oldest' === $date_type ? 'ASC' : 'DESC';
$action = $this->store->query_actions( array(
'claimed' => false,
'status' => $status,
'per_page' => 1,
'order' => $order,
) );
if ( ! empty( $action ) ) {
$date_object = $this->store->get_date( $action[0] );
$action_date = $date_object->format( 'Y-m-d H:i:s O' );
} else {
$action_date = '&ndash;';
}
return $action_date;
}
/**
* Get oldest or newest scheduled date for a given status.
*
* @param array $status_labels Set of statuses to find oldest & newest action for.
* @param array $action_counts Number of actions grouped by status.
* @param array $oldest_and_newest Date of the oldest and newest action with each status.
*/
protected function get_template( $status_labels, $action_counts, $oldest_and_newest ) {
?>
<table class="wc_status_table widefat" cellspacing="0">
<thead>
<tr>
<th colspan="5" data-export-label="Action Scheduler"><h2><?php esc_html_e( 'Action Scheduler', 'action-scheduler' ); ?><?php echo wc_help_tip( esc_html__( 'This section shows scheduled action counts.', 'action-scheduler' ) ); ?></h2></th>
</tr>
<tr>
<td><strong><?php esc_html_e( 'Action Status', 'action-scheduler' ); ?></strong></td>
<td class="help">&nbsp;</td>
<td><strong><?php esc_html_e( 'Count', 'action-scheduler' ); ?></strong></td>
<td><strong><?php esc_html_e( 'Oldest Scheduled Date', 'action-scheduler' ); ?></strong></td>
<td><strong><?php esc_html_e( 'Newest Scheduled Date', 'action-scheduler' ); ?></strong></td>
</tr>
</thead>
<tbody>
<?php
foreach ( $action_counts as $status => $count ) {
// WC uses the 3rd column for export, so we need to display more data in that (hidden when viewed as part of the table) and add an empty 2nd column.
printf(
'<tr><td>%1$s</td><td>&nbsp;</td><td>%2$s<span style="display: none;">, Oldest: %3$s, Newest: %4$s</span></td><td>%3$s</td><td>%4$s</td></tr>',
esc_html( $status_labels[ $status ] ),
number_format_i18n( $count ),
$oldest_and_newest[ $status ]['oldest'],
$oldest_and_newest[ $status ]['newest']
);
}
?>
</tbody>
</table>
<?php
}
/**
* is triggered when invoking inaccessible methods in an object context.
*
* @param string $name
* @param array $arguments
*
* @return mixed
* @link https://php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
*/
public function __call( $name, $arguments ) {
switch ( $name ) {
case 'print':
_deprecated_function( __CLASS__ . '::print()', '2.2.4', __CLASS__ . '::render()' );
return call_user_func_array( array( $this, 'render' ), $arguments );
}
return null;
}
}

View File

@@ -1,197 +0,0 @@
<?php
use Action_Scheduler\WP_CLI\ProgressBar;
/**
* WP CLI Queue runner.
*
* This class can only be called from within a WP CLI instance.
*/
class ActionScheduler_WPCLI_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
/** @var array */
protected $actions;
/** @var ActionScheduler_ActionClaim */
protected $claim;
/** @var \cli\progress\Bar */
protected $progress_bar;
/**
* ActionScheduler_WPCLI_QueueRunner constructor.
*
* @param ActionScheduler_Store $store
* @param ActionScheduler_FatalErrorMonitor $monitor
* @param ActionScheduler_QueueCleaner $cleaner
*
* @throws Exception When this is not run within WP CLI
*/
public function __construct( ActionScheduler_Store $store = null, ActionScheduler_FatalErrorMonitor $monitor = null, ActionScheduler_QueueCleaner $cleaner = null ) {
if ( ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
/* translators: %s php class name */
throw new Exception( sprintf( __( 'The %s class can only be run within WP CLI.', 'action-scheduler' ), __CLASS__ ) );
}
parent::__construct( $store, $monitor, $cleaner );
}
/**
* Set up the Queue before processing.
*
* @author Jeremy Pry
*
* @param int $batch_size The batch size to process.
* @param array $hooks The hooks being used to filter the actions claimed in this batch.
* @param string $group The group of actions to claim with this batch.
* @param bool $force Whether to force running even with too many concurrent processes.
*
* @return int The number of actions that will be run.
* @throws \WP_CLI\ExitException When there are too many concurrent batches.
*/
public function setup( $batch_size, $hooks = array(), $group = '', $force = false ) {
$this->run_cleanup();
$this->add_hooks();
// Check to make sure there aren't too many concurrent processes running.
if ( $this->has_maximum_concurrent_batches() ) {
if ( $force ) {
WP_CLI::warning( __( 'There are too many concurrent batches, but the run is forced to continue.', 'action-scheduler' ) );
} else {
WP_CLI::error( __( 'There are too many concurrent batches.', 'action-scheduler' ) );
}
}
// Stake a claim and store it.
$this->claim = $this->store->stake_claim( $batch_size, null, $hooks, $group );
$this->monitor->attach( $this->claim );
$this->actions = $this->claim->get_actions();
return count( $this->actions );
}
/**
* Add our hooks to the appropriate actions.
*
* @author Jeremy Pry
*/
protected function add_hooks() {
add_action( 'action_scheduler_before_execute', array( $this, 'before_execute' ) );
add_action( 'action_scheduler_after_execute', array( $this, 'after_execute' ), 10, 2 );
add_action( 'action_scheduler_failed_execution', array( $this, 'action_failed' ), 10, 2 );
}
/**
* Set up the WP CLI progress bar.
*
* @author Jeremy Pry
*/
protected function setup_progress_bar() {
$count = count( $this->actions );
$this->progress_bar = new ProgressBar(
/* translators: %d: amount of actions */
sprintf( _n( 'Running %d action', 'Running %d actions', $count, 'action-scheduler' ), number_format_i18n( $count ) ),
$count
);
}
/**
* Process actions in the queue.
*
* @author Jeremy Pry
*
* @param string $context Optional runner context. Default 'WP CLI'.
*
* @return int The number of actions processed.
*/
public function run( $context = 'WP CLI' ) {
do_action( 'action_scheduler_before_process_queue' );
$this->setup_progress_bar();
foreach ( $this->actions as $action_id ) {
// Error if we lost the claim.
if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $this->claim->get_id() ) ) ) {
WP_CLI::warning( __( 'The claim has been lost. Aborting current batch.', 'action-scheduler' ) );
break;
}
$this->process_action( $action_id, $context );
$this->progress_bar->tick();
}
$completed = $this->progress_bar->current();
$this->progress_bar->finish();
$this->store->release_claim( $this->claim );
do_action( 'action_scheduler_after_process_queue' );
return $completed;
}
/**
* Handle WP CLI message when the action is starting.
*
* @author Jeremy Pry
*
* @param $action_id
*/
public function before_execute( $action_id ) {
/* translators: %s refers to the action ID */
WP_CLI::log( sprintf( __( 'Started processing action %s', 'action-scheduler' ), $action_id ) );
}
/**
* Handle WP CLI message when the action has completed.
*
* @author Jeremy Pry
*
* @param int $action_id
* @param null|ActionScheduler_Action $action The instance of the action. Default to null for backward compatibility.
*/
public function after_execute( $action_id, $action = null ) {
// backward compatibility
if ( null === $action ) {
$action = $this->store->fetch_action( $action_id );
}
/* translators: 1: action ID 2: hook name */
WP_CLI::log( sprintf( __( 'Completed processing action %1$s with hook: %2$s', 'action-scheduler' ), $action_id, $action->get_hook() ) );
}
/**
* Handle WP CLI message when the action has failed.
*
* @author Jeremy Pry
*
* @param int $action_id
* @param Exception $exception
* @throws \WP_CLI\ExitException With failure message.
*/
public function action_failed( $action_id, $exception ) {
WP_CLI::error(
/* translators: 1: action ID 2: exception message */
sprintf( __( 'Error processing action %1$s: %2$s', 'action-scheduler' ), $action_id, $exception->getMessage() ),
false
);
}
/**
* Sleep and help avoid hitting memory limit
*
* @param int $sleep_time Amount of seconds to sleep
* @deprecated 3.0.0
*/
protected function stop_the_insanity( $sleep_time = 0 ) {
_deprecated_function( 'ActionScheduler_WPCLI_QueueRunner::stop_the_insanity', '3.0.0', 'ActionScheduler_DataController::free_memory' );
ActionScheduler_DataController::free_memory();
}
/**
* Maybe trigger the stop_the_insanity() method to free up memory.
*/
protected function maybe_stop_the_insanity() {
// The value returned by progress_bar->current() might be padded. Remove padding, and convert to int.
$current_iteration = intval( trim( $this->progress_bar->current() ) );
if ( 0 === $current_iteration % 50 ) {
$this->stop_the_insanity();
}
}
}

View File

@@ -1,158 +0,0 @@
<?php
/**
* Commands for Action Scheduler.
*/
class ActionScheduler_WPCLI_Scheduler_command extends WP_CLI_Command {
/**
* Run the Action Scheduler
*
* ## OPTIONS
*
* [--batch-size=<size>]
* : The maximum number of actions to run. Defaults to 100.
*
* [--batches=<size>]
* : Limit execution to a number of batches. Defaults to 0, meaning batches will continue being executed until all actions are complete.
*
* [--cleanup-batch-size=<size>]
* : The maximum number of actions to clean up. Defaults to the value of --batch-size.
*
* [--hooks=<hooks>]
* : Only run actions with the specified hook. Omitting this option runs actions with any hook. Define multiple hooks as a comma separated string (without spaces), e.g. `--hooks=hook_one,hook_two,hook_three`
*
* [--group=<group>]
* : Only run actions from the specified group. Omitting this option runs actions from all groups.
*
* [--free-memory-on=<count>]
* : The number of actions to process between freeing memory. 0 disables freeing memory. Default 50.
*
* [--pause=<seconds>]
* : The number of seconds to pause when freeing memory. Default no pause.
*
* [--force]
* : Whether to force execution despite the maximum number of concurrent processes being exceeded.
*
* @param array $args Positional arguments.
* @param array $assoc_args Keyed arguments.
* @throws \WP_CLI\ExitException When an error occurs.
*
* @subcommand run
*/
public function run( $args, $assoc_args ) {
// Handle passed arguments.
$batch = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batch-size', 100 ) );
$batches = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'batches', 0 ) );
$clean = absint( \WP_CLI\Utils\get_flag_value( $assoc_args, 'cleanup-batch-size', $batch ) );
$hooks = explode( ',', WP_CLI\Utils\get_flag_value( $assoc_args, 'hooks', '' ) );
$hooks = array_filter( array_map( 'trim', $hooks ) );
$group = \WP_CLI\Utils\get_flag_value( $assoc_args, 'group', '' );
$free_on = \WP_CLI\Utils\get_flag_value( $assoc_args, 'free-memory-on', '' );
$sleep = \WP_CLI\Utils\get_flag_value( $assoc_args, 'pause', '' );
$force = \WP_CLI\Utils\get_flag_value( $assoc_args, 'force', false );
ActionScheduler_DataController::set_free_ticks( $free_on );
ActionScheduler_DataController::set_sleep_time( $sleep );
$batches_completed = 0;
$actions_completed = 0;
$unlimited = $batches === 0;
try {
// Custom queue cleaner instance.
$cleaner = new ActionScheduler_QueueCleaner( null, $clean );
// Get the queue runner instance
$runner = new ActionScheduler_WPCLI_QueueRunner( null, null, $cleaner );
// Determine how many tasks will be run in the first batch.
$total = $runner->setup( $batch, $hooks, $group, $force );
// Run actions for as long as possible.
while ( $total > 0 ) {
$this->print_total_actions( $total );
$actions_completed += $runner->run();
$batches_completed++;
// Maybe set up tasks for the next batch.
$total = ( $unlimited || $batches_completed < $batches ) ? $runner->setup( $batch, $hooks, $group, $force ) : 0;
}
} catch ( Exception $e ) {
$this->print_error( $e );
}
$this->print_total_batches( $batches_completed );
$this->print_success( $actions_completed );
}
/**
* Print WP CLI message about how many actions are about to be processed.
*
* @author Jeremy Pry
*
* @param int $total
*/
protected function print_total_actions( $total ) {
WP_CLI::log(
sprintf(
/* translators: %d refers to how many scheduled taks were found to run */
_n( 'Found %d scheduled task', 'Found %d scheduled tasks', $total, 'action-scheduler' ),
number_format_i18n( $total )
)
);
}
/**
* Print WP CLI message about how many batches of actions were processed.
*
* @author Jeremy Pry
*
* @param int $batches_completed
*/
protected function print_total_batches( $batches_completed ) {
WP_CLI::log(
sprintf(
/* translators: %d refers to the total number of batches executed */
_n( '%d batch executed.', '%d batches executed.', $batches_completed, 'action-scheduler' ),
number_format_i18n( $batches_completed )
)
);
}
/**
* Convert an exception into a WP CLI error.
*
* @author Jeremy Pry
*
* @param Exception $e The error object.
*
* @throws \WP_CLI\ExitException
*/
protected function print_error( Exception $e ) {
WP_CLI::error(
sprintf(
/* translators: %s refers to the exception error message */
__( 'There was an error running the action scheduler: %s', 'action-scheduler' ),
$e->getMessage()
)
);
}
/**
* Print a success message with the number of completed actions.
*
* @author Jeremy Pry
*
* @param int $actions_completed
*/
protected function print_success( $actions_completed ) {
WP_CLI::success(
sprintf(
/* translators: %d refers to the total number of taskes completed */
_n( '%d scheduled task completed.', '%d scheduled tasks completed.', $actions_completed, 'action-scheduler' ),
number_format_i18n( $actions_completed )
)
);
}
}

View File

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

View File

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

View File

@@ -1,269 +0,0 @@
<?php
use Action_Scheduler\WP_CLI\Migration_Command;
use Action_Scheduler\Migration\Controller;
/**
* Class ActionScheduler
* @codeCoverageIgnore
*/
abstract class ActionScheduler {
private static $plugin_file = '';
/** @var ActionScheduler_ActionFactory */
private static $factory = NULL;
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

@@ -1,674 +0,0 @@
<?php
if ( ! class_exists( 'WP_List_Table' ) ) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
/**
* Action Scheduler Abstract List Table class
*
* This abstract class enhances WP_List_Table making it ready to use.
*
* By extending this class we can focus on describing how our table looks like,
* which columns needs to be shown, filter, ordered by and more and forget about the details.
*
* This class supports:
* - Bulk actions
* - Search
* - Sortable columns
* - Automatic translations of the columns
*
* @codeCoverageIgnore
* @since 2.0.0
*/
abstract class ActionScheduler_Abstract_ListTable extends WP_List_Table {
/**
* The table name
*/
protected $table_name;
/**
* Package name, used to get options from WP_List_Table::get_items_per_page.
*/
protected $package;
/**
* How many items do we render per page?
*/
protected $items_per_page = 10;
/**
* Enables search in this table listing. If this array
* is empty it means the listing is not searchable.
*/
protected $search_by = array();
/**
* Columns to show in the table listing. It is a key => value pair. The
* key must much the table column name and the value is the label, which is
* automatically translated.
*/
protected $columns = array();
/**
* Defines the row-actions. It expects an array where the key
* is the column name and the value is an array of actions.
*
* The array of actions are key => value, where key is the method name
* (with the prefix row_action_<key>) and the value is the label
* and title.
*/
protected $row_actions = array();
/**
* The Primary key of our table
*/
protected $ID = 'ID';
/**
* Enables sorting, it expects an array
* of columns (the column names are the values)
*/
protected $sort_by = array();
protected $filter_by = array();
/**
* @var array The status name => count combinations for this table's items. Used to display status filters.
*/
protected $status_counts = array();
/**
* @var array Notices to display when loading the table. Array of arrays of form array( 'class' => {updated|error}, 'message' => 'This is the notice text display.' ).
*/
protected $admin_notices = array();
/**
* @var string Localised string displayed in the <h1> element above the able.
*/
protected $table_header;
/**
* Enables bulk actions. It must be an array where the key is the action name
* and the value is the label (which is translated automatically). It is important
* to notice that it will check that the method exists (`bulk_$name`) and will throw
* an exception if it does not exists.
*
* This class will automatically check if the current request has a bulk action, will do the
* validations and afterwards will execute the bulk method, with two arguments. The first argument
* is the array with primary keys, the second argument is a string with a list of the primary keys,
* escaped and ready to use (with `IN`).
*/
protected $bulk_actions = array();
/**
* Makes translation easier, it basically just wraps
* `_x` with some default (the package name).
*
* @deprecated 3.0.0
*/
protected function translate( $text, $context = '' ) {
return $text;
}
/**
* Reads `$this->bulk_actions` and returns an array that WP_List_Table understands. It
* also validates that the bulk method handler exists. It throws an exception because
* this is a library meant for developers and missing a bulk method is a development-time error.
*/
protected function get_bulk_actions() {
$actions = array();
foreach ( $this->bulk_actions as $action => $label ) {
if ( ! is_callable( array( $this, 'bulk_' . $action ) ) ) {
throw new RuntimeException( "The bulk action $action does not have a callback method" );
}
$actions[ $action ] = $label;
}
return $actions;
}
/**
* Checks if the current request has a bulk action. If that is the case it will validate and will
* execute the bulk method handler. Regardless if the action is valid or not it will redirect to
* the previous page removing the current arguments that makes this request a bulk action.
*/
protected function process_bulk_action() {
global $wpdb;
// Detect when a bulk action is being triggered.
$action = $this->current_action();
if ( ! $action ) {
return;
}
check_admin_referer( 'bulk-' . $this->_args['plural'] );
$method = 'bulk_' . $action;
if ( array_key_exists( $action, $this->bulk_actions ) && is_callable( array( $this, $method ) ) && ! empty( $_GET['ID'] ) && is_array( $_GET['ID'] ) ) {
$ids_sql = '(' . implode( ',', array_fill( 0, count( $_GET['ID'] ), '%s' ) ) . ')';
$this->$method( $_GET['ID'], $wpdb->prepare( $ids_sql, $_GET['ID'] ) );
}
wp_redirect( remove_query_arg(
array( '_wp_http_referer', '_wpnonce', 'ID', 'action', 'action2' ),
wp_unslash( $_SERVER['REQUEST_URI'] )
) );
exit;
}
/**
* Default code for deleting entries. We trust ids_sql because it is
* validated already by process_bulk_action()
*/
protected function bulk_delete( array $ids, $ids_sql ) {
global $wpdb;
$wpdb->query( "DELETE FROM {$this->table_name} WHERE {$this->ID} IN $ids_sql" );
}
/**
* Prepares the _column_headers property which is used by WP_Table_List at rendering.
* It merges the columns and the sortable columns.
*/
protected function prepare_column_headers() {
$this->_column_headers = array(
$this->get_columns(),
array(),
$this->get_sortable_columns(),
);
}
/**
* Reads $this->sort_by and returns the columns name in a format that WP_Table_List
* expects
*/
public function get_sortable_columns() {
$sort_by = array();
foreach ( $this->sort_by as $column ) {
$sort_by[ $column ] = array( $column, true );
}
return $sort_by;
}
/**
* Returns the columns names for rendering. It adds a checkbox for selecting everything
* as the first column
*/
public function get_columns() {
$columns = array_merge(
array( 'cb' => '<input type="checkbox" />' ),
$this->columns
);
return $columns;
}
/**
* Get prepared LIMIT clause for items query
*
* @global wpdb $wpdb
*
* @return string Prepared LIMIT clause for items query.
*/
protected function get_items_query_limit() {
global $wpdb;
$per_page = $this->get_items_per_page( $this->package . '_items_per_page', $this->items_per_page );
return $wpdb->prepare( 'LIMIT %d', $per_page );
}
/**
* Returns the number of items to offset/skip for this current view.
*
* @return int
*/
protected function get_items_offset() {
$per_page = $this->get_items_per_page( $this->package . '_items_per_page', $this->items_per_page );
$current_page = $this->get_pagenum();
if ( 1 < $current_page ) {
$offset = $per_page * ( $current_page - 1 );
} else {
$offset = 0;
}
return $offset;
}
/**
* Get prepared OFFSET clause for items query
*
* @global wpdb $wpdb
*
* @return string Prepared OFFSET clause for items query.
*/
protected function get_items_query_offset() {
global $wpdb;
return $wpdb->prepare( 'OFFSET %d', $this->get_items_offset() );
}
/**
* Prepares the ORDER BY sql statement. It uses `$this->sort_by` to know which
* columns are sortable. This requests validates the orderby $_GET parameter is a valid
* column and sortable. It will also use order (ASC|DESC) using DESC by default.
*/
protected function get_items_query_order() {
if ( empty( $this->sort_by ) ) {
return '';
}
$orderby = esc_sql( $this->get_request_orderby() );
$order = esc_sql( $this->get_request_order() );
return "ORDER BY {$orderby} {$order}";
}
/**
* Return the sortable column specified for this request to order the results by, if any.
*
* @return string
*/
protected function get_request_orderby() {
$valid_sortable_columns = array_values( $this->sort_by );
if ( ! empty( $_GET['orderby'] ) && in_array( $_GET['orderby'], $valid_sortable_columns ) ) {
$orderby = sanitize_text_field( $_GET['orderby'] );
} else {
$orderby = $valid_sortable_columns[0];
}
return $orderby;
}
/**
* Return the sortable column order specified for this request.
*
* @return string
*/
protected function get_request_order() {
if ( ! empty( $_GET['order'] ) && 'desc' === strtolower( $_GET['order'] ) ) {
$order = 'DESC';
} else {
$order = 'ASC';
}
return $order;
}
/**
* Return the status filter for this request, if any.
*
* @return string
*/
protected function get_request_status() {
$status = ( ! empty( $_GET['status'] ) ) ? $_GET['status'] : '';
return $status;
}
/**
* Return the search filter for this request, if any.
*
* @return string
*/
protected function get_request_search_query() {
$search_query = ( ! empty( $_GET['s'] ) ) ? $_GET['s'] : '';
return $search_query;
}
/**
* Process and return the columns name. This is meant for using with SQL, this means it
* always includes the primary key.
*
* @return array
*/
protected function get_table_columns() {
$columns = array_keys( $this->columns );
if ( ! in_array( $this->ID, $columns ) ) {
$columns[] = $this->ID;
}
return $columns;
}
/**
* Check if the current request is doing a "full text" search. If that is the case
* prepares the SQL to search texts using LIKE.
*
* If the current request does not have any search or if this list table does not support
* that feature it will return an empty string.
*
* TODO:
* - Improve search doing LIKE by word rather than by phrases.
*
* @return string
*/
protected function get_items_query_search() {
global $wpdb;
if ( empty( $_GET['s'] ) || empty( $this->search_by ) ) {
return '';
}
$filter = array();
foreach ( $this->search_by as $column ) {
$filter[] = $wpdb->prepare('`' . $column . '` like "%%s%"', $wpdb->esc_like( $_GET['s'] ));
}
return implode( ' OR ', $filter );
}
/**
* Prepares the SQL to filter rows by the options defined at `$this->filter_by`. Before trusting
* any data sent by the user it validates that it is a valid option.
*/
protected function get_items_query_filters() {
global $wpdb;
if ( ! $this->filter_by || empty( $_GET['filter_by'] ) || ! is_array( $_GET['filter_by'] ) ) {
return '';
}
$filter = array();
foreach ( $this->filter_by as $column => $options ) {
if ( empty( $_GET['filter_by'][ $column ] ) || empty( $options[ $_GET['filter_by'][ $column ] ] ) ) {
continue;
}
$filter[] = $wpdb->prepare( "`$column` = %s", $_GET['filter_by'][ $column ] );
}
return implode( ' AND ', $filter );
}
/**
* Prepares the data to feed WP_Table_List.
*
* This has the core for selecting, sorting and filting data. To keep the code simple
* its logic is split among many methods (get_items_query_*).
*
* Beside populating the items this function will also count all the records that matches
* the filtering criteria and will do fill the pagination variables.
*/
public function prepare_items() {
global $wpdb;
$this->process_bulk_action();
$this->process_row_actions();
if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
// _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter
wp_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
exit;
}
$this->prepare_column_headers();
$limit = $this->get_items_query_limit();
$offset = $this->get_items_query_offset();
$order = $this->get_items_query_order();
$where = array_filter(array(
$this->get_items_query_search(),
$this->get_items_query_filters(),
));
$columns = '`' . implode( '`, `', $this->get_table_columns() ) . '`';
if ( ! empty( $where ) ) {
$where = 'WHERE ('. implode( ') AND (', $where ) . ')';
} else {
$where = '';
}
$sql = "SELECT $columns FROM {$this->table_name} {$where} {$order} {$limit} {$offset}";
$this->set_items( $wpdb->get_results( $sql, ARRAY_A ) );
$query_count = "SELECT COUNT({$this->ID}) FROM {$this->table_name} {$where}";
$total_items = $wpdb->get_var( $query_count );
$per_page = $this->get_items_per_page( $this->package . '_items_per_page', $this->items_per_page );
$this->set_pagination_args( array(
'total_items' => $total_items,
'per_page' => $per_page,
'total_pages' => ceil( $total_items / $per_page ),
) );
}
public function extra_tablenav( $which ) {
if ( ! $this->filter_by || 'top' !== $which ) {
return;
}
echo '<div class="alignleft actions">';
foreach ( $this->filter_by as $id => $options ) {
$default = ! empty( $_GET['filter_by'][ $id ] ) ? $_GET['filter_by'][ $id ] : '';
if ( empty( $options[ $default ] ) ) {
$default = '';
}
echo '<select name="filter_by[' . esc_attr( $id ) . ']" class="first" id="filter-by-' . esc_attr( $id ) . '">';
foreach ( $options as $value => $label ) {
echo '<option value="' . esc_attr( $value ) . '" ' . esc_html( $value == $default ? 'selected' : '' ) .'>'
. esc_html( $label )
. '</option>';
}
echo '</select>';
}
submit_button( esc_html__( 'Filter', 'action-scheduler' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
echo '</div>';
}
/**
* Set the data for displaying. It will attempt to unserialize (There is a chance that some columns
* are serialized). This can be override in child classes for futher data transformation.
*/
protected function set_items( array $items ) {
$this->items = array();
foreach ( $items as $item ) {
$this->items[ $item[ $this->ID ] ] = array_map( 'maybe_unserialize', $item );
}
}
/**
* Renders the checkbox for each row, this is the first column and it is named ID regardless
* of how the primary key is named (to keep the code simpler). The bulk actions will do the proper
* name transformation though using `$this->ID`.
*/
public function column_cb( $row ) {
return '<input name="ID[]" type="checkbox" value="' . esc_attr( $row[ $this->ID ] ) .'" />';
}
/**
* Renders the row-actions.
*
* This method renders the action menu, it reads the definition from the $row_actions property,
* and it checks that the row action method exists before rendering it.
*
* @param array $row Row to render
* @param $column_name Current row
* @return
*/
protected function maybe_render_actions( $row, $column_name ) {
if ( empty( $this->row_actions[ $column_name ] ) ) {
return;
}
$row_id = $row[ $this->ID ];
$actions = '<div class="row-actions">';
$action_count = 0;
foreach ( $this->row_actions[ $column_name ] as $action_key => $action ) {
$action_count++;
if ( ! method_exists( $this, 'row_action_' . $action_key ) ) {
continue;
}
$action_link = ! empty( $action['link'] ) ? $action['link'] : add_query_arg( array( 'row_action' => $action_key, 'row_id' => $row_id, 'nonce' => wp_create_nonce( $action_key . '::' . $row_id ) ) );
$span_class = ! empty( $action['class'] ) ? $action['class'] : $action_key;
$separator = ( $action_count < count( $this->row_actions[ $column_name ] ) ) ? ' | ' : '';
$actions .= sprintf( '<span class="%s">', esc_attr( $span_class ) );
$actions .= sprintf( '<a href="%1$s" title="%2$s">%3$s</a>', esc_url( $action_link ), esc_attr( $action['desc'] ), esc_html( $action['name'] ) );
$actions .= sprintf( '%s</span>', $separator );
}
$actions .= '</div>';
return $actions;
}
protected function process_row_actions() {
$parameters = array( 'row_action', 'row_id', 'nonce' );
foreach ( $parameters as $parameter ) {
if ( empty( $_REQUEST[ $parameter ] ) ) {
return;
}
}
$method = 'row_action_' . $_REQUEST['row_action'];
if ( $_REQUEST['nonce'] === wp_create_nonce( $_REQUEST[ 'row_action' ] . '::' . $_REQUEST[ 'row_id' ] ) && method_exists( $this, $method ) ) {
$this->$method( $_REQUEST['row_id'] );
}
wp_redirect( remove_query_arg(
array( 'row_id', 'row_action', 'nonce' ),
wp_unslash( $_SERVER['REQUEST_URI'] )
) );
exit;
}
/**
* Default column formatting, it will escape everythig for security.
*/
public function column_default( $item, $column_name ) {
$column_html = esc_html( $item[ $column_name ] );
$column_html .= $this->maybe_render_actions( $item, $column_name );
return $column_html;
}
/**
* Display the table heading and search query, if any
*/
protected function display_header() {
echo '<h1 class="wp-heading-inline">' . esc_attr( $this->table_header ) . '</h1>';
if ( $this->get_request_search_query() ) {
/* translators: %s: search query */
echo '<span class="subtitle">' . esc_attr( sprintf( __( 'Search results for "%s"', 'action-scheduler' ), $this->get_request_search_query() ) ) . '</span>';
}
echo '<hr class="wp-header-end">';
}
/**
* Display the table heading and search query, if any
*/
protected function display_admin_notices() {
foreach ( $this->admin_notices as $notice ) {
echo '<div id="message" class="' . $notice['class'] . '">';
echo ' <p>' . wp_kses_post( $notice['message'] ) . '</p>';
echo '</div>';
}
}
/**
* Prints the available statuses so the user can click to filter.
*/
protected function display_filter_by_status() {
$status_list_items = array();
$request_status = $this->get_request_status();
// Helper to set 'all' filter when not set on status counts passed in
if ( ! isset( $this->status_counts['all'] ) ) {
$this->status_counts = array( 'all' => array_sum( $this->status_counts ) ) + $this->status_counts;
}
foreach ( $this->status_counts as $status_name => $count ) {
if ( 0 === $count ) {
continue;
}
if ( $status_name === $request_status || ( empty( $request_status ) && 'all' === $status_name ) ) {
$status_list_item = '<li class="%1$s"><strong>%3$s</strong> (%4$d)</li>';
} else {
$status_list_item = '<li class="%1$s"><a href="%2$s">%3$s</a> (%4$d)</li>';
}
$status_filter_url = ( 'all' === $status_name ) ? remove_query_arg( 'status' ) : add_query_arg( 'status', $status_name );
$status_list_items[] = sprintf( $status_list_item, esc_attr( $status_name ), esc_url( $status_filter_url ), esc_html( ucfirst( $status_name ) ), absint( $count ) );
}
if ( $status_list_items ) {
echo '<ul class="subsubsub">';
echo implode( " | \n", $status_list_items );
echo '</ul>';
}
}
/**
* Renders the table list, we override the original class to render the table inside a form
* and to render any needed HTML (like the search box). By doing so the callee of a function can simple
* forget about any extra HTML.
*/
protected function display_table() {
echo '<form id="' . esc_attr( $this->_args['plural'] ) . '-filter" method="get">';
foreach ( $_GET as $key => $value ) {
if ( '_' === $key[0] || 'paged' === $key ) {
continue;
}
echo '<input type="hidden" name="' . esc_attr( $key ) . '" value="' . esc_attr( $value ) . '" />';
}
if ( ! empty( $this->search_by ) ) {
echo $this->search_box( $this->get_search_box_button_text(), 'plugin' ); // WPCS: XSS OK
}
parent::display();
echo '</form>';
}
/**
* Process any pending actions.
*/
public function process_actions() {
$this->process_bulk_action();
$this->process_row_actions();
if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
// _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter
wp_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
exit;
}
}
/**
* Render the list table page, including header, notices, status filters and table.
*/
public function display_page() {
$this->prepare_items();
echo '<div class="wrap">';
$this->display_header();
$this->display_admin_notices();
$this->display_filter_by_status();
$this->display_table();
echo '</div>';
}
/**
* Get the text to display in the search box on the list table.
*/
protected function get_search_box_placeholder() {
return esc_html__( 'Search', 'action-scheduler' );
}
}

View File

@@ -1,232 +0,0 @@
<?php
/**
* Abstract class with common Queue Cleaner functionality.
*/
abstract class ActionScheduler_Abstract_QueueRunner extends ActionScheduler_Abstract_QueueRunner_Deprecated {
/** @var ActionScheduler_QueueCleaner */
protected $cleaner;
/** @var ActionScheduler_FatalErrorMonitor */
protected $monitor;
/** @var ActionScheduler_Store */
protected $store;
/**
* The created time.
*
* Represents when the queue runner was constructed and used when calculating how long a PHP request has been running.
* For this reason it should be as close as possible to the PHP request start time.
*
* @var int
*/
private $created_time;
/**
* ActionScheduler_Abstract_QueueRunner constructor.
*
* @param ActionScheduler_Store $store
* @param ActionScheduler_FatalErrorMonitor $monitor
* @param ActionScheduler_QueueCleaner $cleaner
*/
public function __construct( ActionScheduler_Store $store = null, ActionScheduler_FatalErrorMonitor $monitor = null, ActionScheduler_QueueCleaner $cleaner = null ) {
$this->created_time = microtime( true );
$this->store = $store ? $store : ActionScheduler_Store::instance();
$this->monitor = $monitor ? $monitor : new ActionScheduler_FatalErrorMonitor( $this->store );
$this->cleaner = $cleaner ? $cleaner : new ActionScheduler_QueueCleaner( $this->store );
}
/**
* Process an individual action.
*
* @param int $action_id The action ID to process.
* @param string $context Optional identifer for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
* Generally, this should be capitalised and not localised as it's a proper noun.
*/
public function process_action( $action_id, $context = '' ) {
try {
do_action( 'action_scheduler_before_execute', $action_id, $context );
if ( ActionScheduler_Store::STATUS_PENDING !== $this->store->get_status( $action_id ) ) {
do_action( 'action_scheduler_execution_ignored', $action_id, $context );
return;
}
$action = $this->store->fetch_action( $action_id );
$this->store->log_execution( $action_id );
$action->execute();
do_action( 'action_scheduler_after_execute', $action_id, $action, $context );
$this->store->mark_complete( $action_id );
} catch ( Exception $e ) {
$this->store->mark_failure( $action_id );
do_action( 'action_scheduler_failed_execution', $action_id, $e, $context );
}
if ( isset( $action ) && is_a( $action, 'ActionScheduler_Action' ) && $action->get_schedule()->is_recurring() ) {
$this->schedule_next_instance( $action, $action_id );
}
}
/**
* Schedule the next instance of the action if necessary.
*
* @param ActionScheduler_Action $action
* @param int $action_id
*/
protected function schedule_next_instance( ActionScheduler_Action $action, $action_id ) {
try {
ActionScheduler::factory()->repeat( $action );
} catch ( Exception $e ) {
do_action( 'action_scheduler_failed_to_schedule_next_instance', $action_id, $e, $action );
}
}
/**
* Run the queue cleaner.
*
* @author Jeremy Pry
*/
protected function run_cleanup() {
$this->cleaner->clean( 10 * $this->get_time_limit() );
}
/**
* Get the number of concurrent batches a runner allows.
*
* @return int
*/
public function get_allowed_concurrent_batches() {
return apply_filters( 'action_scheduler_queue_runner_concurrent_batches', 1 );
}
/**
* Check if the number of allowed concurrent batches is met or exceeded.
*
* @return bool
*/
public function has_maximum_concurrent_batches() {
return $this->store->get_claim_count() >= $this->get_allowed_concurrent_batches();
}
/**
* Get the maximum number of seconds a batch can run for.
*
* @return int The number of seconds.
*/
protected function get_time_limit() {
$time_limit = 30;
// Apply deprecated filter from deprecated get_maximum_execution_time() method
if ( has_filter( 'action_scheduler_maximum_execution_time' ) ) {
_deprecated_function( 'action_scheduler_maximum_execution_time', '2.1.1', 'action_scheduler_queue_runner_time_limit' );
$time_limit = apply_filters( 'action_scheduler_maximum_execution_time', $time_limit );
}
return absint( apply_filters( 'action_scheduler_queue_runner_time_limit', $time_limit ) );
}
/**
* Get the number of seconds the process has been running.
*
* @return int The number of seconds.
*/
protected function get_execution_time() {
$execution_time = microtime( true ) - $this->created_time;
// Get the CPU time if the hosting environment uses it rather than wall-clock time to calculate a process's execution time.
if ( function_exists( 'getrusage' ) && apply_filters( 'action_scheduler_use_cpu_execution_time', defined( 'PANTHEON_ENVIRONMENT' ) ) ) {
$resource_usages = getrusage();
if ( isset( $resource_usages['ru_stime.tv_usec'], $resource_usages['ru_stime.tv_usec'] ) ) {
$execution_time = $resource_usages['ru_stime.tv_sec'] + ( $resource_usages['ru_stime.tv_usec'] / 1000000 );
}
}
return $execution_time;
}
/**
* Check if the host's max execution time is (likely) to be exceeded if processing more actions.
*
* @param int $processed_actions The number of actions processed so far - used to determine the likelihood of exceeding the time limit if processing another action
* @return bool
*/
protected function time_likely_to_be_exceeded( $processed_actions ) {
$execution_time = $this->get_execution_time();
$max_execution_time = $this->get_time_limit();
$time_per_action = $execution_time / $processed_actions;
$estimated_time = $execution_time + ( $time_per_action * 3 );
$likely_to_be_exceeded = $estimated_time > $max_execution_time;
return apply_filters( 'action_scheduler_maximum_execution_time_likely_to_be_exceeded', $likely_to_be_exceeded, $this, $processed_actions, $execution_time, $max_execution_time );
}
/**
* Get memory limit
*
* Based on WP_Background_Process::get_memory_limit()
*
* @return int
*/
protected function get_memory_limit() {
if ( function_exists( 'ini_get' ) ) {
$memory_limit = ini_get( 'memory_limit' );
} else {
$memory_limit = '128M'; // Sensible default, and minimum required by WooCommerce
}
if ( ! $memory_limit || -1 === $memory_limit || '-1' === $memory_limit ) {
// Unlimited, set to 32GB.
$memory_limit = '32G';
}
return ActionScheduler_Compatibility::convert_hr_to_bytes( $memory_limit );
}
/**
* Memory exceeded
*
* Ensures the batch process never exceeds 90% of the maximum WordPress memory.
*
* Based on WP_Background_Process::memory_exceeded()
*
* @return bool
*/
protected function memory_exceeded() {
$memory_limit = $this->get_memory_limit() * 0.90;
$current_memory = memory_get_usage( true );
$memory_exceeded = $current_memory >= $memory_limit;
return apply_filters( 'action_scheduler_memory_exceeded', $memory_exceeded, $this );
}
/**
* See if the batch limits have been exceeded, which is when memory usage is almost at
* the maximum limit, or the time to process more actions will exceed the max time limit.
*
* Based on WC_Background_Process::batch_limits_exceeded()
*
* @param int $processed_actions The number of actions processed so far - used to determine the likelihood of exceeding the time limit if processing another action
* @return bool
*/
protected function batch_limits_exceeded( $processed_actions ) {
return $this->memory_exceeded() || $this->time_likely_to_be_exceeded( $processed_actions );
}
/**
* Process actions in the queue.
*
* @author Jeremy Pry
* @param string $context Optional identifer for the context in which this action is being processed, e.g. 'WP CLI' or 'WP Cron'
* Generally, this should be capitalised and not localised as it's a proper noun.
* @return int The number of actions processed.
*/
abstract public function run( $context = '' );
}

View File

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

View File

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

View File

@@ -1,133 +0,0 @@
<?php
/**
* Class ActionScheduler_Abstract_Schema
*
* @package Action_Scheduler
*
* @codeCoverageIgnore
*
* Utility class for creating/updating custom tables
*/
abstract class ActionScheduler_Abstract_Schema {
/**
* @var int Increment this value in derived class to trigger a schema update.
*/
protected $schema_version = 1;
/**
* @var array Names of tables that will be registered by this class.
*/
protected $tables = [];
/**
* Register tables with WordPress, and create them if needed.
*
* @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

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

View File

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

@@ -1,345 +0,0 @@
<?php
/**
* Class ActionScheduler_Store
* @codeCoverageIgnore
*/
abstract class ActionScheduler_Store extends ActionScheduler_Store_Deprecated {
const STATUS_COMPLETE = 'complete';
const STATUS_PENDING = 'pending';
const STATUS_RUNNING = 'in-progress';
const STATUS_FAILED = 'failed';
const STATUS_CANCELED = 'canceled';
const DEFAULT_CLASS = 'ActionScheduler_wpPostStore';
/** @var ActionScheduler_Store */
private static $store = NULL;
/** @var int */
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

@@ -1,152 +0,0 @@
<?php
/**
* Class ActionScheduler_TimezoneHelper
*/
abstract class ActionScheduler_TimezoneHelper {
private static $local_timezone = NULL;
/**
* Set a DateTime's timezone to the WordPress site's timezone, or a UTC offset
* if no timezone string is available.
*
* @since 2.1.0
*
* @param DateTime $date
* @return ActionScheduler_DateTime
*/
public static function set_local_timezone( DateTime $date ) {
// Accept a DateTime for easier backward compatibility, even though we require methods on ActionScheduler_DateTime
if ( ! is_a( $date, 'ActionScheduler_DateTime' ) ) {
$date = as_get_datetime_object( $date->format( 'U' ) );
}
if ( get_option( 'timezone_string' ) ) {
$date->setTimezone( new DateTimeZone( self::get_local_timezone_string() ) );
} else {
$date->setUtcOffset( self::get_local_timezone_offset() );
}
return $date;
}
/**
* Helper to retrieve the timezone string for a site until a WP core method exists
* (see https://core.trac.wordpress.org/ticket/24730).
*
* Adapted from wc_timezone_string() and https://secure.php.net/manual/en/function.timezone-name-from-abbr.php#89155.
*
* If no timezone string is set, and its not possible to match the UTC offset set for the site to a timezone
* string, then an empty string will be returned, and the UTC offset should be used to set a DateTime's
* timezone.
*
* @since 2.1.0
* @return string PHP timezone string for the site or empty if no timezone string is available.
*/
protected static function get_local_timezone_string( $reset = false ) {
// If site timezone string exists, return it.
$timezone = get_option( 'timezone_string' );
if ( $timezone ) {
return $timezone;
}
// Get UTC offset, if it isn't set then return UTC.
$utc_offset = intval( get_option( 'gmt_offset', 0 ) );
if ( 0 === $utc_offset ) {
return 'UTC';
}
// Adjust UTC offset from hours to seconds.
$utc_offset *= 3600;
// Attempt to guess the timezone string from the UTC offset.
$timezone = timezone_name_from_abbr( '', $utc_offset );
if ( $timezone ) {
return $timezone;
}
// Last try, guess timezone string manually.
foreach ( timezone_abbreviations_list() as $abbr ) {
foreach ( $abbr as $city ) {
if ( (bool) date( 'I' ) === (bool) $city['dst'] && $city['timezone_id'] && intval( $city['offset'] ) === $utc_offset ) {
return $city['timezone_id'];
}
}
}
// No timezone string
return '';
}
/**
* Get timezone offset in seconds.
*
* @since 2.1.0
* @return float
*/
protected static function get_local_timezone_offset() {
$timezone = get_option( 'timezone_string' );
if ( $timezone ) {
$timezone_object = new DateTimeZone( $timezone );
return $timezone_object->getOffset( new DateTime( 'now' ) );
} else {
return floatval( get_option( 'gmt_offset', 0 ) ) * HOUR_IN_SECONDS;
}
}
/**
* @deprecated 2.1.0
*/
public static function get_local_timezone( $reset = FALSE ) {
_deprecated_function( __FUNCTION__, '2.1.0', 'ActionScheduler_TimezoneHelper::set_local_timezone()' );
if ( $reset ) {
self::$local_timezone = NULL;
}
if ( !isset(self::$local_timezone) ) {
$tzstring = get_option('timezone_string');
if ( empty($tzstring) ) {
$gmt_offset = get_option('gmt_offset');
if ( $gmt_offset == 0 ) {
$tzstring = 'UTC';
} else {
$gmt_offset *= HOUR_IN_SECONDS;
$tzstring = timezone_name_from_abbr( '', $gmt_offset, 1 );
// If there's no timezone string, try again with no DST.
if ( false === $tzstring ) {
$tzstring = timezone_name_from_abbr( '', $gmt_offset, 0 );
}
// Try mapping to the first abbreviation we can find.
if ( false === $tzstring ) {
$is_dst = date( 'I' );
foreach ( timezone_abbreviations_list() as $abbr ) {
foreach ( $abbr as $city ) {
if ( $city['dst'] == $is_dst && $city['offset'] == $gmt_offset ) {
// If there's no valid timezone ID, keep looking.
if ( null === $city['timezone_id'] ) {
continue;
}
$tzstring = $city['timezone_id'];
break 2;
}
}
}
}
// If we still have no valid string, then fall back to UTC.
if ( false === $tzstring ) {
$tzstring = 'UTC';
}
}
}
self::$local_timezone = new DateTimeZone($tzstring);
}
return self::$local_timezone;
}
}

View File

@@ -1,75 +0,0 @@
<?php
/**
* Class ActionScheduler_Action
*/
class ActionScheduler_Action {
protected $hook = '';
protected $args = array();
/** @var ActionScheduler_Schedule */
protected $schedule = NULL;
protected $group = '';
public function __construct( $hook, array $args = array(), ActionScheduler_Schedule $schedule = NULL, $group = '' ) {
$schedule = empty( $schedule ) ? new ActionScheduler_NullSchedule() : $schedule;
$this->set_hook($hook);
$this->set_schedule($schedule);
$this->set_args($args);
$this->set_group($group);
}
public function execute() {
return do_action_ref_array($this->get_hook(), $this->get_args());
}
/**
* @param string $hook
*/
protected function set_hook( $hook ) {
$this->hook = $hook;
}
public function get_hook() {
return $this->hook;
}
protected function set_schedule( ActionScheduler_Schedule $schedule ) {
$this->schedule = $schedule;
}
/**
* @return ActionScheduler_Schedule
*/
public function get_schedule() {
return $this->schedule;
}
protected function set_args( array $args ) {
$this->args = $args;
}
public function get_args() {
return $this->args;
}
/**
* @param string $group
*/
protected function set_group( $group ) {
$this->group = $group;
}
/**
* @return string
*/
public function get_group() {
return $this->group;
}
/**
* @return bool If the action has been finished
*/
public function is_finished() {
return FALSE;
}
}

View File

@@ -1,23 +0,0 @@
<?php
/**
* Class ActionScheduler_CanceledAction
*
* Stored action which was canceled and therefore acts like a finished action but should always return a null schedule,
* regardless of schedule passed to its constructor.
*/
class ActionScheduler_CanceledAction extends ActionScheduler_FinishedAction {
/**
* @param string $hook
* @param array $args
* @param ActionScheduler_Schedule $schedule
* @param string $group
*/
public function __construct( $hook, array $args = array(), ActionScheduler_Schedule $schedule = null, $group = '' ) {
parent::__construct( $hook, $args, $schedule, $group );
if ( is_null( $schedule ) ) {
$this->set_schedule( new ActionScheduler_NullSchedule() );
}
}
}

View File

@@ -1,16 +0,0 @@
<?php
/**
* Class ActionScheduler_FinishedAction
*/
class ActionScheduler_FinishedAction extends ActionScheduler_Action {
public function execute() {
// don't execute
}
public function is_finished() {
return TRUE;
}
}

View File

@@ -1,16 +0,0 @@
<?php
/**
* Class ActionScheduler_NullAction
*/
class ActionScheduler_NullAction extends ActionScheduler_Action {
public function __construct( $hook = '', array $args = array(), ActionScheduler_Schedule $schedule = NULL ) {
$this->set_schedule( new ActionScheduler_NullSchedule() );
}
public function execute() {
// don't execute
}
}

View File

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

View File

@@ -1,803 +0,0 @@
<?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

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

@@ -1,240 +0,0 @@
<?php
/**
* Class ActionScheduler_wpCommentLogger
*/
class ActionScheduler_wpCommentLogger extends ActionScheduler_Logger {
const AGENT = 'ActionScheduler';
const TYPE = 'action_log';
/**
* @param string $action_id
* @param string $message
* @param DateTime $date
*
* @return string The log entry ID
*/
public function log( $action_id, $message, DateTime $date = NULL ) {
if ( empty($date) ) {
$date = as_get_datetime_object();
} else {
$date = as_get_datetime_object( clone $date );
}
$comment_id = $this->create_wp_comment( $action_id, $message, $date );
return $comment_id;
}
protected function create_wp_comment( $action_id, $message, DateTime $date ) {
$comment_date_gmt = $date->format('Y-m-d H:i:s');
ActionScheduler_TimezoneHelper::set_local_timezone( $date );
$comment_data = array(
'comment_post_ID' => $action_id,
'comment_date' => $date->format('Y-m-d H:i:s'),
'comment_date_gmt' => $comment_date_gmt,
'comment_author' => self::AGENT,
'comment_content' => $message,
'comment_agent' => self::AGENT,
'comment_type' => self::TYPE,
);
return wp_insert_comment($comment_data);
}
/**
* @param string $entry_id
*
* @return ActionScheduler_LogEntry
*/
public function get_entry( $entry_id ) {
$comment = $this->get_comment( $entry_id );
if ( empty($comment) || $comment->comment_type != self::TYPE ) {
return new ActionScheduler_NullLogEntry();
}
$date = as_get_datetime_object( $comment->comment_date_gmt );
ActionScheduler_TimezoneHelper::set_local_timezone( $date );
return new ActionScheduler_LogEntry( $comment->comment_post_ID, $comment->comment_content, $date );
}
/**
* @param string $action_id
*
* @return ActionScheduler_LogEntry[]
*/
public function get_logs( $action_id ) {
$status = 'all';
if ( get_post_status($action_id) == 'trash' ) {
$status = 'post-trashed';
}
$comments = get_comments(array(
'post_id' => $action_id,
'orderby' => 'comment_date_gmt',
'order' => 'ASC',
'type' => self::TYPE,
'status' => $status,
));
$logs = array();
foreach ( $comments as $c ) {
$entry = $this->get_entry( $c );
if ( !empty($entry) ) {
$logs[] = $entry;
}
}
return $logs;
}
protected function get_comment( $comment_id ) {
return get_comment( $comment_id );
}
/**
* @param WP_Comment_Query $query
*/
public function filter_comment_queries( $query ) {
foreach ( array('ID', 'parent', 'post_author', 'post_name', 'post_parent', 'type', 'post_type', 'post_id', 'post_ID') as $key ) {
if ( !empty($query->query_vars[$key]) ) {
return; // don't slow down queries that wouldn't include action_log comments anyway
}
}
$query->query_vars['action_log_filter'] = TRUE;
add_filter( 'comments_clauses', array( $this, 'filter_comment_query_clauses' ), 10, 2 );
}
/**
* @param array $clauses
* @param WP_Comment_Query $query
*
* @return array
*/
public function filter_comment_query_clauses( $clauses, $query ) {
if ( !empty($query->query_vars['action_log_filter']) ) {
$clauses['where'] .= $this->get_where_clause();
}
return $clauses;
}
/**
* Make sure Action Scheduler logs are excluded from comment feeds, which use WP_Query, not
* the WP_Comment_Query class handled by @see self::filter_comment_queries().
*
* @param string $where
* @param WP_Query $query
*
* @return string
*/
public function filter_comment_feed( $where, $query ) {
if ( is_comment_feed() ) {
$where .= $this->get_where_clause();
}
return $where;
}
/**
* Return a SQL clause to exclude Action Scheduler comments.
*
* @return string
*/
protected function get_where_clause() {
global $wpdb;
return sprintf( " AND {$wpdb->comments}.comment_type != '%s'", self::TYPE );
}
/**
* Remove action log entries from wp_count_comments()
*
* @param array $stats
* @param int $post_id
*
* @return object
*/
public function filter_comment_count( $stats, $post_id ) {
global $wpdb;
if ( 0 === $post_id ) {
$stats = $this->get_comment_count();
}
return $stats;
}
/**
* Retrieve the comment counts from our cache, or the database if the cached version isn't set.
*
* @return object
*/
protected function get_comment_count() {
global $wpdb;
$stats = get_transient( 'as_comment_count' );
if ( ! $stats ) {
$stats = array();
$count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} WHERE comment_type NOT IN('order_note','action_log') GROUP BY comment_approved", ARRAY_A );
$total = 0;
$stats = array();
$approved = array( '0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed' );
foreach ( (array) $count as $row ) {
// Don't count post-trashed toward totals
if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) {
$total += $row['num_comments'];
}
if ( isset( $approved[ $row['comment_approved'] ] ) ) {
$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
}
}
$stats['total_comments'] = $total;
$stats['all'] = $total;
foreach ( $approved as $key ) {
if ( empty( $stats[ $key ] ) ) {
$stats[ $key ] = 0;
}
}
$stats = (object) $stats;
set_transient( 'as_comment_count', $stats );
}
return $stats;
}
/**
* Delete comment count cache whenever there is new comment or the status of a comment changes. Cache
* will be regenerated next time ActionScheduler_wpCommentLogger::filter_comment_count() is called.
*/
public function delete_comment_count_cache() {
delete_transient( 'as_comment_count' );
}
/**
* @codeCoverageIgnore
*/
public function init() {
add_action( 'action_scheduler_before_process_queue', array( $this, 'disable_comment_counting' ), 10, 0 );
add_action( 'action_scheduler_after_process_queue', array( $this, 'enable_comment_counting' ), 10, 0 );
parent::init();
add_action( 'pre_get_comments', array( $this, 'filter_comment_queries' ), 10, 1 );
add_action( 'wp_count_comments', array( $this, 'filter_comment_count' ), 20, 2 ); // run after WC_Comments::wp_count_comments() to make sure we exclude order notes and action logs
add_action( 'comment_feed_where', array( $this, 'filter_comment_feed' ), 10, 2 );
// Delete comments count cache whenever there is a new comment or a comment status changes
add_action( 'wp_insert_comment', array( $this, 'delete_comment_count_cache' ) );
add_action( 'wp_set_comment_status', array( $this, 'delete_comment_count_cache' ) );
}
public function disable_comment_counting() {
wp_defer_comment_counting(true);
}
public function enable_comment_counting() {
wp_defer_comment_counting(false);
}
}

View File

@@ -1,858 +0,0 @@
<?php
/**
* Class ActionScheduler_wpPostStore
*/
class ActionScheduler_wpPostStore extends ActionScheduler_Store {
const POST_TYPE = 'scheduled-action';
const GROUP_TAXONOMY = 'action-group';
const SCHEDULE_META_KEY = '_action_manager_schedule';
const DEPENDENCIES_MET = 'as-post-store-dependencies-met';
/** @var DateTimeZone */
protected $local_timezone = NULL;
public function save_action( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ){
try {
$this->validate_action( $action );
$post_array = $this->create_post_array( $action, $scheduled_date );
$post_id = $this->save_post_array( $post_array );
$this->save_post_schedule( $post_id, $action->get_schedule() );
$this->save_action_group( $post_id, $action->get_group() );
do_action( 'action_scheduler_stored_action', $post_id );
return $post_id;
} catch ( Exception $e ) {
throw new RuntimeException( sprintf( __('Error saving action: %s', 'action-scheduler'), $e->getMessage() ), 0 );
}
}
protected function create_post_array( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
$post = array(
'post_type' => self::POST_TYPE,
'post_title' => $action->get_hook(),
'post_content' => json_encode($action->get_args()),
'post_status' => ( $action->is_finished() ? 'publish' : 'pending' ),
'post_date_gmt' => $this->get_scheduled_date_string( $action, $scheduled_date ),
'post_date' => $this->get_scheduled_date_string_local( $action, $scheduled_date ),
);
return $post;
}
protected function save_post_array( $post_array ) {
add_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 );
add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 );
$has_kses = false !== has_filter( 'content_save_pre', 'wp_filter_post_kses' );
if ( $has_kses ) {
// Prevent KSES from corrupting JSON in post_content.
kses_remove_filters();
}
$post_id = wp_insert_post($post_array);
if ( $has_kses ) {
kses_init_filters();
}
remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10 );
remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 );
if ( is_wp_error($post_id) || empty($post_id) ) {
throw new RuntimeException(__('Unable to save action.', 'action-scheduler'));
}
return $post_id;
}
public function filter_insert_post_data( $postdata ) {
if ( $postdata['post_type'] == self::POST_TYPE ) {
$postdata['post_author'] = 0;
if ( $postdata['post_status'] == 'future' ) {
$postdata['post_status'] = 'publish';
}
}
return $postdata;
}
/**
* Create a (probably unique) post name for scheduled actions in a more performant manner than wp_unique_post_slug().
*
* When an action's post status is transitioned to something other than 'draft', 'pending' or 'auto-draft, like 'publish'
* or 'failed' or 'trash', WordPress will find a unique slug (stored in post_name column) using the wp_unique_post_slug()
* function. This is done to ensure URL uniqueness. The approach taken by wp_unique_post_slug() is to iterate over existing
* post_name values that match, and append a number 1 greater than the largest. This makes sense when manually creating a
* post from the Edit Post screen. It becomes a bottleneck when automatically processing thousands of actions, with a
* database containing thousands of related post_name values.
*
* WordPress 5.1 introduces the 'pre_wp_unique_post_slug' filter for plugins to address this issue.
*
* We can short-circuit WordPress's wp_unique_post_slug() approach using the 'pre_wp_unique_post_slug' filter. This
* method is available to be used as a callback on that filter. It provides a more scalable approach to generating a
* post_name/slug that is probably unique. Because Action Scheduler never actually uses the post_name field, or an
* action's slug, being probably unique is good enough.
*
* For more backstory on this issue, see:
* - https://github.com/woocommerce/action-scheduler/issues/44 and
* - https://core.trac.wordpress.org/ticket/21112
*
* @param string $override_slug Short-circuit return value.
* @param string $slug The desired slug (post_name).
* @param int $post_ID Post ID.
* @param string $post_status The post status.
* @param string $post_type Post type.
* @return string
*/
public function set_unique_post_slug( $override_slug, $slug, $post_ID, $post_status, $post_type ) {
if ( self::POST_TYPE == $post_type ) {
$override_slug = uniqid( self::POST_TYPE . '-', true ) . '-' . wp_generate_password( 32, false );
}
return $override_slug;
}
protected function save_post_schedule( $post_id, $schedule ) {
update_post_meta( $post_id, self::SCHEDULE_META_KEY, $schedule );
}
protected function save_action_group( $post_id, $group ) {
if ( empty($group) ) {
wp_set_object_terms( $post_id, array(), self::GROUP_TAXONOMY, FALSE );
} else {
wp_set_object_terms( $post_id, array($group), self::GROUP_TAXONOMY, FALSE );
}
}
public function fetch_action( $action_id ) {
$post = $this->get_post( $action_id );
if ( empty($post) || $post->post_type != self::POST_TYPE ) {
return $this->get_null_action();
}
try {
$action = $this->make_action_from_post( $post );
} catch ( ActionScheduler_InvalidActionException $exception ) {
do_action( 'action_scheduler_failed_fetch_action', $post->ID, $exception );
return $this->get_null_action();
}
return $action;
}
protected function get_post( $action_id ) {
if ( empty($action_id) ) {
return NULL;
}
return get_post($action_id);
}
protected function get_null_action() {
return new ActionScheduler_NullAction();
}
protected function make_action_from_post( $post ) {
$hook = $post->post_title;
$args = json_decode( $post->post_content, true );
$this->validate_args( $args, $post->ID );
$schedule = get_post_meta( $post->ID, self::SCHEDULE_META_KEY, true );
$this->validate_schedule( $schedule, $post->ID );
$group = wp_get_object_terms( $post->ID, self::GROUP_TAXONOMY, array('fields' => 'names') );
$group = empty( $group ) ? '' : reset($group);
return ActionScheduler::factory()->get_stored_action( $this->get_action_status_by_post_status( $post->post_status ), $hook, $args, $schedule, $group );
}
/**
* @param string $post_status
*
* @throws InvalidArgumentException if $post_status not in known status fields returned by $this->get_status_labels()
* @return string
*/
protected function get_action_status_by_post_status( $post_status ) {
switch ( $post_status ) {
case 'publish' :
$action_status = self::STATUS_COMPLETE;
break;
case 'trash' :
$action_status = self::STATUS_CANCELED;
break;
default :
if ( ! array_key_exists( $post_status, $this->get_status_labels() ) ) {
throw new InvalidArgumentException( sprintf( 'Invalid post status: "%s". No matching action status available.', $post_status ) );
}
$action_status = $post_status;
break;
}
return $action_status;
}
/**
* @param string $action_status
* @throws InvalidArgumentException if $post_status not in known status fields returned by $this->get_status_labels()
* @return string
*/
protected function get_post_status_by_action_status( $action_status ) {
switch ( $action_status ) {
case self::STATUS_COMPLETE :
$post_status = 'publish';
break;
case self::STATUS_CANCELED :
$post_status = 'trash';
break;
default :
if ( ! array_key_exists( $action_status, $this->get_status_labels() ) ) {
throw new InvalidArgumentException( sprintf( 'Invalid action status: "%s".', $action_status ) );
}
$post_status = $action_status;
break;
}
return $post_status;
}
/**
* @param string $hook
* @param array $params
*
* @return string ID of the next action matching the criteria or NULL if not found
*/
public function find_action( $hook, $params = array() ) {
$params = wp_parse_args( $params, array(
'args' => NULL,
'status' => ActionScheduler_Store::STATUS_PENDING,
'group' => '',
));
/** @var wpdb $wpdb */
global $wpdb;
$query = "SELECT p.ID FROM {$wpdb->posts} p";
$args = array();
if ( !empty($params['group']) ) {
$query .= " INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID";
$query .= " INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id";
$query .= " INNER JOIN {$wpdb->terms} t ON tt.term_id=t.term_id AND t.slug=%s";
$args[] = $params['group'];
}
$query .= " WHERE p.post_title=%s";
$args[] = $hook;
$query .= " AND p.post_type=%s";
$args[] = self::POST_TYPE;
if ( !is_null($params['args']) ) {
$query .= " AND p.post_content=%s";
$args[] = json_encode($params['args']);
}
if ( ! empty( $params['status'] ) ) {
$query .= " AND p.post_status=%s";
$args[] = $this->get_post_status_by_action_status( $params['status'] );
}
switch ( $params['status'] ) {
case self::STATUS_COMPLETE:
case self::STATUS_RUNNING:
case self::STATUS_FAILED:
$order = 'DESC'; // Find the most recent action that matches
break;
case self::STATUS_PENDING:
default:
$order = 'ASC'; // Find the next action that matches
break;
}
$query .= " ORDER BY post_date_gmt $order LIMIT 1";
$query = $wpdb->prepare( $query, $args );
$id = $wpdb->get_var($query);
return $id;
}
/**
* Returns the SQL statement to query (or count) actions.
*
* @param array $query Filtering options
* @param string $select_or_count Whether the SQL should select and return the IDs or just the row count
* @throws InvalidArgumentException if $select_or_count not count or select
* @return string SQL statement. The returned SQL is already properly escaped.
*/
protected function get_query_actions_sql( array $query, $select_or_count = 'select' ) {
if ( ! in_array( $select_or_count, array( 'select', 'count' ) ) ) {
throw new InvalidArgumentException(__('Invalid schedule. Cannot save action.', 'action-scheduler'));
}
$query = wp_parse_args( $query, array(
'hook' => '',
'args' => NULL,
'date' => NULL,
'date_compare' => '<=',
'modified' => NULL,
'modified_compare' => '<=',
'group' => '',
'status' => '',
'claimed' => NULL,
'per_page' => 5,
'offset' => 0,
'orderby' => 'date',
'order' => 'ASC',
'search' => '',
) );
/** @var wpdb $wpdb */
global $wpdb;
$sql = ( 'count' === $select_or_count ) ? 'SELECT count(p.ID)' : 'SELECT p.ID ';
$sql .= "FROM {$wpdb->posts} p";
$sql_params = array();
if ( empty( $query['group'] ) && 'group' === $query['orderby'] ) {
$sql .= " LEFT JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID";
$sql .= " LEFT JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id";
$sql .= " LEFT JOIN {$wpdb->terms} t ON tt.term_id=t.term_id";
} elseif ( ! empty( $query['group'] ) ) {
$sql .= " INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID";
$sql .= " INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id";
$sql .= " INNER JOIN {$wpdb->terms} t ON tt.term_id=t.term_id";
$sql .= " AND t.slug=%s";
$sql_params[] = $query['group'];
}
$sql .= " WHERE post_type=%s";
$sql_params[] = self::POST_TYPE;
if ( $query['hook'] ) {
$sql .= " AND p.post_title=%s";
$sql_params[] = $query['hook'];
}
if ( !is_null($query['args']) ) {
$sql .= " AND p.post_content=%s";
$sql_params[] = json_encode($query['args']);
}
if ( ! empty( $query['status'] ) ) {
$sql .= " AND p.post_status=%s";
$sql_params[] = $this->get_post_status_by_action_status( $query['status'] );
}
if ( $query['date'] instanceof DateTime ) {
$date = clone $query['date'];
$date->setTimezone( new DateTimeZone('UTC') );
$date_string = $date->format('Y-m-d H:i:s');
$comparator = $this->validate_sql_comparator($query['date_compare']);
$sql .= " AND p.post_date_gmt $comparator %s";
$sql_params[] = $date_string;
}
if ( $query['modified'] instanceof DateTime ) {
$modified = clone $query['modified'];
$modified->setTimezone( new DateTimeZone('UTC') );
$date_string = $modified->format('Y-m-d H:i:s');
$comparator = $this->validate_sql_comparator($query['modified_compare']);
$sql .= " AND p.post_modified_gmt $comparator %s";
$sql_params[] = $date_string;
}
if ( $query['claimed'] === TRUE ) {
$sql .= " AND p.post_password != ''";
} elseif ( $query['claimed'] === FALSE ) {
$sql .= " AND p.post_password = ''";
} elseif ( !is_null($query['claimed']) ) {
$sql .= " AND p.post_password = %s";
$sql_params[] = $query['claimed'];
}
if ( ! empty( $query['search'] ) ) {
$sql .= " AND (p.post_title LIKE %s OR p.post_content LIKE %s OR p.post_password LIKE %s)";
for( $i = 0; $i < 3; $i++ ) {
$sql_params[] = sprintf( '%%%s%%', $query['search'] );
}
}
if ( 'select' === $select_or_count ) {
switch ( $query['orderby'] ) {
case 'hook':
$orderby = 'p.post_title';
break;
case 'group':
$orderby = 't.name';
break;
case 'status':
$orderby = 'p.post_status';
break;
case 'modified':
$orderby = 'p.post_modified';
break;
case 'claim_id':
$orderby = 'p.post_password';
break;
case 'schedule':
case 'date':
default:
$orderby = 'p.post_date_gmt';
break;
}
if ( 'ASC' === strtoupper( $query['order'] ) ) {
$order = 'ASC';
} else {
$order = 'DESC';
}
$sql .= " ORDER BY $orderby $order";
if ( $query['per_page'] > 0 ) {
$sql .= " LIMIT %d, %d";
$sql_params[] = $query['offset'];
$sql_params[] = $query['per_page'];
}
}
return $wpdb->prepare( $sql, $sql_params );
}
/**
* @param array $query
* @param string $query_type Whether to select or count the results. Default, select.
* @return string|array The IDs of actions matching the query
*/
public function query_actions( $query = array(), $query_type = 'select' ) {
/** @var wpdb $wpdb */
global $wpdb;
$sql = $this->get_query_actions_sql( $query, $query_type );
return ( 'count' === $query_type ) ? $wpdb->get_var( $sql ) : $wpdb->get_col( $sql );
}
/**
* Get a count of all actions in the store, grouped by status
*
* @return array
*/
public function action_counts() {
$action_counts_by_status = array();
$action_stati_and_labels = $this->get_status_labels();
$posts_count_by_status = (array) wp_count_posts( self::POST_TYPE, 'readable' );
foreach ( $posts_count_by_status as $post_status_name => $count ) {
try {
$action_status_name = $this->get_action_status_by_post_status( $post_status_name );
} catch ( Exception $e ) {
// Ignore any post statuses that aren't for actions
continue;
}
if ( array_key_exists( $action_status_name, $action_stati_and_labels ) ) {
$action_counts_by_status[ $action_status_name ] = $count;
}
}
return $action_counts_by_status;
}
/**
* @param string $action_id
*
* @throws InvalidArgumentException
*/
public function cancel_action( $action_id ) {
$post = get_post($action_id);
if ( empty($post) || ($post->post_type != self::POST_TYPE) ) {
throw new InvalidArgumentException(sprintf(__('Unidentified action %s', 'action-scheduler'), $action_id));
}
do_action( 'action_scheduler_canceled_action', $action_id );
add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 );
wp_trash_post($action_id);
remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 );
}
public function delete_action( $action_id ) {
$post = get_post($action_id);
if ( empty($post) || ($post->post_type != self::POST_TYPE) ) {
throw new InvalidArgumentException(sprintf(__('Unidentified action %s', 'action-scheduler'), $action_id));
}
do_action( 'action_scheduler_deleted_action', $action_id );
wp_delete_post( $action_id, TRUE );
}
/**
* @param string $action_id
*
* @throws InvalidArgumentException
* @return ActionScheduler_DateTime The date the action is schedule to run, or the date that it ran.
*/
public function get_date( $action_id ) {
$next = $this->get_date_gmt( $action_id );
return ActionScheduler_TimezoneHelper::set_local_timezone( $next );
}
/**
* @param string $action_id
*
* @throws InvalidArgumentException
* @return ActionScheduler_DateTime The date the action is schedule to run, or the date that it ran.
*/
public function get_date_gmt( $action_id ) {
$post = get_post($action_id);
if ( empty($post) || ($post->post_type != self::POST_TYPE) ) {
throw new InvalidArgumentException(sprintf(__('Unidentified action %s', 'action-scheduler'), $action_id));
}
if ( $post->post_status == 'publish' ) {
return as_get_datetime_object($post->post_modified_gmt);
} else {
return as_get_datetime_object($post->post_date_gmt);
}
}
/**
* @param int $max_actions
* @param DateTime $before_date Jobs must be schedule before this date. Defaults to now.
* @param array $hooks Claim only actions with a hook or hooks.
* @param string $group Claim only actions in the given group.
*
* @return ActionScheduler_ActionClaim
* @throws RuntimeException When there is an error staking a claim.
* @throws InvalidArgumentException When the given group is not valid.
*/
public function stake_claim( $max_actions = 10, DateTime $before_date = null, $hooks = array(), $group = '' ) {
$claim_id = $this->generate_claim_id();
$this->claim_actions( $claim_id, $max_actions, $before_date, $hooks, $group );
$action_ids = $this->find_actions_by_claim_id( $claim_id );
return new ActionScheduler_ActionClaim( $claim_id, $action_ids );
}
/**
* @return int
*/
public function get_claim_count(){
global $wpdb;
$sql = "SELECT COUNT(DISTINCT post_password) FROM {$wpdb->posts} WHERE post_password != '' AND post_type = %s AND post_status IN ('in-progress','pending')";
$sql = $wpdb->prepare( $sql, array( self::POST_TYPE ) );
return $wpdb->get_var( $sql );
}
protected function generate_claim_id() {
$claim_id = md5(microtime(true) . rand(0,1000));
return substr($claim_id, 0, 20); // to fit in db field with 20 char limit
}
/**
* @param string $claim_id
* @param int $limit
* @param DateTime $before_date Should use UTC timezone.
* @param array $hooks Claim only actions with a hook or hooks.
* @param string $group Claim only actions in the given group.
*
* @return int The number of actions that were claimed
* @throws RuntimeException When there is a database error.
* @throws InvalidArgumentException When the group is invalid.
*/
protected function claim_actions( $claim_id, $limit, DateTime $before_date = null, $hooks = array(), $group = '' ) {
// Set up initial variables.
$date = null === $before_date ? as_get_datetime_object() : clone $before_date;
$limit_ids = ! empty( $group );
$ids = $limit_ids ? $this->get_actions_by_group( $group, $limit, $date ) : array();
// If limiting by IDs and no posts found, then return early since we have nothing to update.
if ( $limit_ids && 0 === count( $ids ) ) {
return 0;
}
/** @var wpdb $wpdb */
global $wpdb;
/*
* Build up custom query to update the affected posts. Parameters are built as a separate array
* to make it easier to identify where they are in the query.
*
* We can't use $wpdb->update() here because of the "ID IN ..." clause.
*/
$update = "UPDATE {$wpdb->posts} SET post_password = %s, post_modified_gmt = %s, post_modified = %s";
$params = array(
$claim_id,
current_time( 'mysql', true ),
current_time( 'mysql' ),
);
// Build initial WHERE clause.
$where = "WHERE post_type = %s AND post_status = %s AND post_password = ''";
$params[] = self::POST_TYPE;
$params[] = ActionScheduler_Store::STATUS_PENDING;
if ( ! empty( $hooks ) ) {
$placeholders = array_fill( 0, count( $hooks ), '%s' );
$where .= ' AND post_title IN (' . join( ', ', $placeholders ) . ')';
$params = array_merge( $params, array_values( $hooks ) );
}
/*
* Add the IDs to the WHERE clause. IDs not escaped because they came directly from a prior DB query.
*
* If we're not limiting by IDs, then include the post_date_gmt clause.
*/
if ( $limit_ids ) {
$where .= ' AND ID IN (' . join( ',', $ids ) . ')';
} else {
$where .= ' AND post_date_gmt <= %s';
$params[] = $date->format( 'Y-m-d H:i:s' );
}
// Add the ORDER BY clause and,ms limit.
$order = 'ORDER BY menu_order ASC, post_date_gmt ASC, ID ASC LIMIT %d';
$params[] = $limit;
// Run the query and gather results.
$rows_affected = $wpdb->query( $wpdb->prepare( "{$update} {$where} {$order}", $params ) );
if ( $rows_affected === false ) {
throw new RuntimeException( __( 'Unable to claim actions. Database error.', 'action-scheduler' ) );
}
return (int) $rows_affected;
}
/**
* Get IDs of actions within a certain group and up to a certain date/time.
*
* @param string $group The group to use in finding actions.
* @param int $limit The number of actions to retrieve.
* @param DateTime $date DateTime object representing cutoff time for actions. Actions retrieved will be
* up to and including this DateTime.
*
* @return array IDs of actions in the appropriate group and before the appropriate time.
* @throws InvalidArgumentException When the group does not exist.
*/
protected function get_actions_by_group( $group, $limit, DateTime $date ) {
// Ensure the group exists before continuing.
if ( ! term_exists( $group, self::GROUP_TAXONOMY )) {
throw new InvalidArgumentException( sprintf( __( 'The group "%s" does not exist.', 'action-scheduler' ), $group ) );
}
// Set up a query for post IDs to use later.
$query = new WP_Query();
$query_args = array(
'fields' => 'ids',
'post_type' => self::POST_TYPE,
'post_status' => ActionScheduler_Store::STATUS_PENDING,
'has_password' => false,
'posts_per_page' => $limit * 3,
'suppress_filters' => true,
'no_found_rows' => true,
'orderby' => array(
'menu_order' => 'ASC',
'date' => 'ASC',
'ID' => 'ASC',
),
'date_query' => array(
'column' => 'post_date_gmt',
'before' => $date->format( 'Y-m-d H:i' ),
'inclusive' => true,
),
'tax_query' => array(
array(
'taxonomy' => self::GROUP_TAXONOMY,
'field' => 'slug',
'terms' => $group,
'include_children' => false,
),
),
);
return $query->query( $query_args );
}
/**
* @param string $claim_id
* @return array
*/
public function find_actions_by_claim_id( $claim_id ) {
/** @var wpdb $wpdb */
global $wpdb;
$sql = "SELECT ID FROM {$wpdb->posts} WHERE post_type = %s AND post_password = %s";
$sql = $wpdb->prepare( $sql, array( self::POST_TYPE, $claim_id ) );
$action_ids = $wpdb->get_col( $sql );
return $action_ids;
}
public function release_claim( ActionScheduler_ActionClaim $claim ) {
$action_ids = $this->find_actions_by_claim_id( $claim->get_id() );
if ( empty($action_ids) ) {
return; // nothing to do
}
$action_id_string = implode(',', array_map('intval', $action_ids));
/** @var wpdb $wpdb */
global $wpdb;
$sql = "UPDATE {$wpdb->posts} SET post_password = '' WHERE ID IN ($action_id_string) AND post_password = %s";
$sql = $wpdb->prepare( $sql, array( $claim->get_id() ) );
$result = $wpdb->query($sql);
if ( $result === false ) {
/* translators: %s: claim ID */
throw new RuntimeException( sprintf( __('Unable to unlock claim %s. Database error.', 'action-scheduler'), $claim->get_id() ) );
}
}
/**
* @param string $action_id
*/
public function unclaim_action( $action_id ) {
/** @var wpdb $wpdb */
global $wpdb;
$sql = "UPDATE {$wpdb->posts} SET post_password = '' WHERE ID = %d AND post_type = %s";
$sql = $wpdb->prepare( $sql, $action_id, self::POST_TYPE );
$result = $wpdb->query($sql);
if ( $result === false ) {
/* translators: %s: action ID */
throw new RuntimeException( sprintf( __('Unable to unlock claim on action %s. Database error.', 'action-scheduler'), $action_id ) );
}
}
public function mark_failure( $action_id ) {
/** @var wpdb $wpdb */
global $wpdb;
$sql = "UPDATE {$wpdb->posts} SET post_status = %s WHERE ID = %d AND post_type = %s";
$sql = $wpdb->prepare( $sql, self::STATUS_FAILED, $action_id, self::POST_TYPE );
$result = $wpdb->query($sql);
if ( $result === false ) {
/* translators: %s: action ID */
throw new RuntimeException( sprintf( __('Unable to mark failure on action %s. Database error.', 'action-scheduler'), $action_id ) );
}
}
/**
* Return an action's claim ID, as stored in the post password column
*
* @param string $action_id
* @return mixed
*/
public function get_claim_id( $action_id ) {
return $this->get_post_column( $action_id, 'post_password' );
}
/**
* Return an action's status, as stored in the post status column
*
* @param string $action_id
* @return mixed
*/
public function get_status( $action_id ) {
$status = $this->get_post_column( $action_id, 'post_status' );
if ( $status === null ) {
throw new InvalidArgumentException( __( 'Invalid action ID. No status found.', 'action-scheduler' ) );
}
return $this->get_action_status_by_post_status( $status );
}
private function get_post_column( $action_id, $column_name ) {
/** @var \wpdb $wpdb */
global $wpdb;
return $wpdb->get_var( $wpdb->prepare( "SELECT {$column_name} FROM {$wpdb->posts} WHERE ID=%d AND post_type=%s", $action_id, self::POST_TYPE ) );
}
/**
* @param string $action_id
*/
public function log_execution( $action_id ) {
/** @var wpdb $wpdb */
global $wpdb;
$sql = "UPDATE {$wpdb->posts} SET menu_order = menu_order+1, post_status=%s, post_modified_gmt = %s, post_modified = %s WHERE ID = %d AND post_type = %s";
$sql = $wpdb->prepare( $sql, self::STATUS_RUNNING, current_time('mysql', true), current_time('mysql'), $action_id, self::POST_TYPE );
$wpdb->query($sql);
}
/**
* Record that an action was completed.
*
* @param int $action_id ID of the completed action.
* @throws InvalidArgumentException|RuntimeException
*/
public function mark_complete( $action_id ) {
$post = get_post($action_id);
if ( empty($post) || ($post->post_type != self::POST_TYPE) ) {
throw new InvalidArgumentException(sprintf(__('Unidentified action %s', 'action-scheduler'), $action_id));
}
add_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 );
add_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10, 5 );
$result = wp_update_post(array(
'ID' => $action_id,
'post_status' => 'publish',
), TRUE);
remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10 );
remove_filter( 'pre_wp_unique_post_slug', array( $this, 'set_unique_post_slug' ), 10 );
if ( is_wp_error($result) ) {
throw new RuntimeException($result->get_error_message());
}
}
/**
* Mark action as migrated when there is an error deleting the action.
*
* @param int $action_id Action ID.
*/
public function mark_migrated( $action_id ) {
wp_update_post(
array(
'ID' => $action_id,
'post_status' => 'migrated'
)
);
}
/**
* Determine whether the post store can be migrated.
*
* @return bool
*/
public function migration_dependencies_met( $setting ) {
global $wpdb;
$dependencies_met = get_transient( self::DEPENDENCIES_MET );
if ( empty( $dependencies_met ) ) {
$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.
*
* Previously, AS wasn't concerned about args length, as we used the (unindex) post_content column. However,
* as we prepare to move to custom tables, and can use an indexed VARCHAR column instead, we want to warn
* developers of this impending requirement.
*
* @param ActionScheduler_Action $action
*/
protected function validate_action( ActionScheduler_Action $action ) {
try {
parent::validate_action( $action );
} catch ( Exception $e ) {
$message = sprintf( __( '%s Support for strings longer than this will be removed in a future version.', 'action-scheduler' ), $e->getMessage() );
_doing_it_wrong( 'ActionScheduler_Action::$args', $message, '2.1.0' );
}
}
/**
* @codeCoverageIgnore
*/
public function init() {
add_filter( 'action_scheduler_migration_dependencies_met', array( $this, 'migration_dependencies_met' ) );
$post_type_registrar = new ActionScheduler_wpPostStore_PostTypeRegistrar();
$post_type_registrar->register();
$post_status_registrar = new ActionScheduler_wpPostStore_PostStatusRegistrar();
$post_status_registrar->register();
$taxonomy_registrar = new ActionScheduler_wpPostStore_TaxonomyRegistrar();
$taxonomy_registrar->register();
}
}

View File

@@ -1,58 +0,0 @@
<?php
/**
* Class ActionScheduler_wpPostStore_PostStatusRegistrar
* @codeCoverageIgnore
*/
class ActionScheduler_wpPostStore_PostStatusRegistrar {
public function register() {
register_post_status( ActionScheduler_Store::STATUS_RUNNING, array_merge( $this->post_status_args(), $this->post_status_running_labels() ) );
register_post_status( ActionScheduler_Store::STATUS_FAILED, array_merge( $this->post_status_args(), $this->post_status_failed_labels() ) );
}
/**
* Build the args array for the post type definition
*
* @return array
*/
protected function post_status_args() {
$args = array(
'public' => false,
'exclude_from_search' => false,
'show_in_admin_all_list' => true,
'show_in_admin_status_list' => true,
);
return apply_filters( 'action_scheduler_post_status_args', $args );
}
/**
* Build the args array for the post type definition
*
* @return array
*/
protected function post_status_failed_labels() {
$labels = array(
'label' => _x( 'Failed', 'post', 'action-scheduler' ),
/* translators: %s: count */
'label_count' => _n_noop( 'Failed <span class="count">(%s)</span>', 'Failed <span class="count">(%s)</span>', 'action-scheduler' ),
);
return apply_filters( 'action_scheduler_post_status_failed_labels', $labels );
}
/**
* Build the args array for the post type definition
*
* @return array
*/
protected function post_status_running_labels() {
$labels = array(
'label' => _x( 'In-Progress', 'post', 'action-scheduler' ),
/* translators: %s: count */
'label_count' => _n_noop( 'In-Progress <span class="count">(%s)</span>', 'In-Progress <span class="count">(%s)</span>', 'action-scheduler' ),
);
return apply_filters( 'action_scheduler_post_status_running_labels', $labels );
}
}

View File

@@ -1,50 +0,0 @@
<?php
/**
* Class ActionScheduler_wpPostStore_PostTypeRegistrar
* @codeCoverageIgnore
*/
class ActionScheduler_wpPostStore_PostTypeRegistrar {
public function register() {
register_post_type( ActionScheduler_wpPostStore::POST_TYPE, $this->post_type_args() );
}
/**
* Build the args array for the post type definition
*
* @return array
*/
protected function post_type_args() {
$args = array(
'label' => __( 'Scheduled Actions', 'action-scheduler' ),
'description' => __( 'Scheduled actions are hooks triggered on a cetain date and time.', 'action-scheduler' ),
'public' => false,
'map_meta_cap' => true,
'hierarchical' => false,
'supports' => array('title', 'editor','comments'),
'rewrite' => false,
'query_var' => false,
'can_export' => true,
'ep_mask' => EP_NONE,
'labels' => array(
'name' => __( 'Scheduled Actions', 'action-scheduler' ),
'singular_name' => __( 'Scheduled Action', 'action-scheduler' ),
'menu_name' => _x( 'Scheduled Actions', 'Admin menu name', 'action-scheduler' ),
'add_new' => __( 'Add', 'action-scheduler' ),
'add_new_item' => __( 'Add New Scheduled Action', 'action-scheduler' ),
'edit' => __( 'Edit', 'action-scheduler' ),
'edit_item' => __( 'Edit Scheduled Action', 'action-scheduler' ),
'new_item' => __( 'New Scheduled Action', 'action-scheduler' ),
'view' => __( 'View Action', 'action-scheduler' ),
'view_item' => __( 'View Action', 'action-scheduler' ),
'search_items' => __( 'Search Scheduled Actions', 'action-scheduler' ),
'not_found' => __( 'No actions found', 'action-scheduler' ),
'not_found_in_trash' => __( 'No actions found in trash', 'action-scheduler' ),
),
);
$args = apply_filters('action_scheduler_post_type_args', $args);
return $args;
}
}

View File

@@ -1,26 +0,0 @@
<?php
/**
* Class ActionScheduler_wpPostStore_TaxonomyRegistrar
* @codeCoverageIgnore
*/
class ActionScheduler_wpPostStore_TaxonomyRegistrar {
public function register() {
register_taxonomy( ActionScheduler_wpPostStore::GROUP_TAXONOMY, ActionScheduler_wpPostStore::POST_TYPE, $this->taxonomy_args() );
}
protected function taxonomy_args() {
$args = array(
'label' => __('Action Group', 'action-scheduler'),
'public' => false,
'hierarchical' => false,
'show_admin_column' => true,
'query_var' => false,
'rewrite' => false,
);
$args = apply_filters('action_scheduler_taxonomy_args', $args);
return $args;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

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

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