This commit is contained in:
Prospress Inc
2018-07-19 12:14:08 +02:00
committed by Remco Tolsma
parent 5fb62b0e6a
commit 1039aec2d9
126 changed files with 13546 additions and 4169 deletions

View File

@@ -554,55 +554,66 @@ jQuery(document).ready(function($){
return data; return data;
}); });
// We're on the Subscriptions settings page var $allowSwitching = $( document.getElementById( 'woocommerce_subscriptions_allow_switching' ) );
if($('#woocommerce_subscriptions_allow_switching').length > 0 ){ var $syncRenewals = $( document.getElementById( 'woocommerce_subscriptions_sync_payments' ) );
var allowSwitching = $('#woocommerce_subscriptions_allow_switching').val(),
$switchSettingsRows = $('#woocommerce_subscriptions_allow_switching').parents('tr').siblings('tr'),
$syncProratationRow = $('#woocommerce_subscriptions_prorate_synced_payments').parents('tr'),
$suspensionExtensionRow = $('#woocommerce_subscriptions_recoup_suspension').parents('tr');
if('no'==allowSwitching){ // We're on the Subscriptions settings page
if ( $allowSwitching.length > 0 ) {
var allowSwitchingVal = $allowSwitching.val(),
$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 ( 'no' === allowSwitchingVal ) {
$switchSettingsRows.hide(); $switchSettingsRows.hide();
} }
$( '#woocommerce_subscriptions_allow_switching' ).on( 'change', function() { $allowSwitching.on( 'change', function() {
if ( 'no' == $( this ).val() ) { if ( 'no' === $( this ).val() ) {
$switchSettingsRows.fadeOut(); $switchSettingsRows.fadeOut();
} else if ( 'no' == allowSwitching ) { // switching was previously disable, so settings will be hidden } else if ( 'no' === allowSwitchingVal ) { // switching was previously disabled, so settings will be hidden
$switchSettingsRows.fadeIn(); $switchSettingsRows.fadeIn();
} }
allowSwitching = $( this ).val(); allowSwitchingVal = $( this ).val();
} ); } );
// Show/hide suspension extension setting // Show/hide suspension extension setting
if ($('#woocommerce_subscriptions_max_customer_suspensions').val() > 0) { $( '#woocommerce_subscriptions_max_customer_suspensions' ).on( 'change', function() {
$suspensionExtensionRow.show(); if ( $( this ).val() > 0 ) {
} else {
$suspensionExtensionRow.hide();
}
$('#woocommerce_subscriptions_max_customer_suspensions').on('change', function(){
if ($(this).val() > 0) {
$suspensionExtensionRow.show(); $suspensionExtensionRow.show();
} else { } else {
$suspensionExtensionRow.hide(); $suspensionExtensionRow.hide();
} }
}); } ).change();
// Show/hide sync proration setting // No animation when initially hiding prorated rows.
if ($('#woocommerce_subscriptions_sync_payments').is(':checked')) { if ( ! $syncRenewals.is( ':checked' ) ) {
$syncProratationRow.show(); $syncRows.hide();
} else { } else if ( 'recurring' !== $prorateFirstRenewal.val() ) {
$syncProratationRow.hide(); $daysNoFeeRow.hide();
} }
$('#woocommerce_subscriptions_sync_payments').on('change', function(){ // Animate showing and hiding the synchronization rows.
if ($(this).is(':checked')) { $syncRenewals.on( 'change', function(){
$syncProratationRow.show(); if ( $( this ).is( ':checked' ) ) {
$syncRows.not( $daysNoFeeRow ).fadeIn();
$prorateFirstRenewal.change();
} else { } else {
$syncProratationRow.hide(); $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 // Don't display the variation notice for variable subscription products
@@ -666,4 +677,70 @@ jQuery(document).ready(function($){
$( '#general_product_data, #variable_product_options' ).on( 'change', '[class^="wc_input_subscription_payment_sync"], [class^="wc_input_subscription_trial_length"]', function() { $( '#general_product_data, #variable_product_options' ).on( 'change', '[class^="wc_input_subscription_payment_sync"], [class^="wc_input_subscription_trial_length"]', function() {
$.disableEnableOneTimeShipping(); $.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();
}); });

View File

@@ -0,0 +1,53 @@
jQuery( document ).ready( function( $ ) {
'use strict';
var renewals_field = document.querySelector( '.wcs_number_payments_field' ),
$renewals_field = $( renewals_field );
/**
* Subscription coupon actions.
* @type {{init: function, type_options: function, move_field: function}}
*/
var wcs_meta_boxes_coupon_actions = {
/**
* Initialize variation actions.
*/
init: function() {
if ( renewals_field ) {
$( document.getElementById( 'discount_type' ) ).on( 'change', this.type_options ).change();
this.move_field();
}
},
/**
* Show/hide fields by coupon type options.
*/
type_options: function() {
var select_val = $( this ).val();
switch ( select_val ) {
case 'recurring_fee':
case 'recurring_percent':
$renewals_field.show();
break;
default:
$renewals_field.hide();
break;
}
},
/**
* Move the renewal form field in the DOM to a better location.
*/
move_field: function() {
var parent = document.getElementById( 'general_coupon_data' ),
shipping = parent.querySelector( '.free_shipping_field' );
parent.insertBefore( renewals_field, shipping );
}
};
wcs_meta_boxes_coupon_actions.init();
} );

View File

@@ -168,6 +168,60 @@ jQuery(document).ready(function($){
function zeroise( val ) { function zeroise( val ) {
return (val > 9 ) ? val : '0' + 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(){ $('body.post-type-shop_subscription #post').submit(function(){
if('wcs_process_renewal' == $( "body.post-type-shop_subscription select[name='wc_order_action']" ).val()) { if('wcs_process_renewal' == $( "body.post-type-shop_subscription select[name='wc_order_action']" ).val()) {

17
assets/js/frontend/wcs-cart.js Executable file
View File

@@ -0,0 +1,17 @@
function hide_non_applicable_coupons() {
var coupon_elements = document.getElementsByClassName( 'cart-discount' );
for ( var i = 0; i < coupon_elements.length; i++ ) {
if ( 0 !== coupon_elements[i].getElementsByClassName( 'wcs-hidden-coupon' ).length ) {
coupon_elements[i].style.display = 'none';
}
}
}
hide_non_applicable_coupons();
jQuery( document ).ready( function( $ ){
$( document.body ).on( 'updated_cart_totals updated_checkout', function() {
hide_non_applicable_coupons();
} );
} );

View File

@@ -1,5 +1,65 @@
*** WooCommerce Subscriptions Changelog *** *** WooCommerce Subscriptions Changelog ***
2018.07.10 - version 2.3.2
* Fix: Extend the next payment date after early renewal if there's no end date. PR#2804
* Fix: Prevent throwing type hinting errors when getting related orders from cache. RR#2805
* Tweak: Don't copying `_created_via` meta from subscriptions to related orders as this overrides the value set when the order was created. PR#2794
* Tweak: Make `wcs_get_subscriptions_for_order()` the canonical function for retrieving subscriptions for a given order (regardless of type). PR#2805
2018.07.06 - version 2.3.1
* Fix: Catchable fatal error from function parameter hinting. PR#2797
2018.07.04 - version 2.3.0
* New: Allow store managers to link an order with a subscription using the parent order relationship via a UI on the admin edit subscription screen. PR#2272
* New: Add an option to charge the full recurring amount at the time of sign up for synchronised subscription products. PR#2343
* New: Add new coupon setting which store managers to use to create recurring coupons which apply for a certain number of payments. PR * New: Add new sections to the system status. PR#2493
* New: Allow customers to renew subscriptions before their next payment date from their My Account Subscription page. PR#2544
* New: Add persistent cache of related order IDs in subscription meta. Improves performance when obtaining subscription related orders. PR#2572
* New: Add new sections to the system status. PR#2493
* New: Add persistent cache of customer subscriptions. PR#2635
* New: Add extra args ($order and $cart) to woocommerce_checkout_create_subscription filter. PR#2645
* New: Update Action Scheduler to v2.0.0.
* New: Add a new admin upgrade notice helper class `WCS_Upgrade_Notice_Manager`. PR#2622
* New: Add WCS_INIT_TIMESTAMP constant and use it to time background updates. PR#2739
* New: Display an admin notice when a site is downgraded. PR#2743
* Fix: Repair subscriptions which have been suspended in PayPal but not in WooCommerce. PR#2407
* Fix: Make sure wcs_get_product_limitation() uses the parent product when determining variation product subscription limitations. PR#2513
* Fix: Remove non-recurring fees from renewal carts. PR#2642
* Fix: Don't autocomplete orders which have a subtotal greater than 0. PR#2665
* Fix: [Reports] Exclude trashed subscriptions from all calculations. Fixes inconsistencies between some subscription counts. PR#2674
* Fix: Check if the recurring_carts variable has been set before calling count() on it. PR#2688
* Fix: Issues caused by a loophole where trashed or non grouped products remain a valid subscription product parent for switching. PR#2682
* Fix: Check if there is no shipping method for a shipping zone before trying to access it when displaying cart HTML. PR#2701
* Fix: Correctly calculate switching sign-up fee proration when switching between synced products. PR#2722
* Fix: Indirect modification of WC_Checkout::$shipping_methods PHP errors. PR#2729
* Fix: Only allow switching between products which are visible to the customer. PR#2727
* Fix: [WC3.4] Only trigger the woocommerce_after_add_to_cart_button action hook once on variable subscription single product pages. PR#2750
* Fix: [WC3.4] Fix missing endpoint settings. PR#2767
* Fix: Remove unused chosen shipping methods for recurring packages. Fixes an issue where if the number of available shipping methods changes, the recurring carts hold onto their previously chosen method. PR#2782
* Fix: Protect against possible errors when getting the subscriptions my account endpoint url. PR#2781
* Tweak: Prevent bulk deletion of variations in use by at least one subscription. PR#2678
* Tweak: Add better support for custom order types via `WC_Subscription::get_last_order()`. PR#2644
* Tweak: Add `WCS_Admin_Post_Types::get_date_column_content()` helper function for displaying date content in post tables. PR#2643
* Tweak: Change the Edit Subscription Schedule meta box titles. PR#2649
* Tweak: Hide Recurring Coupons in the initial cart if they don't apply. PR#2616
* Tweak: Add a filter to allow third-parties to filter orders by custom order types. PR#2667
* Tweak: Don't schedule events for subscription start & last payment dates. PR#2669
* Tweak: Add new `wcs_create_subscription` action. PR#2732
* Tweak: Include variations in the "Subscriptions by product" reports. PR#2704
* Tweak: Improve performance of getting a variable product's min and max variation data. PR#2723
* Tweak: Add Subscription endpoints to the WC_Query endpoints. This allows our endpoints to be considered by functions like is_wc_endpoint_url() and also wc_body_class(). PR#2749
* Tweak: Add an order note to renewal orders processed under staging site conditions. PR#2773
* Tweak: Add a new badge to the subscriptions admin menu item when a site is operating as a staging site. PR#2773
* Tweak: Add note to guest checkout setting, noting that an account is required when purchasing subscription products. PR#2751
* Tweak: Deprecate the 'wcs_pre_get_users_subscriptions' filter. PR#2785
* Tweak: Increase minimum required WC version to 2.6. PR#2786
* Tweak: Remove TLC transient library and the cache manager which implemented it. PR#2614
* Tweak: On site's already running WC 3.0 ensure all subscriptions have address indexes via a background repair script. PR#2605
* Tweak: Require PHP 5.6 or newer. PR#2325
* Tweak: Change 'created_via' order property for subscription orders. PR#2389
* Tweak: Boost performance of admin subscription search by using billing and shipping indexes. PR#2409
* Tweak: Add filter to control the automatic redirect behaviour of the Subscriptions menu item on My Account. PR#2633
2018.05.29 - version 2.2.21 2018.05.29 - version 2.2.21
* Tweak: Update WooCommerce tested up to compatibility flag. * Tweak: Update WooCommerce tested up to compatibility flag.
* Fix: [GDPR] While processing erasure requests anonymise all user subscriptions with any status. PR#2720 * Fix: [GDPR] While processing erasure requests anonymise all user subscriptions with any status. PR#2720

1252
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,148 @@
<?php
/**
* Debug Tool with methods to update data in the background
*
* Add tools for debugging and managing Subscriptions to the
* WooCommerce > System Status > Tools administration screen.
*
* @author Prospress
* @category Admin
* @package WooCommerce Subscriptions/Admin
* @version 2.3
* @since 2.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
} // Exit if accessed directly
/**
* WCS_Background_Updater Class
*
* Provide APIs for a debug tool to update data in the background using Action Scheduler.
*/
abstract class WCS_Background_Updater {
/**
* @var int The amount of time, in seconds, to give the background process to run the update.
*/
protected $time_limit;
/**
* @var string The hook used to schedule background updates.
*/
protected $scheduled_hook;
/**
* Attach callbacks to hooks
*/
public function init() {
// Make sure child classes have defined a scheduled hook, otherwise we can't do background updates.
if ( is_null( $this->scheduled_hook ) ) {
throw new RuntimeException( __CLASS__ . ' must assign a hook to $this->scheduled_hook' );
}
if ( is_null( $this->time_limit ) ) {
$this->time_limit = 60;
// Allow more time for CLI requests, as they're not beholden to script timeouts
if ( $this->is_wp_cli_request() ) {
$this->time_limit *= 3;
}
}
// Allow for each class's time limit to be customised by 3rd party code, as well as all tools' time limits
$this->time_limit = apply_filters( 'wcs_debug_tools_time_limit', $this->time_limit, $this );
// Action scheduled in Action Scheduler for updating data in the background
add_action( $this->scheduled_hook, array( $this, 'run_update' ) );
}
/**
* Get the items to be updated, if any.
*
* @return array An array of items to update, or empty array if there are no items to update.
*/
abstract protected function get_items_to_update();
/**
* Run the update for a single item.
*
* @param mixed $item The item to update.
*/
abstract protected function update_item( $item );
/**
* Update a set of items in the background.
*
* This method will loop over until there are no more items to update, or the process has been running for the
* time limit set on the class @see $this->time_limit, which is 60 seconds by default (wall clock time, not
* execution time).
*
* The $scheduler_hook is rescheduled before updating any items something goes wrong when processing a batch - it's
* scheduled for $this->time_limit in future, so there's little chance of duplicate processes running at the same
* time with WP Cron, but importantly, there is some chance so it should not be used for critical data, like
* payments. Instead, it is intended for use for things like cache updates. It's also a good idea to use an atomic
* update methods to avoid updating something that has already been updated in a separate request.
*
* Importantly, the overlap between the next scheduled update and the current batch is also useful for running
* Action Scheduler via WP CLI, because it will allow for continuous execution of updates (i.e. updating a new
* batch as soon as one batch has execeeded the time limit rather than having to run Action Scheduler via WP CLI
* again later).
*/
public function run_update() {
$this->schedule_background_update();
// If the update is being run via WP CLI, we don't need to worry about the request time, just the processing time for this method
$start_time = $this->is_wp_cli_request() ? gmdate( 'U' ) : WCS_INIT_TIMESTAMP;
do {
$items = $this->get_items_to_update();
foreach ( $items as $item ) {
$this->update_item( $item );
$time_elapsed = ( gmdate( 'U' ) - $start_time );
if ( $time_elapsed >= $this->time_limit ) {
break 2;
}
}
} while ( ! empty( $items ) );
// If we stopped processing the batch because we ran out of items to process, not because we ran out of time, we don't need to run any other batches
if ( empty( $items ) ) {
$this->unschedule_background_updates();
}
}
/**
* Schedule the instance's hook to run in $this->time_limit seconds, if it's not already scheduled.
*/
protected function schedule_background_update() {
if ( false === wc_next_scheduled_action( $this->scheduled_hook ) ) {
wc_schedule_single_action( gmdate( 'U' ) + $this->time_limit, $this->scheduled_hook );
}
}
/**
* Unschedule the instance's hook in Action Scheduler
*/
protected function unschedule_background_updates() {
wc_unschedule_action( $this->scheduled_hook );
}
/**
* Check whether the current request is via WP CLI
*
* @return bool
*/
protected function is_wp_cli_request() {
return ( defined( 'WP_CLI' ) && WP_CLI );
}
}

View File

@@ -0,0 +1,51 @@
<?php
/**
* WCS_Background_Upgrader Class
*
* Provide APIs for an upgrade script to update data in the background using Action Scheduler.
*
* @author Prospress
* @category Admin
* @package WooCommerce Subscriptions/Admin/Upgrades
* @since 2.3
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
abstract class WCS_Background_Upgrader extends WCS_Background_Updater {
/**
* WC Logger instance for logging messages.
*
* @var WC_Logger
*/
protected $logger;
/**
* @var string The log file handle to write messages to.
*/
protected $log_handle;
/**
* Schedule the @see $this->scheduled_hook action to start repairing subscriptions in
* @see $this->time_limit seconds (60 seconds by default).
*
* @since 2.3.0
*/
public function schedule_repair() {
$this->schedule_background_update();
}
/**
* Add a message to the wcs-upgrade-subscriptions-paypal-suspended log
*
* @param string $message The message to be logged
* @since 2.3.0
*/
protected function log( $message ) {
$this->logger->add( $this->log_handle, $message );
}
}

View File

@@ -0,0 +1,58 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Define requirements for a customer data store and provide method for accessing active data store.
*
* A unified way to query customer data for subscriptions makes it possible to add a caching layer
* to that data in the short term, and in the longer term seamlessly handle different storage for
* customer data defined by WooCommerce core. This is important because at the time of writing,
* the customer ID for an order is stored in a post meta field with the key '_customer_user', but
* it is being moved to use the 'post_author' column of the posts table from WC v2.4 or v2.5. It
* will eventually also be moved quite likely to custom tables.
*
* @version 2.3.0
* @since 2.3.0
* @category Class
* @author Prospress
*/
abstract class WCS_Customer_Store {
/** @var WCS_Customer_Store */
private static $instance = null;
/**
* Get the IDs for a given user's subscriptions.
*
* @param int $user_id The id of the user whose subscriptions you want.
* @return array
*/
abstract public function get_users_subscription_ids( $user_id );
/**
* Get the active customer data store.
*
* @return WCS_Customer_Store
*/
final public static function instance() {
if ( empty( self::$instance ) ) {
if ( ! did_action( 'plugins_loaded' ) ) {
wcs_doing_it_wrong( __METHOD__, 'This method was called before the "plugins_loaded" hook. It applies a filter to the customer data store instantiated. For that to work, it should first be called after all plugins are loaded.', '2.3.0' );
}
$class = apply_filters( 'wcs_customer_store_class', 'WCS_Customer_Store_Cached_CPT' );
self::$instance = new $class();
self::$instance->init();
}
return self::$instance;
}
/**
* Stub for initialising the class outside the constructor, for things like attaching callbacks to hooks.
*/
protected function init() {}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* WCS_Debug_Tool_Cache_Updater Class
*
* Shared methods for tool on the WooCommerce > System Status > Tools page that need to
* update a cached data store's cache.
*
* @author Prospress
* @category Admin
* @package WooCommerce Subscriptions/Admin
* @version 2.3
* @since 2.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
} // Exit if accessed directly
/**
* WCS_Debug_Tool_Cache_Updater Class
*
* Shared methods for tool on the WooCommerce > System Status > Tools page that need to
* update a cached data store's cache.
*/
abstract class WCS_Debug_Tool_Cache_Updater extends WCS_Debug_Tool {
/**
* @var mixed $data_Store The store used for updating the cache.
*/
protected $data_store;
/**
* Attach callbacks and hooks, if the class's data store is using caching.
*/
public function init() {
if ( $this->is_data_store_cached() ) {
parent::init();
}
}
/**
* Check if the store is a cache updater, and has methods required to erase or generate cache.
*/
protected function is_data_store_cached() {
return is_a( $this->data_store, 'WCS_Cache_Updater' );
}
}

View File

@@ -0,0 +1,66 @@
<?php
/**
* Subscriptions Debug Tool
*
* Add tools for debugging and managing Subscriptions to the
* WooCommerce > System Status > Tools administration screen.
*
* @author Prospress
* @category Admin
* @package WooCommerce Subscriptions/Admin
* @version 2.3
* @since 2.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
} // Exit if accessed directly
/**
* WCS_Debug_Tool Class
*
* Add a debug tool to the WooCommerce > System Status > Tools page.
*/
abstract class WCS_Debug_Tool {
/**
* @var string $tool_key The key used to add the tool to the array of available tools.
*/
protected $tool_key;
/**
* @var array $tool_data Data for this tool, containing:
* - 'name': The section name given to the tool
* - 'button': The text displayed on the tool's button
* - 'desc': The long description for the tool.
* - 'callback': The callback used to perform the tool's action.
*/
protected $tool_data;
/**
* Attach callbacks to hooks and validate required properties are assigned values.
*/
public function init() {
if ( empty( $this->tool_key ) ) {
throw new RuntimeException( __CLASS__ . ' must assign a tool key to $this->tool_key' );
}
if ( empty( $this->tool_data ) ) {
throw new RuntimeException( __CLASS__ . ' must assign an array of data about the tool to $this->tool_data' );
}
add_filter( 'woocommerce_debug_tools', array( $this, 'add_debug_tools' ) );
}
/**
* Add subscription related tools to display on the WooCommerce > System Status > Tools administration screen
*
* @param array $tools Arrays defining the tools displayed on the System Status screen
* @return array
*/
public function add_debug_tools( $tools ) {
$tools[ $this->tool_key ] = $this->tool_data;
return $tools;
}
}

View File

@@ -0,0 +1,141 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Define requirements for a related order data store and provide method for accessing active data store.
*
* Orders can have a special relationship with a subscription if they are used to record a subscription related
* transaction, like a renewal, upgrade/downgrade (switch) or resubscribe. The related order data store provides
* a set of public APIs that can be used to query and manage that relationship.
*
* Parent orders are not managed via this data store as the order data stores inherited by Subscriptions already
* provide APIs for managing the parent relationship.
*
* @version 2.3.0
* @since 2.3.0
* @category Class
* @author Prospress
*/
abstract class WCS_Related_Order_Store {
/** @var WCS_Related_Order_Store */
private static $instance = null;
/**
* Types of relationships the data store supports.
*
* @var array
*/
private static $relation_types = array(
'renewal',
'switch',
'resubscribe',
);
/**
* An array using @see self::$relation_types as keys for more performant checks by @see $this->check_relation_type().
*
* Set when instantiated.
*
* @var array
*/
private static $relation_type_keys = array(
'renewal' => true,
'switch' => true,
'resubscribe' => true,
);
/**
* Get the active related order data store.
*
* @return WCS_Related_Order_Store
*/
final public static function instance() {
if ( empty( self::$instance ) ) {
if ( ! did_action( 'plugins_loaded' ) ) {
wcs_doing_it_wrong( __METHOD__, 'This method was called before the "plugins_loaded" hook. It applies a filter to the related order data store instantiated. For that to work, it should first be called after all plugins are loaded.', '2.3.0' );
}
$class = apply_filters( 'wcs_related_order_store_class', 'WCS_Related_Order_Store_Cached_CPT' );
self::$instance = new $class();
self::$instance->init();
}
return self::$instance;
}
/**
* Stub for initialising the class outside the constructor, for things like attaching callbacks to hooks.
*/
protected function init() {}
/**
* Get orders related to a given subscription with a given relationship type.
*
* @param WC_Order $subscription The order or subscription for which calling code wants to find related orders.
* @param string $relation_type The relationship between the subscription and the orders. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented.
*
* @return array
*/
abstract public function get_related_order_ids( WC_Order $subscription, $relation_type );
/**
* Find subscriptions related to a given order in a given way, if any.
*
* @param WC_Order $order An order that may be linked with subscriptions.
* @param string $relation_type The relationship between the subscription and the orders. Must be 'renewal', 'switch' or 'resubscribe.
* @return array
*/
abstract public function get_related_subscription_ids( WC_Order $order, $relation_type );
/**
* Helper function for linking an order to a subscription via a given relationship.
*
* @param WC_Order $order The order to link with the subscription.
* @param WC_Order $subscription The order or subscription to link the order to.
* @param string $relation_type The relationship between the subscription and the order. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented.
*/
abstract public function add_relation( WC_Order $order, WC_Order $subscription, $relation_type );
/**
* Remove the relationship between a given order and subscription.
*
* @param WC_Order $order An order that may be linked with subscriptions.
* @param WC_Order $subscription A subscription or order to unlink the order with, if a relation exists.
* @param string $relation_type The relationship between the subscription and the order. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented.
*/
abstract public function delete_relation( WC_Order $order, WC_Order $subscription, $relation_type );
/**
* Remove all related orders/subscriptions of a given type from an order.
*
* @param WC_Order $order An order that may be linked with subscriptions.
* @param string $relation_type The relationship between the subscription and the order. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented.
*/
abstract public function delete_relations( WC_Order $order, $relation_type );
/**
* Types of relationships the data store supports.
*
* @return array The possible relationships between a subscription and orders. Includes 'renewal', 'switch' or 'resubscribe' by default.
*/
public function get_relation_types() {
return self::$relation_types;
}
/**
* Check if a given relationship is supported by the data store.
*
* @param string $relation_type The relationship between the subscription and the order. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented.
*
* @throws InvalidArgumentException If the given order relation is not a known type.
*/
protected function check_relation_type( $relation_type ) {
if ( ! isset( self::$relation_type_keys[ $relation_type ] ) ) {
throw new InvalidArgumentException( sprintf( __( 'Invalid relation type: %s. Order relationship type must be one of: %s.', 'woocommerce-subscriptions' ), $relation_type, implode( ', ', $this->get_relation_types() ) ) );
}
}
}

View File

@@ -27,15 +27,10 @@ abstract class WCS_Scheduler {
} }
public function set_date_types_to_schedule() { public function set_date_types_to_schedule() {
$this->date_types_to_schedule = apply_filters( 'woocommerce_subscriptions_date_types_to_schedule', array_keys( wcs_get_subscription_date_types() ) ); $date_types_to_schedule = wcs_get_subscription_date_types();
unset( $date_types_to_schedule['start'], $date_types_to_schedule['last_payment'] );
if ( isset( $this->date_types_to_schedule['start'] ) ) { $this->date_types_to_schedule = apply_filters( 'woocommerce_subscriptions_date_types_to_schedule', array_keys( $date_types_to_schedule ) );
unset( $this->date_types_to_schedule['start'] );
}
if ( isset( $this->date_types_to_schedule['last_payment'] ) ) {
unset( $this->date_types_to_schedule['last_payment'] );
}
} }
protected function get_date_types_to_schedule() { protected function get_date_types_to_schedule() {

View File

@@ -112,8 +112,6 @@ class WC_Subscriptions_Admin {
add_filter( 'set-screen-option', __CLASS__ . '::set_manage_subscriptions_screen_option', 10, 3 ); add_filter( 'set-screen-option', __CLASS__ . '::set_manage_subscriptions_screen_option', 10, 3 );
add_filter( 'woocommerce_system_status_report', __CLASS__ . '::render_system_status_items' );
add_filter( 'woocommerce_payment_gateways_setting_columns', __CLASS__ . '::payment_gateways_rewewal_column' ); add_filter( 'woocommerce_payment_gateways_setting_columns', __CLASS__ . '::payment_gateways_rewewal_column' );
add_action( 'woocommerce_payment_gateways_setting_column_renewals', __CLASS__ . '::payment_gateways_rewewal_support' ); add_action( 'woocommerce_payment_gateways_setting_column_renewals', __CLASS__ . '::payment_gateways_rewewal_support' );
@@ -127,6 +125,10 @@ class WC_Subscriptions_Admin {
add_action( 'woocommerce_admin_order_totals_after_refunded', __CLASS__ . '::maybe_attach_gettext_callback', 10, 1 ); add_action( 'woocommerce_admin_order_totals_after_refunded', __CLASS__ . '::maybe_attach_gettext_callback', 10, 1 );
// Unhook gettext callback to prevent extra call impact // Unhook gettext callback to prevent extra call impact
add_action( 'woocommerce_order_item_add_action_buttons', __CLASS__ . '::maybe_unattach_gettext_callback', 10, 1 ); add_action( 'woocommerce_order_item_add_action_buttons', __CLASS__ . '::maybe_unattach_gettext_callback', 10, 1 );
// Add a reminder on the enable guest checkout setting that subscriptions still require an account
add_filter( 'woocommerce_payment_gateways_settings', array( __CLASS__, 'add_guest_checkout_setting_note' ), 10, 1 );
add_filter( 'woocommerce_account_settings', array( __CLASS__, 'add_guest_checkout_setting_note' ), 10, 1 );
} }
/** /**
@@ -735,6 +737,7 @@ class WC_Subscriptions_Admin {
'bulkEditPeriodMessage' => __( 'Enter the new period, either day, week, month or year:', 'woocommerce-subscriptions' ), 'bulkEditPeriodMessage' => __( 'Enter the new period, either day, week, month or year:', 'woocommerce-subscriptions' ),
'bulkEditLengthMessage' => __( 'Enter a new length (e.g. 5):', 'woocommerce-subscriptions' ), 'bulkEditLengthMessage' => __( 'Enter a new length (e.g. 5):', 'woocommerce-subscriptions' ),
'bulkEditIntervalhMessage' => __( 'Enter a new interval as a single number (e.g. to charge every 2nd month, enter 2):', 'woocommerce-subscriptions' ), 'bulkEditIntervalhMessage' => __( 'Enter a new interval as a single number (e.g. to charge every 2nd month, enter 2):', 'woocommerce-subscriptions' ),
'bulkDeleteOptionLabel' => __( 'Delete all variations without a subscription', 'woocommerce-subscriptions' ),
'oneTimeShippingCheckNonce' => wp_create_nonce( 'one_time_shipping' ), 'oneTimeShippingCheckNonce' => wp_create_nonce( 'one_time_shipping' ),
); );
} else if ( 'edit-shop_order' == $screen->id ) { } else if ( 'edit-shop_order' == $screen->id ) {
@@ -1400,38 +1403,6 @@ class WC_Subscriptions_Admin {
return ob_get_clean(); return ob_get_clean();
} }
/**
* Renders the Subscription information in the WC status page
*/
public static function render_system_status_items() {
$debug_data = array();
$is_wcs_debug = defined( 'WCS_DEBUG' ) ? WCS_DEBUG : false;
$debug_data['wcs_debug'] = array(
'name' => _x( 'WCS_DEBUG', 'label that indicates whether debugging is turned on for the plugin', 'woocommerce-subscriptions' ),
'note' => ( $is_wcs_debug ) ? __( 'Yes', 'woocommerce-subscriptions' ) : __( 'No', 'woocommerce-subscriptions' ),
'success' => $is_wcs_debug ? 0 : 1,
);
$debug_data['wcs_staging'] = array(
'name' => _x( 'Subscriptions Mode', 'Live or Staging, Label on WooCommerce -> System Status page', 'woocommerce-subscriptions' ),
'note' => '<strong>' . ( ( WC_Subscriptions::is_duplicate_site() ) ? _x( 'Staging', 'refers to staging site', 'woocommerce-subscriptions' ) : _x( 'Live', 'refers to live site', 'woocommerce-subscriptions' ) ) . '</strong>',
'success' => ( WC_Subscriptions::is_duplicate_site() ) ? 0 : 1,
);
$theme_overrides = self::get_theme_overrides();
$debug_data['wcs_theme_overrides'] = array(
'name' => _x( 'Subscriptions Template Theme Overrides', 'label for the system status page', 'woocommerce-subscriptions' ),
'mark' => '',
'mark_icon' => $theme_overrides['has_outdated_templates'] ? 'warning' : 'yes',
'data' => $theme_overrides,
);
$debug_data = apply_filters( 'wcs_system_status', $debug_data );
include( plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'templates/admin/status.php' );
}
/** /**
* Adds Subscriptions specific details to the WooCommerce System Status report. * Adds Subscriptions specific details to the WooCommerce System Status report.
* *
@@ -1673,57 +1644,6 @@ class WC_Subscriptions_Admin {
return apply_filters( 'wcs_admin_is_subscription_product_save_request', $is_subscription_product_save_request, $post_id, $product_types ); return apply_filters( 'wcs_admin_is_subscription_product_save_request', $is_subscription_product_save_request, $post_id, $product_types );
} }
/**
* Determine which of our files have been overridden by the theme.
*
* @author Jeremy Pry
* @return array Theme override data.
*/
private static function get_theme_overrides() {
$wcs_template_dir = dirname( WC_Subscriptions::$plugin_file ) . '/templates/';
$wc_template_path = trailingslashit( wc()->template_path() );
$theme_root = trailingslashit( get_theme_root() );
$overridden = array();
$outdated = false;
$templates = WC_Admin_Status::scan_template_files( $wcs_template_dir );
foreach ( $templates as $file ) {
$theme_file = $is_outdated = false;
$locations = array(
get_stylesheet_directory() . "/{$file}",
get_stylesheet_directory() . "/{$wc_template_path}{$file}",
get_template_directory() . "/{$file}",
get_template_directory() . "/{$wc_template_path}{$file}",
);
foreach ( $locations as $location ) {
if ( is_readable( $location ) ) {
$theme_file = $location;
break;
}
}
if ( ! empty( $theme_file ) ) {
$core_version = WC_Admin_Status::get_file_version( $wcs_template_dir . $file );
$theme_version = WC_Admin_Status::get_file_version( $theme_file );
if ( $core_version && ( empty( $theme_version ) || version_compare( $theme_version, $core_version, '<' ) ) ) {
$outdated = $is_outdated = true;
}
$overridden[] = array(
'file' => str_replace( $theme_root, '', $theme_file ),
'version' => $theme_version,
'core_version' => $core_version,
'is_outdated' => $is_outdated,
);
}
}
return array(
'has_outdated_templates' => $outdated,
'overridden_templates' => $overridden,
);
}
/** /**
* Insert a setting or an array of settings after another specific setting by its ID. * Insert a setting or an array of settings after another specific setting by its ID.
* *
@@ -1754,6 +1674,41 @@ class WC_Subscriptions_Admin {
} }
} }
/**
* Add a reminder on the enable guest checkout setting that subscriptions still require an account
* @since 2.3.0
* @param array $settings The list of settings
*/
public static function add_guest_checkout_setting_note( $settings ) {
$is_wc_pre_3_4_0 = WC_Subscriptions::is_woocommerce_pre( '3.4.0' );
$current_filter = current_filter();
if ( ( $is_wc_pre_3_4_0 && 'woocommerce_payment_gateways_settings' !== $current_filter ) || ( ! $is_wc_pre_3_4_0 && 'woocommerce_account_settings' !== $current_filter ) ) {
return $settings;
}
if ( ! is_array( $settings ) ) {
return $settings;
}
foreach ( $settings as &$value ) {
if ( isset( $value['id'] ) && 'woocommerce_enable_guest_checkout' === $value['id'] ) {
$value['desc_tip'] = ! empty( $value['desc_tip'] ) ? $value['desc_tip'] . ' ' : '';
$value['desc_tip'] .= __( 'Note that purchasing a subscription still requires an account.', 'woocommerce-subscriptions' );
break;
}
}
return $settings;
}
/**
* Renders the Subscription information in the WC status page
*/
public static function render_system_status_items() {
_deprecated_function( __METHOD__, '2.3', 'WCS_Admin_System_Status::render_system_status_items()' );
WCS_Admin_System_Status::render_system_status_items();
}
/** /**
* Outputs the contents of the "Renewal Orders" meta box. * Outputs the contents of the "Renewal Orders" meta box.
* *

View File

@@ -41,6 +41,7 @@ class WCS_Admin_Meta_Boxes {
add_action( 'woocommerce_order_action_wcs_process_renewal', __CLASS__ . '::process_renewal_action_request', 10, 1 ); add_action( 'woocommerce_order_action_wcs_process_renewal', __CLASS__ . '::process_renewal_action_request', 10, 1 );
add_action( 'woocommerce_order_action_wcs_create_pending_renewal', __CLASS__ . '::create_pending_renewal_action_request', 10, 1 ); add_action( 'woocommerce_order_action_wcs_create_pending_renewal', __CLASS__ . '::create_pending_renewal_action_request', 10, 1 );
add_action( 'woocommerce_order_action_wcs_create_pending_parent', __CLASS__ . '::create_pending_parent_action_request', 10, 1 );
add_filter( 'woocommerce_resend_order_emails_available', __CLASS__ . '::remove_order_email_actions', 0, 1 ); add_filter( 'woocommerce_resend_order_emails_available', __CLASS__ . '::remove_order_email_actions', 0, 1 );
@@ -55,7 +56,7 @@ class WCS_Admin_Meta_Boxes {
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-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( 'Billing Schedule', 'meta box title', 'woocommerce-subscriptions' ), 'WCS_Meta_Box_Schedule::output', 'shop_subscription', 'side', 'default' ); 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' ); remove_meta_box( 'woocommerce-order-data', 'shop_subscription', 'normal' );
@@ -91,9 +92,10 @@ class WCS_Admin_Meta_Boxes {
global $post; global $post;
// Get admin screen id // Get admin screen id
$screen = get_current_screen(); $screen = get_current_screen();
$screen_id = isset( $screen->id ) ? $screen->id : '';
if ( 'shop_subscription' == $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( 'jstz', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/admin/jstz.min.js' );
@@ -112,8 +114,9 @@ class WCS_Admin_Meta_Boxes {
'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' ), '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(), 'payment_method' => wcs_get_subscription( $post )->get_payment_method(),
'search_customers_nonce' => wp_create_nonce( 'search-customers' ), 'search_customers_nonce' => wp_create_nonce( 'search-customers' ),
'get_customer_orders_nonce' => wp_create_nonce( 'get-customer-orders' ),
) ) ); ) ) );
} else if ( 'shop_order' == $screen->id ) { } 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_enqueue_script( 'wcs-admin-meta-boxes-order', plugin_dir_url( WC_Subscriptions::$plugin_file ) . 'assets/js/admin/wcs-meta-boxes-order.js' );
@@ -122,6 +125,16 @@ class WCS_Admin_Meta_Boxes {
) )
); );
} }
// 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
);
}
} }
/** /**
@@ -140,8 +153,11 @@ class WCS_Admin_Meta_Boxes {
$actions['wcs_process_renewal'] = esc_html__( 'Process renewal', 'woocommerce-subscriptions' ); $actions['wcs_process_renewal'] = esc_html__( 'Process renewal', 'woocommerce-subscriptions' );
} }
$actions['wcs_create_pending_renewal'] = esc_html__( 'Create pending renewal order', '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 ) ) { } else if ( self::can_renewal_order_be_retried( $theorder ) ) {
$actions['wcs_retry_renewal_payment'] = esc_html__( 'Retry Renewal Payment', 'woocommerce-subscriptions' ); $actions['wcs_retry_renewal_payment'] = esc_html__( 'Retry Renewal Payment', 'woocommerce-subscriptions' );
} }
@@ -173,12 +189,46 @@ class WCS_Admin_Meta_Boxes {
$renewal_order = wcs_create_renewal_order( $subscription ); $renewal_order = wcs_create_renewal_order( $subscription );
if ( ! $subscription->is_manual() ) { 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 $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();
}
} }
$subscription->add_order_note( __( 'Create pending renewal order requested by admin action.', 'woocommerce-subscriptions' ), false, true ); $subscription->add_order_note( __( 'Create pending renewal order requested by admin action.', 'woocommerce-subscriptions' ), false, true );
} }
/**
* 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();
}
}
$subscription->add_order_note( __( 'Create pending parent order requested by admin action.', 'woocommerce-subscriptions' ), false, true );
}
/** /**
* Removes order related emails from the available actions. * Removes order related emails from the available actions.
* *

View File

@@ -0,0 +1,272 @@
<?php
/**
* API for creating and displaying an admin notice.
*
* @since 2.3.0
* @category Class
* @author Prospress
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class WCS_Admin_Notice {
/**
* The notice type. Can be notice, notice-info, updated, error or a custom notice type.
*
* @var string
*/
protected $type;
/**
* The notice heading. Optional property.
*
* @var string
*/
protected $heading;
/**
* The notice's main content.
*
* @var string
*/
protected $content;
/**
* The notice's content type. Can be 'simple' or 'html'.
*
* @var string
*/
protected $content_type;
/**
* The container div's attributes. Optional property.
*
* @see WCS_Admin_Notice::__construct() for example format.
* @var array
*/
protected $attributes;
/**
* The URL used to dismiss the notice. Optional property.
*
* @var string
*/
protected $dismiss_url;
/**
* A list of actions the user can take
*
* @see WCS_Admin_Notice::set_actions() for example format.
* @var array
*/
protected $actions;
/**
* Constructor.
*
* @param string $type The notice type. Can be notice, notice-info, updated, error or a custom notice type.
* @param array $attributes The container div's attributes. Optional.
* @param string $dismiss_url The URL used to dismiss the notice. Optional.
* @since 2.3.0
*/
public function __construct( $type, array $attributes = array(), $dismiss_url = '' ) {
$this->type = $type;
$this->attributes = $attributes;
$this->dismiss_url = $dismiss_url;
}
/**
* Display the admin notice.
*
* Will print the notice if called during the 'admin_notices' action. Otherwise will attach a callback and display the notice when the 'admin_notices' is triggered.
*
* @since 2.3.0
*/
public function display() {
if ( 'admin_notices' !== current_filter() ) {
add_action( 'admin_notices', array( $this, __FUNCTION__ ) );
return;
}
wc_get_template(
'html-admin-notice.php',
array( 'notice' => $this ),
'',
plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'templates/admin/'
);
}
/**
* Whether the admin notice is dismissible.
*
* @since 2.3.0
* @return boolean
*/
public function is_dismissible() {
return ! empty( $this->dismiss_url );
}
/**
* Whether the admin notice has a heading or not.
*
* @since 2.3.0
* @return boolean
*/
public function has_heading() {
return ! empty( $this->heading );
}
/**
* Whether the admin notice has actions or not.
*
* @since 2.3.0
* @return boolean
*/
public function has_actions() {
return ! empty( $this->actions ) && is_array( $this->actions );
}
/* Printers */
/**
* Print the notice's heading.
*
* @since 2.3.0
*/
public function print_heading() {
echo esc_html( $this->heading );
}
/**
* Get the notice's content.
*
* Will wrap simple notices in paragraph elements (<p></p>) for correct styling and print HTML notices unchanged.
*
* @since 2.3.0
*/
public function print_content() {
switch ( $this->content_type ) {
case 'simple':
echo '<p>' . wp_kses_post( $this->content ) . '</p>';
break;
case 'html':
echo wp_kses_post( $this->content );
break;
case 'template':
wc_get_template( $this->content['template_name'], $this->content['args'], '', $this->content['template_path'] );
break;
}
}
/**
* Print the notice's attributes.
*
* Turns the attributes array into 'id="id" class="class class class"' strings.
*
* @since 2.3.0
*/
public function print_attributes() {
$attributes = $this->attributes;
$attributes['class'][] = $this->type;
if ( $this->is_dismissible() ) {
$attributes['style'][] = 'position: relative;';
}
foreach ( $attributes as $attribute => $values ) {
$attributes[ $attribute ] = $attribute . '="' . implode( ' ', array_map( 'esc_attr', $values ) ) . '"';
}
echo wp_kses_post( implode( ' ', $attributes ) );
}
/**
* Print the notice's dismiss URL.
*
* @since 2.3.0
*/
public function print_dismiss_url() {
echo esc_attr( $this->dismiss_url );
}
/* Getters */
/**
* Get the notice's actions.
*
* @since 2.3.0
* @return array
*/
public function get_actions() {
return $this->actions;
}
/* Setters */
/**
* Set the notice's content to a simple string.
*
* @param string $content The notice content.
*/
public function set_simple_content( $content ) {
$this->content_type = 'simple';
$this->content = $content;
}
/**
* Set the notice's content to a string containing HTML elements.
*
* @param string $html The notice content.
*/
public function set_html_content( $html ) {
$this->content_type = 'html';
$this->content = $html;
}
/**
* Set the notice's content to a string containing HTML elements.
*
* @since 2.3.0
* @param string $template_name Template name.
* @param string $template_path Template path.
* @param array $args Arguments. (default: array).
*/
public function set_content_template( $template_name, $template_path, $args = array() ) {
$this->content_type = 'template';
$this->content = array(
'template_name' => $template_name,
'template_path' => $template_path,
'args' => $args,
);
}
/**
* Set actions the user can make in response to this notice.
*
* @since 2.3.0
* @param array $actions The actions the user can make. Example format:
* array(
* array(
* 'name' => 'The actions's name', // This arg will appear as the button text.
* 'url' => 'url', // The url the user will be directed to if clicked.
* 'class' => 'class string', // The class attribute string used in the link element. Optional. Will default to 'docs button' - a plain button.
* )
* )
*/
public function set_actions( array $actions ) {
$this->actions = $actions;
}
/**
* Set notice's heading. If set this will appear at the top of the notice wrapped in a h2 element.
*
* @since 2.3.0
* @param string $heading The notice heading.
*/
public function set_heading( $heading ) {
$this->heading = $heading;
}
}

View File

@@ -593,20 +593,7 @@ class WCS_Admin_Post_Types {
case 'next_payment_date': case 'next_payment_date':
case 'last_payment_date': case 'last_payment_date':
case 'end_date': case 'end_date':
$date_type_map = array( 'start_date' => 'date_created', 'last_payment_date' => 'last_order_date_created' ); $column_content = self::get_date_column_content( $the_subscription, $column );
$date_type = array_key_exists( $column, $date_type_map ) ? $date_type_map[ $column ] : $column;
if ( 0 == $the_subscription->get_time( $date_type, 'gmt' ) ) {
$column_content .= '-';
} else {
$column_content .= sprintf( '<time class="%s" title="%s">%s</time>', esc_attr( $column ), esc_attr( date( __( 'Y/m/d g:i:s A', 'woocommerce-subscriptions' ) , $the_subscription->get_time( $date_type, 'site' ) ) ), esc_html( $the_subscription->get_date_to_display( $date_type ) ) );
if ( 'next_payment_date' == $column && $the_subscription->payment_method_supports( 'gateway_scheduled_payments' ) && ! $the_subscription->is_manual() && $the_subscription->has_status( 'active' ) ) {
$column_content .= '<div class="woocommerce-help-tip" data-tip="' . esc_attr__( 'This date should be treated as an estimate only. The payment gateway for this subscription controls when payments are processed.', 'woocommerce-subscriptions' ) . '"></div>';
}
}
$column_content = $column_content;
break; break;
case 'orders' : case 'orders' :
@@ -618,6 +605,32 @@ class WCS_Admin_Post_Types {
} }
/**
* Return the content for a date column on the Edit Subscription screen
*
* @param WC_Subscription $subscription
* @param string $column
* @return string
* @since 2.3.0
*/
public static function get_date_column_content( $subscription, $column ) {
$date_type_map = array( 'start_date' => 'date_created', 'last_payment_date' => 'last_order_date_created' );
$date_type = array_key_exists( $column, $date_type_map ) ? $date_type_map[ $column ] : $column;
if ( 0 == $subscription->get_time( $date_type, 'gmt' ) ) {
$column_content = '-';
} else {
$column_content = sprintf( '<time class="%s" title="%s">%s</time>', esc_attr( $column ), esc_attr( date( __( 'Y/m/d g:i:s A', 'woocommerce-subscriptions' ) , $subscription->get_time( $date_type, 'site' ) ) ), esc_html( $subscription->get_date_to_display( $date_type ) ) );
if ( 'next_payment_date' == $column && $subscription->payment_method_supports( 'gateway_scheduled_payments' ) && ! $subscription->is_manual() && $subscription->has_status( 'active' ) ) {
$column_content .= '<div class="woocommerce-help-tip" data-tip="' . esc_attr__( 'This date should be treated as an estimate only. The payment gateway for this subscription controls when payments are processed.', 'woocommerce-subscriptions' ) . '"></div>';
}
}
return $column_content;
}
/** /**
* Make columns sortable * Make columns sortable
* *
@@ -653,80 +666,19 @@ class WCS_Admin_Post_Types {
return; return;
} }
$search_fields = array_map( 'wc_clean', apply_filters( 'woocommerce_shop_subscription_search_fields', array( $post_ids = wcs_subscription_search( $_GET['s'] );
'_order_key',
'_billing_company',
'_billing_address_1',
'_billing_address_2',
'_billing_city',
'_billing_postcode',
'_billing_country',
'_billing_state',
'_billing_email',
'_billing_phone',
'_shipping_address_1',
'_shipping_address_2',
'_shipping_city',
'_shipping_postcode',
'_shipping_country',
'_shipping_state',
) ) );
$search_order_id = str_replace( 'Order #', '', $_GET['s'] ); if ( ! empty( $post_ids ) ) {
if ( ! is_numeric( $search_order_id ) ) {
$search_order_id = 0; // Remove s - we don't want to search order name
unset( $wp->query_vars['s'] );
// so we know we're doing this
$wp->query_vars['shop_subscription_search'] = true;
// Search by found posts
$wp->query_vars['post__in'] = $post_ids;
} }
// Search orders
$post_ids = array_unique( array_merge(
$wpdb->get_col(
$wpdb->prepare( "
SELECT p1.post_id
FROM {$wpdb->postmeta} p1
INNER JOIN {$wpdb->postmeta} p2 ON p1.post_id = p2.post_id
WHERE
( p1.meta_key = '_billing_first_name' AND p2.meta_key = '_billing_last_name' AND CONCAT(p1.meta_value, ' ', p2.meta_value) LIKE '%%%s%%' )
OR
( p1.meta_key = '_shipping_first_name' AND p2.meta_key = '_shipping_last_name' AND CONCAT(p1.meta_value, ' ', p2.meta_value) LIKE '%%%s%%' )
OR
( p1.meta_key IN ('" . implode( "','", esc_sql( $search_fields ) ) . "') AND p1.meta_value LIKE '%%%s%%' )
",
esc_attr( $_GET['s'] ), esc_attr( $_GET['s'] ), esc_attr( $_GET['s'] )
)
),
$wpdb->get_col(
$wpdb->prepare( "
SELECT order_id
FROM {$wpdb->prefix}woocommerce_order_items as order_items
WHERE order_item_name LIKE '%%%s%%'
",
esc_attr( $_GET['s'] )
)
),
$wpdb->get_col(
$wpdb->prepare( "
SELECT p1.ID
FROM {$wpdb->posts} p1
INNER JOIN {$wpdb->postmeta} p2 ON p1.ID = p2.post_id
INNER JOIN {$wpdb->users} u ON p2.meta_value = u.ID
WHERE u.user_email LIKE '%%%s%%'
AND p2.meta_key = '_customer_user'
AND p1.post_type = 'shop_subscription'
",
esc_attr( $_GET['s'] )
)
),
array( $search_order_id )
) );
// Remove s - we don't want to search order name
unset( $wp->query_vars['s'] );
// so we know we're doing this
$wp->query_vars['shop_subscription_search'] = true;
// Search by found posts
$wp->query_vars['post__in'] = $post_ids;
} }
/** /**

View File

@@ -0,0 +1,347 @@
<?php
/**
* Subscriptions System Status
*
* Adds additional Subscriptions related information to the WooCommerce System Status.
*
* @package WooCommerce Subscriptions
* @subpackage WC_Subscriptions_Admin
* @category Class
* @author Prospress
* @since 2.3.0
*/
class WCS_Admin_System_Status {
/**
* @var int Subscriptions' WooCommerce Marketplace product ID
*/
const WCS_PRODUCT_ID = 27147;
/**
* Attach callbacks
*
* @since 2.3.0
*/
public static function init() {
add_filter( 'woocommerce_system_status_report', array( __CLASS__, 'render_system_status_items' ) );
}
/**
* Renders the Subscription information in the WC status page
*
* @since 2.3.0
*/
public static function render_system_status_items() {
$store_data = $subscriptions_data = $subscriptions_by_payment_gateway_data = $payment_gateway_data = array();
self::set_debug_mode( $subscriptions_data );
self::set_staging_mode( $subscriptions_data );
self::set_theme_overrides( $subscriptions_data );
self::set_subscription_statuses( $subscriptions_data );
self::set_woocommerce_account_data( $subscriptions_data );
// Subscriptions by Payment Gateway
self::set_subscriptions_by_payment_gateway( $subscriptions_by_payment_gateway );
// Payment gateway features
self::set_subscriptions_payment_gateway_support( $payment_gateway_data );
// Store settings
self::set_store_location( $store_data );
$system_status_sections = array(
array(
'title' => __( 'Subscriptions', 'woocommerce-subscriptions' ),
'tooltip' => __( 'This section shows any information about Subscriptions.', 'woocommerce-subscriptions' ),
'data' => apply_filters( 'wcs_system_status', $subscriptions_data ),
),
array(
'title' => __( 'Store Setup', 'woocommerce-subscriptions' ),
'tooltip' => __( 'This section shows general information about the store.', 'woocommerce-subscriptions' ),
'data' => $store_data,
),
array(
'title' => __( 'Subscriptions by Payment Gateway', 'woocommerce-subscriptions' ),
'tooltip' => __( 'This section shows information about Subscription payment methods.', 'woocommerce-subscriptions' ),
'data' => $subscriptions_by_payment_gateway,
),
array(
'title' => __( 'Payment Gateway Support', 'woocommerce-subscriptions' ),
'tooltip' => __( 'This section shows information about payment gateway feature support.', 'woocommerce-subscriptions' ),
'data' => $payment_gateway_data,
),
);
foreach ( $system_status_sections as $section ) {
$section_title = $section['title'];
$section_tooltip = $section['tooltip'];
$debug_data = $section['data'];
include( plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'templates/admin/status.php' );
}
}
/**
* Include WCS_DEBUG flag
*/
private static function set_debug_mode( &$debug_data ) {
$is_wcs_debug = defined( 'WCS_DEBUG' ) ? WCS_DEBUG : false;
$debug_data['wcs_debug'] = array(
'name' => _x( 'WCS_DEBUG', 'label that indicates whether debugging is turned on for the plugin', 'woocommerce-subscriptions' ),
'label' => 'WCS_DEBUG',
'note' => ( $is_wcs_debug ) ? __( 'Yes', 'woocommerce-subscriptions' ) : __( 'No', 'woocommerce-subscriptions' ),
'success' => $is_wcs_debug ? 0 : 1,
);
}
/**
* Include the staging/live mode the store is running in.
*/
private static function set_staging_mode( &$debug_data ) {
$debug_data['wcs_staging'] = array(
'name' => _x( 'Subscriptions Mode', 'Live or Staging, Label on WooCommerce -> System Status page', 'woocommerce-subscriptions' ),
'label' => 'Subscriptions Mode',
'note' => '<strong>' . ( ( WC_Subscriptions::is_duplicate_site() ) ? _x( 'Staging', 'refers to staging site', 'woocommerce-subscriptions' ) : _x( 'Live', 'refers to live site', 'woocommerce-subscriptions' ) ) . '</strong>',
'success' => ( WC_Subscriptions::is_duplicate_site() ) ? 0 : 1,
);
}
/**
* List any Subscriptions template overrides.
*/
private static function set_theme_overrides( &$debug_data ) {
$theme_overrides = self::get_theme_overrides();
if ( ! empty( $theme_overrides['overrides'] ) ) {
$debug_data['wcs_theme_overrides'] = array(
'name' => _x( 'Subscriptions Template Theme Overrides', 'label for the system status page', 'woocommerce-subscriptions' ),
'label' => 'Subscriptions Template Theme Overrides',
'data' => $theme_overrides['overrides'],
);
// Include a note on how to update if the templates are out of date.
if ( ! empty( $theme_overrides['has_outdated_templates'] ) && true === $theme_overrides['has_outdated_templates'] ) {
$debug_data['wcs_theme_overrides'] += array(
'mark_icon' => 'warning',
'note' => sprintf( __( '%sLearn how to update%s', 'woocommerce-subscriptions' ), '<a href="https://docs.woocommerce.com/document/fix-outdated-templates-woocommerce/" target="_blank">', '</a>' ),
);
}
}
}
/**
* Determine which of our files have been overridden by the theme.
*
* @author Jeremy Pry
* @return array Theme override data.
*/
private static function get_theme_overrides() {
$wcs_template_dir = dirname( WC_Subscriptions::$plugin_file ) . '/templates/';
$wc_template_path = trailingslashit( wc()->template_path() );
$theme_root = trailingslashit( get_theme_root() );
$overridden = array();
$outdated = false;
$templates = WC_Admin_Status::scan_template_files( $wcs_template_dir );
foreach ( $templates as $file ) {
$theme_file = $is_outdated = false;
$locations = array(
get_stylesheet_directory() . "/{$file}",
get_stylesheet_directory() . "/{$wc_template_path}{$file}",
get_template_directory() . "/{$file}",
get_template_directory() . "/{$wc_template_path}{$file}",
);
foreach ( $locations as $location ) {
if ( is_readable( $location ) ) {
$theme_file = $location;
break;
}
}
if ( ! empty( $theme_file ) ) {
$core_version = WC_Admin_Status::get_file_version( $wcs_template_dir . $file );
$theme_version = WC_Admin_Status::get_file_version( $theme_file );
$overridden_template_output = sprintf( '<code>%s</code>', esc_html( str_replace( $theme_root, '', $theme_file ) ) );
if ( $core_version && ( empty( $theme_version ) || version_compare( $theme_version, $core_version, '<' ) ) ) {
$outdated = true;
$overridden_template_output .= sprintf(
/* translators: %1$s is the file version, %2$s is the core version */
esc_html__( 'version %1$s is out of date. The core version is %2$s', 'woocommerce-subscriptions' ),
'<strong style="color:red">' . esc_html( $theme_version ) . '</strong>',
'<strong>' . esc_html( $core_version ) . '</strong>'
);
}
$overridden['overrides'][] = $overridden_template_output;
}
}
$overridden['has_outdated_templates'] = $outdated;
return $overridden;
}
/**
* Add a breakdown of Subscriptions per status.
*/
private static function set_subscription_statuses( &$debug_data ) {
$subscriptions_by_status = (array) wp_count_posts( 'shop_subscription' );
$subscriptions_by_status_output = array();
foreach ( $subscriptions_by_status as $status => $count ) {
if ( ! empty( $count ) ) {
$subscriptions_by_status_output[] = $status . ': ' . $count;
}
}
$debug_data['wcs_subscriptions_by_status'] = array(
'name' => _x( 'Subscription Statuses', 'label for the system status page', 'woocommerce-subscriptions' ),
'label' => 'Subscription Statuses',
'mark' => '',
'mark_icon' => '',
'data' => $subscriptions_by_status_output,
);
}
/**
* Include information about whether the store is linked to a WooCommerce account and whether they have an active WCS product key.
*/
private static function set_woocommerce_account_data( &$debug_data ) {
if ( ! class_exists( 'WC_Helper' ) ) {
return;
}
$woocommerce_account_auth = WC_Helper_Options::get( 'auth' );
$woocommerce_account_connected = ! empty( $woocommerce_account_auth );
$debug_data['wcs_woocommerce_account_connected'] = array(
'name' => _x( 'WooCommerce Account Connected', 'label for the system status page', 'woocommerce-subscriptions' ),
'label' => 'WooCommerce Account Connected',
'note' => $woocommerce_account_connected ? 'Yes' : 'No',
'success' => $woocommerce_account_connected,
);
if ( ! $woocommerce_account_connected ) {
return;
}
// Check for an active WooCommerce Subscriptions product key
$woocommerce_account_subscriptions = WC_Helper::get_subscriptions();
$site_id = absint( $woocommerce_account_auth['site_id'] );
$has_active_product_key = false;
foreach ( $woocommerce_account_subscriptions as $subscription ) {
if ( isset( $subscription['product_id'] ) && self::WCS_PRODUCT_ID === $subscription['product_id'] ) {
$has_active_product_key = in_array( $site_id, $subscription['connections'] );
break;
}
}
$debug_data['wcs_active_product_key'] = array(
'name' => _x( 'Active Product Key', 'label for the system status page', 'woocommerce-subscriptions' ),
'label' => 'Active Product Key',
'note' => $has_active_product_key ? 'Yes' : 'No',
'success' => $has_active_product_key,
);
}
/**
* Add a breakdown of subscriptions per payment gateway.
*/
private static function set_subscriptions_by_payment_gateway( &$debug_data ) {
global $wpdb;
$gateways = WC()->payment_gateways->get_available_payment_gateways();
$results = $wpdb->get_results( "
SELECT COUNT(subscriptions.ID) as count, post_meta.meta_value as payment_method, subscriptions.post_status
FROM $wpdb->posts as subscriptions RIGHT JOIN $wpdb->postmeta as post_meta ON post_meta.post_id = subscriptions.ID
WHERE subscriptions.post_type = 'shop_subscription' && post_meta.meta_key = '_payment_method'
GROUP BY post_meta.meta_value, subscriptions.post_status", ARRAY_A );
$subscriptions_payment_gateway_data = array();
foreach ( $results as $result ) {
$payment_method = $result['payment_method'];
$subscription_status = $result['post_status'];
if ( isset( $gateways[ $payment_method ] ) ) {
$payment_method_name = $payment_method_label = $gateways[ $payment_method ]->method_title;
} else {
$payment_method_label = $payment_method = 'other';
$payment_method_name = _x( 'Other', 'label for the system status page', 'woocommerce-subscriptions' );
}
$key = 'wcs_payment_method_subscriptions_by' . $payment_method;
if ( ! isset( $debug_data[ $key ] ) ) {
$debug_data[ $key ] = array(
'name' => $payment_method_name,
'label' => $payment_method_label,
'data' => array(),
);
}
$debug_data[ $key ]['data'][] = $subscription_status . ': ' . $result['count'];
}
}
/**
* List the enabled payment gateways and the features they support.
*/
private static function set_subscriptions_payment_gateway_support( &$debug_data ) {
$gateways = WC()->payment_gateways->get_available_payment_gateways();
foreach ( $gateways as $gateway_id => $gateway ) {
$debug_data[ 'wcs_' . $gateway_id . '_feature_support' ] = array(
'name' => $gateway->method_title,
'label' => $gateway->method_title,
'data' => $gateway->supports,
);
if ( 'paypal' === $gateway_id ) {
$are_reference_transactions_enabled = WCS_PayPal::are_reference_transactions_enabled();
$debug_data['wcs_paypal_reference_transactions'] = array(
'name' => _x( 'PayPal Reference Transactions Enabled', 'label for the system status page', 'woocommerce-subscriptions' ),
'label' => 'PayPal Reference Transactions Enabled',
'mark_icon' => $are_reference_transactions_enabled ? 'yes' : 'warning',
'note' => $are_reference_transactions_enabled ? 'Yes' : 'No',
'success' => $are_reference_transactions_enabled,
);
}
}
}
/**
* Add the store's country and state information.
*/
private static function set_store_location( &$debug_data ) {
$store_base_location = wc_get_base_location();
$countries = WC()->countries->get_countries();
$states = WC()->countries->get_states( $store_base_location['country'] );
$store_location_string = '';
if ( isset( $countries[ $store_base_location['country'] ] ) ) {
$store_location_string = $countries[ $store_base_location['country'] ];
if ( ! empty( $states[ $store_base_location['state'] ] ) ) {
$store_location_string .= ' &mdash; ' . $states[ $store_base_location['state'] ];
}
}
$debug_data['wcs_store_location'] = array(
'name' => _x( 'Country / State', 'label for the system status page', 'woocommerce-subscriptions' ),
'label' => 'Country / State',
'note' => $store_location_string,
'mark' => '',
'mark_icon' => '',
);
}
}

View File

@@ -0,0 +1,59 @@
<?php
/**
* Debug Tool with methods to update cached data in the background
*
* Add tools for debugging and managing Subscriptions to the
* WooCommerce > System Status > Tools administration screen.
*
* @author Prospress
* @category Admin
* @package WooCommerce Subscriptions/Admin
* @version 2.3
* @since 2.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
} // Exit if accessed directly
/**
* WCS_Debug_Tool_Cache_Background_Updater Class
*
* Provide APIs for a debug tool to update a cached data store's data in the background using Action Scheduler.
*/
class WCS_Debug_Tool_Cache_Background_Updater extends WCS_Background_Updater {
/**
* @var WCS_Cache_Updater The data store used to manage the cache.
*/
protected $data_store;
/**
* WCS_Debug_Tool_Cache_Background_Updater constructor.
*
* @param string $scheduled_hook The hook to schedule to run the update.
* @param WCS_Cache_Updater $data_store
*/
public function __construct( $scheduled_hook, WCS_Cache_Updater $data_store ) {
$this->scheduled_hook = $scheduled_hook;
$this->data_store = $data_store;
}
/**
* Get the items to be updated, if any.
*
* @return array An array of items to update, or empty array if there are no items to update.
*/
protected function get_items_to_update() {
return $this->data_store->get_items_to_update();
}
/**
* Run the update for a single item.
*
* @param mixed $item The item to update.
*/
protected function update_item( $item ) {
return $this->data_store->update_items_cache( $item );
}
}

View File

@@ -0,0 +1,54 @@
<?php
/**
* WCS_Debug_Tool_Cache_Eraser Class
*
* Add a debug tool to the WooCommerce > System Status > Tools page for
* deleting a data store's cache/s.
*
* @author Prospress
* @category Admin
* @package WooCommerce Subscriptions/Admin
* @version 2.3
* @since 2.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
} // Exit if accessed directly
/**
* WCS_Debug_Tool_Cache_Eraser Class
*
* Add a debug tool to the WooCommerce > System Status > Tools page for
* deleting a data store's cache/s.
*/
class WCS_Debug_Tool_Cache_Eraser extends WCS_Debug_Tool_Cache_Updater {
/**
* WCS_Debug_Tool_Cache_Eraser constructor.
*
* @param string $tool_key The key used to add the tool to the array of available tools.
* @param string $tool_name The section name given to the tool on the admin screen.
* @param string $tool_description The long description for the tool displayed on the admin screen.
* @param WCS_Cache_Updater $data_store The cached data store this tool will use for erasing cache.
*/
public function __construct( $tool_key, $tool_name, $tool_description, WCS_Cache_Updater $data_store ) {
$this->tool_key = $tool_key;
$this->data_store = $data_store;
$this->tool_data = array(
'name' => $tool_name,
'button' => $tool_name,
'desc' => $tool_description,
'callback' => array( $this, 'delete_caches' ),
);
}
/**
* Clear all of the data store's caches.
*/
public function delete_caches() {
if ( $this->is_data_store_cached() ) {
$this->data_store->delete_all_caches();
}
}
}

View File

@@ -0,0 +1,68 @@
<?php
/**
* WCS_Debug_Tool_Related_Order_Cache_Generator Class
*
* Add a debug tool to the WooCommerce > System Status > Tools page for generating a cache.
*
* @author Prospress
* @category Admin
* @package WooCommerce Subscriptions/Admin
* @version 2.3
* @since 2.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
} // Exit if accessed directly
/**
* WCS_Debug_Tool_Cache_Generator Class
*
* Add a debug tool to the WooCommerce > System Status > Tools page for generating a cache.
*/
class WCS_Debug_Tool_Cache_Generator extends WCS_Debug_Tool_Cache_Updater {
/**
* @var WCS_Background_Updater $update The instance used to generate the cache data in the background.
*/
protected $cache_updater;
/**
* WCS_Debug_Tool_Cache_Generator constructor.
*
* @param string $tool_key The key used to add the tool to the array of available tools.
* @param string $tool_name The section name given to the tool on the admin screen.
* @param string $tool_description The long description for the tool displayed on the admin screen.
* @param WCS_Cache_Updater $data_store
* @param WCS_Background_Updater $cache_updater
*/
public function __construct( $tool_key, $tool_name, $tool_description, WCS_Cache_Updater $data_store, WCS_Background_Updater $cache_updater ) {
$this->tool_key = $tool_key;
$this->data_store = $data_store;
$this->cache_updater = $cache_updater;
$this->tool_data = array(
'name' => $tool_name,
'button' => $tool_name,
'desc' => $tool_description,
'callback' => array( $this, 'generate_caches' ),
);
}
/**
* Attach callbacks and hooks, if the store supports getting uncached items, which is required to generate cache
* and also acts as a proxy to determine if the related order store is using caching
*/
public function init() {
if ( $this->is_data_store_cached() ) {
parent::init();
$this->cache_updater->init();
}
}
/**
* Generate the data store's cache by calling the @see $this->>cache_updater's update method.
*/
public function generate_caches() {
$this->cache_updater->run_update();
}
}

View File

@@ -0,0 +1,114 @@
<?php
/**
* Methods for adding Subscriptions Debug Tools
*
* Add tools for debugging and managing Subscriptions to the
* WooCommerce > System Status > Tools administration screen.
*
* @author Prospress
* @category Admin
* @package WooCommerce Subscriptions/Admin
* @version 2.3
* @since 2.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
} // Exit if accessed directly
/**
* WCS_Debug_Tool_Factory Class
*
* Add debug tools to the WooCommerce > System Status > Tools page.
*/
final class WCS_Debug_Tool_Factory {
/**
* Add a debug tool for manually managing a data store's cache.
*
* @param string $tool_type A known type of cache tool. Known types are 'eraser' or 'generator'.
* @param string $tool_name The section name given to the tool on the admin screen.
* @param string $tool_desc The long description for the tool on the admin screen.
* @param WCS_Cache_Updater $data_store
*/
public static function add_cache_tool( $tool_type, $tool_name, $tool_desc, WCS_Cache_Updater $data_store ) {
if ( ! is_admin() && ! defined( 'DOING_CRON' ) && ! defined( 'WP_CLI' ) ) {
return;
}
self::load_cache_tool_file( $tool_type );
$tool_class_name = self::get_cache_tool_class_name( $tool_type );
$tool_key = self::get_tool_key( $tool_name );
if ( 'generator' === $tool_type ) {
$cache_updater = new WCS_Debug_Tool_Cache_Background_Updater( $tool_key, $data_store );
$tool = new $tool_class_name( $tool_key, $tool_name, $tool_desc, $data_store, $cache_updater );
} else {
$tool = new $tool_class_name( $tool_key, $tool_name, $tool_desc, $data_store );
}
$tool->init();
}
/**
* Get the string used to identify the tool.
*
* @param string The name of the cache tool being created
* @return string The key used to identify the tool - sanitized name with wcs_ prefix.
*/
protected static function get_tool_key( $tool_name ) {
return sprintf( 'wcs_%s', str_replace( ' ', '_', strtolower( $tool_name ) ) );
}
/**
* Get a cache tool's class name by passing in the cache name and type.
*
* For example, get_cache_tool_class_name( 'related-order', 'generator' ) will return WCS_Debug_Tool_Related_Order_Cache_Generator.
*
* To make sure the class's file is loaded, call @see self::load_cache_tool_class() first.
*
* @param array $cache_tool_type The type of cache tool. Known tools are 'eraser' and 'generator'.
* @return string The cache tool's class name.
*/
protected static function get_cache_tool_class_name( $cache_tool_type ) {
$tool_class_name = sprintf( 'WCS_Debug_Tool_Cache_%s', ucfirst( $cache_tool_type ) );
if ( ! class_exists( $tool_class_name ) ) {
throw new InvalidArgumentException( sprintf( '%s() requires a path to load %s. Class does not exist after loading %s.', __METHOD__, $class_name, $file_path ) );
}
return $tool_class_name;
}
/**
* Load a cache tool file in the default file path.
*
* For example, load_cache_tool( 'related-order', 'generator' ) will load the file includes/admin/debug-tools/class-wcs-debug-tool-related-order-cache-generator.php
*
* @param array $cache_tool_type The type of cache tool. Known tools are 'eraser' and 'generator'.
*/
protected static function load_cache_tool_file( $cache_tool_type ) {
$file_path = sprintf( 'includes/admin/debug-tools/class-wcs-debug-tool-cache-%s.php', $cache_tool_type );
$file_path = plugin_dir_path( WC_Subscriptions::$plugin_file ) . $file_path;
if ( ! file_exists( $file_path ) ) {
throw new InvalidArgumentException( sprintf( '%s() requires a cache name linked to a valid debug tool. File does not exist: %s', __METHOD__, $rel_file_path ) );
}
self::load_required_classes( $cache_tool_type );
require_once( $file_path );
}
/**
* Load classes that debug tools extend.
*
* @param array $cache_tool_type The type of cache tool. Known tools are 'eraser' and 'generator'.
*/
protected static function load_required_classes( $cache_tool_type ) {
require_once( plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'includes/abstracts/abstract-wcs-debug-tool-cache-updater.php' );
if ( 'generator' === $cache_tool_type ) {
require_once( plugin_dir_path( WC_Subscriptions::$plugin_file ) . 'includes/admin/debug-tools/class-wcs-debug-tool-cache-background-updater.php' );
}
}
}

View File

@@ -71,18 +71,13 @@ class WCS_Meta_Box_Related_Orders {
$initial_subscriptions = wcs_get_subscriptions_for_resubscribe_order( $this_subscription ); $initial_subscriptions = wcs_get_subscriptions_for_resubscribe_order( $this_subscription );
$resubscribed_subscriptions = get_posts( array( $resubscribe_order_ids = WCS_Related_Order_Store::instance()->get_related_order_ids( $this_subscription, 'resubscribe' );
'meta_key' => '_subscription_resubscribe',
'meta_value' => $post->ID,
'post_type' => 'shop_subscription',
'post_status' => 'any',
'posts_per_page' => -1,
) );
foreach ( $resubscribed_subscriptions as $subscription ) { foreach ( $resubscribe_order_ids as $order_id ) {
$subscription = wcs_get_subscription( $subscription ); $order = wc_get_order( $order_id );
wcs_set_objects_property( $subscription, 'relationship', _x( 'Resubscribed Subscription', 'relation to order', 'woocommerce-subscriptions' ), 'set_prop_only' ); $relation = wcs_is_subscription( $order ) ? _x( 'Resubscribed Subscription', 'relation to order', 'woocommerce-subscriptions' ) : _x( 'Resubscribe Order', 'relation to order', 'woocommerce-subscriptions' );
$orders[] = $subscription; wcs_set_objects_property( $order, 'relationship', $relation, 'set_prop_only' );
$orders[] = $order;
} }
} else if ( wcs_order_contains_subscription( $post->ID, array( 'resubscribe' ) ) ) { } else if ( wcs_order_contains_subscription( $post->ID, array( 'resubscribe' ) ) ) {
$initial_subscriptions = wcs_get_subscriptions_for_order( $post->ID, array( 'order_type' => array( 'resubscribe' ) ) ); $initial_subscriptions = wcs_get_subscriptions_for_order( $post->ID, array( 'order_type' => array( 'resubscribe' ) ) );

View File

@@ -97,8 +97,30 @@ class WCS_Meta_Box_Subscription_Data extends WC_Meta_Box_Order_Data {
?> ?>
</select> </select>
</p> </p>
<?php
<?php do_action( 'woocommerce_admin_order_data_after_order_details', $subscription ); ?> $parent_order = $subscription->get_parent();
if ( $parent_order ) { ?>
<p class="form-field form-field-wide">
<?php echo esc_html__( 'Parent order: ', 'woocommerce-subscriptions' ) ?>
<a href="<?php echo esc_url( get_edit_post_link( $subscription->get_parent_id() ) ); ?>">
<?php echo sprintf( esc_html__( '#%1$s', 'woocommerce-subscriptions' ), esc_html( $parent_order->get_order_number() ) ); ?>
</a>
</p>
<?php } else {
?>
<p class="form-field form-field-wide">
<label for="parent-order-id"><?php esc_html_e( 'Parent order:', 'woocommerce-subscriptions' ); ?> </label>
<?php
WCS_Select2::render( array(
'class' => 'wc-enhanced-select',
'name' => 'parent-order-id',
'id' => 'parent-order-id',
'placeholder' => esc_attr__( 'Select an order&hellip;', 'woocommerce-subscriptions' ),
) );
?>
</p>
<?php }
do_action( 'woocommerce_admin_order_data_after_order_details', $subscription ); ?>
</div> </div>
<div class="order_data_column"> <div class="order_data_column">
@@ -302,6 +324,19 @@ class WCS_Meta_Box_Subscription_Data extends WC_Meta_Box_Order_Data {
wcs_set_objects_property( $subscription, $field['id'], wc_clean( $_POST[ $field['id'] ] ) ); wcs_set_objects_property( $subscription, $field['id'], wc_clean( $_POST[ $field['id'] ] ) );
} }
// Save the linked parent order id
if ( ! empty( $_POST['parent-order-id'] ) ) {
// if the parent order to be set is a renewal order
if ( wcs_order_contains_renewal( $_POST['parent-order-id'] ) ) {
// remove renewal meta
$parent = wc_get_order( $_POST['parent-order-id'] );
wcs_delete_objects_property( $parent, 'subscription_renewal' );
}
$subscription->set_parent_id( wc_clean( $_POST['parent-order-id'] ) );
$subscription->add_order_note( sprintf( _x( 'Subscription linked to parent order %s via admin.', 'subscription note after linking to a parent order', 'woocommerce-subscriptions' ), sprintf( '<a href="%1$s">#%2$s</a> ', esc_url( wcs_get_edit_post_link( $subscription->get_parent_id() ) ), $subscription->get_parent()->get_order_number() ) ), false, true );
$subscription->save();
}
try { try {
WCS_Change_Payment_Method_Admin::save_meta( $subscription ); WCS_Change_Payment_Method_Admin::save_meta( $subscription );

View File

@@ -19,7 +19,7 @@ if ( ! defined( 'ABSPATH' ) ) {
echo woocommerce_wp_select( array( echo woocommerce_wp_select( array(
'id' => '_billing_interval', 'id' => '_billing_interval',
'class' => 'billing_interval', 'class' => 'billing_interval',
'label' => __( 'Recurring:', 'woocommerce-subscriptions' ), 'label' => __( 'Payment:', 'woocommerce-subscriptions' ),
'value' => $the_subscription->get_billing_interval(), 'value' => $the_subscription->get_billing_interval(),
'options' => wcs_get_subscription_period_interval_strings(), 'options' => wcs_get_subscription_period_interval_strings(),
) )
@@ -42,7 +42,7 @@ if ( ! defined( 'ABSPATH' ) ) {
<?php printf( '%s %s', esc_html( wcs_get_subscription_period_interval_strings( $the_subscription->get_billing_interval() ) ), esc_html( wcs_get_subscription_period_strings( 1, $the_subscription->get_billing_period() ) ) ); ?> <?php printf( '%s %s', esc_html( wcs_get_subscription_period_interval_strings( $the_subscription->get_billing_interval() ) ), esc_html( wcs_get_subscription_period_strings( 1, $the_subscription->get_billing_period() ) ) ); ?>
<?php endif; ?> <?php endif; ?>
</div> </div>
<?php do_action( 'wcs_subscription_schedule_after_billing_schedule', $the_subscription ); ?>
<?php foreach ( wcs_get_subscription_date_types() as $date_key => $date_label ) : ?> <?php foreach ( wcs_get_subscription_date_types() as $date_key => $date_label ) : ?>
<?php $internal_date_key = wcs_normalise_date_type_key( $date_key ) ?> <?php $internal_date_key = wcs_normalise_date_type_key( $date_key ) ?>
<?php if ( false === wcs_display_date_type( $date_key, $the_subscription ) ) : ?> <?php if ( false === wcs_display_date_type( $date_key, $the_subscription ) ) : ?>

View File

@@ -337,11 +337,13 @@ class WCS_Report_Cache_Manager {
$new_data = array( $new_data = array(
'wcs_report_cache_enabled' => array( 'wcs_report_cache_enabled' => array(
'name' => _x( 'Report Cache Enabled', 'Whether the Report Cache has been enabled', 'woocommerce-subscriptions' ), 'name' => _x( 'Report Cache Enabled', 'Whether the Report Cache has been enabled', 'woocommerce-subscriptions' ),
'label' => 'Report Cache Enabled',
'note' => $cache_enabled ? __( 'Yes', 'woocommerce-subscriptions' ) : __( 'No', 'woocommerce-subscriptions' ), 'note' => $cache_enabled ? __( 'Yes', 'woocommerce-subscriptions' ) : __( 'No', 'woocommerce-subscriptions' ),
'success' => $cache_enabled, 'success' => $cache_enabled,
), ),
'wcs_cache_update_failures' => array( 'wcs_cache_update_failures' => array(
'name' => __( 'Cache Update Failures', 'woocommerce-subscriptions' ), 'name' => __( 'Cache Update Failures', 'woocommerce-subscriptions' ),
'label' => 'Cache Update Failures',
/* translators: %d refers to the number of times we have detected cache update failures */ /* translators: %d refers to the number of times we have detected cache update failures */
'note' => sprintf( _n( '%d failures', '%d failure', $failures, 'woocommerce-subscriptions' ), $failures ), 'note' => sprintf( _n( '%d failures', '%d failure', $failures, 'woocommerce-subscriptions' ), $failures ),
'success' => 0 === $failures, 'success' => 0 === $failures,

View File

@@ -55,7 +55,12 @@ class WC_Report_Subscription_By_Product extends WP_List_Table {
switch ( $column_name ) { switch ( $column_name ) {
case 'product_name' : case 'product_name' :
return edit_post_link( $report_item->product_name, null, null, $report_item->product_id ); // If the product is a subscription variation, use the parent product's edit post link
if ( $report_item->parent_product_id > 0 ) {
return edit_post_link( $report_item->product_name, ' - ', null, $report_item->parent_product_id );
} else {
return edit_post_link( $report_item->product_name, null, null, $report_item->product_id );
}
case 'subscription_count' : case 'subscription_count' :
return sprintf( '<a href="%s%d">%d</a>', admin_url( 'edit.php?post_type=shop_subscription&_wcs_product=' ), $report_item->product_id, $report_item->subscription_count ); return sprintf( '<a href="%s%d">%d</a>', admin_url( 'edit.php?post_type=shop_subscription&_wcs_product=' ), $report_item->product_id, $report_item->subscription_count );
@@ -114,6 +119,7 @@ class WC_Report_Subscription_By_Product extends WP_List_Table {
$query = apply_filters( 'wcs_reports_product_query', $query = apply_filters( 'wcs_reports_product_query',
"SELECT product.id as product_id, "SELECT product.id as product_id,
product.post_parent as parent_product_id,
product.post_title as product_name, product.post_title as product_name,
mo.product_type, mo.product_type,
COUNT(subscription_line_items.subscription_id) as subscription_count, COUNT(subscription_line_items.subscription_id) as subscription_count,
@@ -136,14 +142,14 @@ class WC_Report_Subscription_By_Product extends WP_List_Table {
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS wcoimeta2 INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS wcoimeta2
ON wcoimeta2.order_item_id = wcoitems.order_item_id ON wcoimeta2.order_item_id = wcoitems.order_item_id
WHERE wcoitems.order_item_type = 'line_item' WHERE wcoitems.order_item_type = 'line_item'
AND wcoimeta.meta_key = '_product_id' AND ( wcoimeta.meta_key = '_product_id' OR wcoimeta.meta_key = '_variation_id' )
AND wcoimeta2.meta_key = '_line_total' AND wcoimeta2.meta_key = '_line_total'
) as subscription_line_items ) as subscription_line_items
ON product.id = subscription_line_items.product_id ON product.id = subscription_line_items.product_id
LEFT JOIN {$wpdb->posts} as subscriptions LEFT JOIN {$wpdb->posts} as subscriptions
ON subscriptions.ID = subscription_line_items.subscription_id ON subscriptions.ID = subscription_line_items.subscription_id
WHERE product.post_status = 'publish' WHERE product.post_status = 'publish'
AND product.post_type = 'product' AND ( product.post_type = 'product' OR product.post_type = 'product_variation' )
AND subscriptions.post_type = 'shop_subscription' AND subscriptions.post_type = 'shop_subscription'
AND subscriptions.post_status NOT IN( 'wc-pending', 'trash' ) AND subscriptions.post_status NOT IN( 'wc-pending', 'trash' )
GROUP BY product.id GROUP BY product.id
@@ -160,6 +166,33 @@ class WC_Report_Subscription_By_Product extends WP_List_Table {
$report_data = $cached_results[ $query_hash ]; $report_data = $cached_results[ $query_hash ];
// Organize subscription variations under the parent product in a tree structure
$tree = array();
foreach ( $report_data as $product_id => $product ) {
if ( ! $product->parent_product_id ) {
if ( isset( $tree[ $product_id ] ) ) {
array_unshift( $tree[ $product_id ], $product_id );
} else {
$tree[ $product_id ][] = $product_id;
}
} else {
$tree[ $product->parent_product_id ][] = $product_id;
}
}
// Create an array with all the report data in the correct order
$ordered_report_data = array();
foreach ( $tree as $parent_id => $children ) {
foreach ( $children as $child_id ) {
$ordered_report_data[ $child_id ] = $report_data[ $child_id ];
// When there are variations, store the variation ids.
if ( 'variable-subscription' === $report_data[ $child_id ]->product_type ) {
$ordered_report_data[ $child_id ]->variations = array_diff( $children, array( $parent_id ) );
}
}
}
// Now let's get the total revenue for each product so we can provide an average lifetime value for that product // Now let's get the total revenue for each product so we can provide an average lifetime value for that product
$query = apply_filters( 'wcs_reports_product_lifetime_value_query', $query = apply_filters( 'wcs_reports_product_lifetime_value_query',
"SELECT wcoimeta.meta_value as product_id, SUM(wcoimeta2.meta_value) as product_total "SELECT wcoimeta.meta_value as product_id, SUM(wcoimeta2.meta_value) as product_total
@@ -172,7 +205,7 @@ class WC_Report_Subscription_By_Product extends WP_List_Table {
ON wcoimeta.order_item_id = wcoitems.order_item_id ON wcoimeta.order_item_id = wcoitems.order_item_id
INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS wcoimeta2 INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS wcoimeta2
ON wcoimeta2.order_item_id = wcoitems.order_item_id ON wcoimeta2.order_item_id = wcoitems.order_item_id
WHERE wcoimeta.meta_key = '_product_id' WHERE ( wcoimeta.meta_key = '_product_id' OR wcoimeta.meta_key = '_variation_id' )
AND wcoimeta2.meta_key = '_line_total' AND wcoimeta2.meta_key = '_line_total'
GROUP BY product_id" ); GROUP BY product_id" );
@@ -185,11 +218,11 @@ class WC_Report_Subscription_By_Product extends WP_List_Table {
} }
// Add the product total to each item // Add the product total to each item
foreach ( array_keys( $report_data ) as $product_id ) { foreach ( array_keys( $ordered_report_data ) as $product_id ) {
$report_data[ $product_id ]->product_total = isset( $cached_results[ $query_hash ][ $product_id ] ) ? $cached_results[ $query_hash ][ $product_id ]->product_total : 0; $ordered_report_data[ $product_id ]->product_total = isset( $cached_results[ $query_hash ][ $product_id ] ) ? $cached_results[ $query_hash ][ $product_id ]->product_total : 0;
} }
return $report_data; return $ordered_report_data;
} }
/** /**
@@ -199,20 +232,77 @@ class WC_Report_Subscription_By_Product extends WP_List_Table {
$chart_colors = array( '#33a02c', '#1f78b4', '#6a3d9a', '#e31a1c', '#ff7f00', '#b15928', '#a6cee3', '#b2df8a', '#fb9a99', '#ffff99', '#fdbf6f', '#cab2d6' ); $chart_colors = array( '#33a02c', '#1f78b4', '#6a3d9a', '#e31a1c', '#ff7f00', '#b15928', '#a6cee3', '#b2df8a', '#fb9a99', '#ffff99', '#fdbf6f', '#cab2d6' );
//We only will display the first 12 plans in the chart // We only will display the first 12 plans of parent products in the chart
$products = array_slice( $this->items, 0, 12 ); $products = array_slice( wp_list_filter( $this->items, array( 'parent_product_id' => 0 ) ), 0, 12 );
// Filter top n variations corresponding to top 12 parent products
$variations = array();
foreach ( $products as $product ) {
if ( ! empty( $product->variations ) ) { // Variable subscription
foreach ( $product->variations as $variation_id ) {
$variations[] = $this->items[ $variation_id ];
}
} else { // Simple subscription
$variations[] = $product;
}
}
?> ?>
<div class="chart-container" style="float: left; padding-top: 50px; min-width: 0px;"> <div class="chart-container" style="float: left; padding-top: 50px; min-width: 0px;">
<div class="data-container" style="display: inline-block; margin-left: 30px; border: 1px solid #e5e5e5; background-color: #FFF; padding: 20px;"> <div class="data-container" style="display: inline-block; margin-left: 30px; border: 1px solid #e5e5e5; background-color: #FFF; padding: 20px;">
<div class="chart-placeholder product_breakdown_chart pie-chart" style="height:200px; width: 200px; float: left;"></div> <div class="chart-placeholder product_breakdown_chart pie-chart" style="height: 200px; width: 200px; float: left;"></div>
<div class="chart-placeholder variation_breakdown_chart pie-chart" style="height: 200px; width: 200px;"></div>
<div class="legend-container" style="margin-left: 10px; float: left;"></div> <div class="legend-container" style="margin-left: 10px; float: left;"></div>
<div style="clear:both;"></div> <div style="clear: both;"></div>
</div> </div>
</div> </div>
<script type="text/javascript"> <script type="text/javascript">
jQuery(function(){ jQuery(function(){
jQuery.plot( jQuery.plot(
jQuery('.chart-placeholder.variation_breakdown_chart'),
[
<?php
$colorindex = -1;
$last_parent_id = -1;
foreach ( $variations as $product ) {
if ( '0' === $product->parent_product_id || $last_parent_id !== $product->parent_product_id ) {
$colorindex++;
$last_parent_id = $product->parent_product_id;
}
?>
{
label: '<?php echo esc_js( $product->product_name ); ?>',
data: '<?php echo esc_js( $product->subscription_count ); ?>',
color: '<?php echo esc_js( $chart_colors[ $colorindex ] ); ?>',
},
<?php
}
?>
],
{
grid: {
hoverable: true
},
series: {
pie: {
show: true,
radius: 1,
innerRadius: 0.7,
label: {
show: false
}
},
prepend_label: true,
enable_tooltip: true,
append_tooltip: "<?php echo ' ' . esc_js( __( 'subscriptions', 'woocommerce-subscriptions' ) ); ?>",
},
legend: {
show: false,
}
}
);
jQuery('.chart-placeholder.variation_breakdown_chart').resize();
jQuery.plot(
jQuery('.chart-placeholder.product_breakdown_chart'), jQuery('.chart-placeholder.product_breakdown_chart'),
[ [
<?php <?php
@@ -236,22 +326,23 @@ class WC_Report_Subscription_By_Product extends WP_List_Table {
series: { series: {
pie: { pie: {
show: true, show: true,
radius: 1, radius: 0.7,
innerRadius: 0.6, innerRadius: 0.3,
label: { label: {
show: false show: false
} }
}, },
prepend_label: true,
enable_tooltip: true, enable_tooltip: true,
append_tooltip: "<?php echo ' ' . esc_js( __( 'subscriptions', 'woocommerce-subscriptions' ) ); ?>", append_tooltip: "<?php echo ' ' . esc_js( __( 'subscriptions', 'woocommerce-subscriptions' ) ); ?>",
}, },
legend: { legend: {
show: true, show: true,
position: "ne",
container: jQuery('.legend-container'), container: jQuery('.legend-container'),
} }
} }
); );
jQuery('.chart-placeholder.product_breakdown_chart').resize(); jQuery('.chart-placeholder.product_breakdown_chart').resize();
}); });
</script> </script>

View File

@@ -66,6 +66,13 @@ class WC_Report_Subscription_Events_By_Date extends WC_Admin_Report {
'name' => 'post_date', 'name' => 'post_date',
), ),
), ),
'where' => array(
'post_status' => array(
'key' => 'post_status',
'operator' => 'NOT IN',
'value' => array( 'trash', 'auto-draft' ),
),
),
'group_by' => $this->group_by_query, 'group_by' => $this->group_by_query,
'order_status' => '', 'order_status' => '',
'order_by' => 'post_date ASC', 'order_by' => 'post_date ASC',
@@ -102,6 +109,13 @@ class WC_Report_Subscription_Events_By_Date extends WC_Admin_Report {
'join_type' => 'LEFT', // To avoid issues if there is no renewal_total meta 'join_type' => 'LEFT', // To avoid issues if there is no renewal_total meta
), ),
), ),
'where' => array(
'post_status' => array(
'key' => 'post_status',
'operator' => 'NOT IN',
'value' => array( 'trash', 'auto-draft' ),
),
),
'group_by' => $this->group_by_query, 'group_by' => $this->group_by_query,
'order_status' => $args['order_status'], 'order_status' => $args['order_status'],
'order_by' => 'post_date ASC', 'order_by' => 'post_date ASC',
@@ -138,6 +152,13 @@ class WC_Report_Subscription_Events_By_Date extends WC_Admin_Report {
'join_type' => 'LEFT', // To avoid issues if there is no resubscribe_total meta 'join_type' => 'LEFT', // To avoid issues if there is no resubscribe_total meta
), ),
), ),
'where' => array(
'post_status' => array(
'key' => 'post_status',
'operator' => 'NOT IN',
'value' => array( 'trash', 'auto-draft' ),
),
),
'group_by' => $this->group_by_query, 'group_by' => $this->group_by_query,
'order_status' => $args['order_status'], 'order_status' => $args['order_status'],
'order_by' => 'post_date ASC', 'order_by' => 'post_date ASC',
@@ -168,6 +189,13 @@ class WC_Report_Subscription_Events_By_Date extends WC_Admin_Report {
'name' => 'switch_orders', 'name' => 'switch_orders',
), ),
), ),
'where' => array(
'post_status' => array(
'key' => 'post_status',
'operator' => 'NOT IN',
'value' => array( 'trash', 'auto-draft' ),
),
),
'group_by' => $this->group_by_query, 'group_by' => $this->group_by_query,
'order_status' => $args['order_status'], 'order_status' => $args['order_status'],
'order_by' => 'post_date ASC', 'order_by' => 'post_date ASC',
@@ -195,6 +223,7 @@ class WC_Report_Subscription_Events_By_Date extends WC_Admin_Report {
WHERE subscription_posts.post_type = 'shop_subscription' WHERE subscription_posts.post_type = 'shop_subscription'
AND subscription_posts.post_date >= %s AND subscription_posts.post_date >= %s
AND subscription_posts.post_date < %s AND subscription_posts.post_date < %s
AND subscription_posts.post_status NOT IN ( 'trash', 'auto-draft' )
GROUP BY order_id GROUP BY order_id
) AS subscriptions ON subscriptions.order_id = order_posts.ID ) AS subscriptions ON subscriptions.order_id = order_posts.ID
LEFT JOIN {$wpdb->postmeta} AS order_total_post_meta LEFT JOIN {$wpdb->postmeta} AS order_total_post_meta
@@ -295,6 +324,7 @@ class WC_Report_Subscription_Events_By_Date extends WC_Admin_Report {
JOIN {$wpdb->postmeta} AS wcsmeta_cancel JOIN {$wpdb->postmeta} AS wcsmeta_cancel
ON wcsubs.ID = wcsmeta_cancel.post_id ON wcsubs.ID = wcsmeta_cancel.post_id
AND wcsmeta_cancel.meta_key = %s AND wcsmeta_cancel.meta_key = %s
AND wcsubs.post_status NOT IN ( 'trash', 'auto-draft' )
GROUP BY YEAR( cancel_date ), MONTH( cancel_date ), DAY( cancel_date ) GROUP BY YEAR( cancel_date ), MONTH( cancel_date ), DAY( cancel_date )
HAVING cancel_date BETWEEN %s AND %s HAVING cancel_date BETWEEN %s AND %s
ORDER BY wcsmeta_cancel.meta_value ASC", ORDER BY wcsmeta_cancel.meta_value ASC",
@@ -322,6 +352,7 @@ class WC_Report_Subscription_Events_By_Date extends WC_Admin_Report {
JOIN {$wpdb->postmeta} AS wcsmeta_end JOIN {$wpdb->postmeta} AS wcsmeta_end
ON wcsubs.ID = wcsmeta_end.post_id ON wcsubs.ID = wcsmeta_end.post_id
AND wcsmeta_end.meta_key = %s AND wcsmeta_end.meta_key = %s
AND wcsubs.post_status NOT IN ( 'trash', 'auto-draft' )
GROUP BY YEAR( end_date ), MONTH( end_date ), DAY( end_date ) GROUP BY YEAR( end_date ), MONTH( end_date ), DAY( end_date )
HAVING end_date BETWEEN %s AND %s HAVING end_date BETWEEN %s AND %s
ORDER BY wcsmeta_end.meta_value ASC", ORDER BY wcsmeta_end.meta_value ASC",

View File

@@ -16,8 +16,18 @@ if ( ! defined( 'ABSPATH' ) ) {
class WC_Product_Variable_Subscription extends WC_Product_Variable { class WC_Product_Variable_Subscription extends WC_Product_Variable {
private $min_max_variation_data = array(); /**
* A cache of the variable product's min and max data generated by @see wcs_get_min_max_variation_data().
*
* @var array
*/
protected $min_max_variation_data = array();
/**
* A cache of the variable product's sorted variation prices.
*
* @var array
*/
private $sorted_variation_prices = array(); private $sorted_variation_prices = array();
/** /**
@@ -141,15 +151,10 @@ class WC_Product_Variable_Subscription extends WC_Product_Variable {
if ( empty( $this->sorted_variation_prices[ $prices_hash ] ) ) { if ( empty( $this->sorted_variation_prices[ $prices_hash ] ) ) {
$child_variation_ids = array_keys( $prices ); $min_max_variation_data = $this->get_min_and_max_variation_data( array_keys( $prices ) );
$variation_hash = md5( json_encode( $child_variation_ids ) );
if ( empty( $this->min_max_variation_data[ $variation_hash ] ) ) { $min_variation_id = $min_max_variation_data['min']['variation_id'];
$this->min_max_variation_data[ $variation_hash ] = wcs_get_min_max_variation_data( $this, $child_variation_ids ); $max_variation_id = $min_max_variation_data['max']['variation_id'];
}
$min_variation_id = $this->min_max_variation_data[ $variation_hash ]['min']['variation_id'];
$max_variation_id = $this->min_max_variation_data[ $variation_hash ]['max']['variation_id'];
// Reorder the variable price arrays to reflect the min and max values so that WooCommerce will find them in the correct order // Reorder the variable price arrays to reflect the min and max values so that WooCommerce will find them in the correct order
$min_price = $prices[ $min_variation_id ]; $min_price = $prices[ $min_variation_id ];
@@ -168,6 +173,66 @@ class WC_Product_Variable_Subscription extends WC_Product_Variable {
return $this->sorted_variation_prices[ $prices_hash ]; return $this->sorted_variation_prices[ $prices_hash ];
} }
/**
* Set the product's min and max variation data.
*
* @param array $min_and_max_data The min and max variation data returned by @see wcs_get_min_max_variation_data(). Optional.
* @param array $variation_ids The child variation IDs. Optional. By default this value be generated by @see WC_Product_Variable->get_visible_children().
* @since 2.3.0
*/
public function set_min_and_max_variation_data( $min_and_max_data = array(), $variation_ids = array() ) {
if ( empty( $variation_ids ) ) {
$variation_ids = $this->get_visible_children();
}
if ( empty( $min_and_max_data ) ) {
$min_and_max_data = wcs_get_min_max_variation_data( $this, $variation_ids );
}
$this->add_meta_data( '_min_max_variation_data', $min_and_max_data, true );
$this->add_meta_data( '_min_max_variation_ids_hash', $this->get_variation_ids_hash( $variation_ids ), true );
}
/**
* Get the min and max variation data.
*
* This is a wrapper for @see wcs_get_min_max_variation_data() but to avoid calling
* that resource intensive function multiple times per request, check the value
* stored in meta or cached in memory before calling that function.
*
* @param array $variation_ids An array of variation IDs.
* @return array The variable product's min and max variation data.
* @since 2.3.0
*/
public function get_min_and_max_variation_data( $variation_ids ) {
$variation_ids_hash = $this->get_variation_ids_hash( $variation_ids );
if ( $variation_ids_hash === $this->get_meta( '_min_max_variation_ids_hash', true ) ) {
$min_and_max_variation_data = $this->get_meta( '_min_max_variation_data', true );
} elseif ( ! empty( $this->min_max_variation_data[ $variation_ids_hash ] ) ) {
$min_and_max_variation_data = $this->min_max_variation_data[ $variation_ids_hash ];
} else {
$min_and_max_variation_data = wcs_get_min_max_variation_data( $this, $variation_ids );
$this->min_max_variation_data[ $variation_ids_hash ] = $min_and_max_variation_data;
}
return $min_and_max_variation_data;
}
/**
* Generate a unique hash from an array of variation IDs.
*
* @param array $variation_ids
* @return string
*/
protected static function get_variation_ids_hash( $variation_ids ) {
// Sort the variation IDs so the hash isn't different for the same array of IDs
sort( $variation_ids );
return md5( json_encode( $variation_ids ) );
}
/* Deprecated Functions */ /* Deprecated Functions */
/** /**
@@ -235,15 +300,11 @@ class WC_Product_Variable_Subscription extends WC_Product_Variable {
*/ */
protected function get_price_prefix( $prices ) { protected function get_price_prefix( $prices ) {
$child_variation_ids = array_keys( $prices['price'] );
$min_max_variation_data = $this->get_min_and_max_variation_data( $child_variation_ids );
// Are the subscription details of all variations identical? // Are the subscription details of all variations identical?
$child_variation_ids = array_keys( $prices['price'] ); if ( $min_max_variation_data['identical'] ) {
$variation_hash = md5( json_encode( $child_variation_ids ) );
if ( empty( $this->min_max_variation_data[ $variation_hash ] ) ) {
$this->min_max_variation_data[ $variation_hash ] = wcs_get_min_max_variation_data( $this, $child_variation_ids );
}
if ( $this->min_max_variation_data[ $variation_hash ]['identical'] ) {
$prefix = ''; $prefix = '';
} else { } else {
$prefix = wcs_get_price_html_from_text( $this ); $prefix = wcs_get_price_html_from_text( $this );

View File

@@ -94,7 +94,7 @@ class WC_Subscription extends WC_Order {
/** /**
* Initialize the subscription object. * Initialize the subscription object.
* *
* @param int|WC_Subscription $order * @param int|WC_Subscription $subscription
*/ */
public function __construct( $subscription ) { public function __construct( $subscription ) {
@@ -257,30 +257,10 @@ class WC_Subscription extends WC_Order {
// And finally, check that the latest order (switch or renewal) doesn't need payment // And finally, check that the latest order (switch or renewal) doesn't need payment
} else { } else {
$last_order_id = get_posts( array( $order = $this->get_last_order( 'all', array( 'renewal', 'switch' ) );
'posts_per_page' => 1,
'post_type' => 'shop_order',
'post_status' => 'any',
'fields' => 'ids',
'orderby' => 'ID',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => '_subscription_renewal',
'compare' => '=',
'value' => $this->get_id(),
'type' => 'numeric',
),
),
) );
if ( ! empty( $last_order_id ) ) { if ( $order && ( $order->needs_payment() || $order->has_status( array( 'on-hold', 'failed', 'cancelled' ) ) ) ) {
$needs_payment = true;
$order = wc_get_order( $last_order_id[0] );
if ( $order->needs_payment() || $order->has_status( array( 'on-hold', 'failed', 'cancelled' ) ) ) {
$needs_payment = true;
}
} }
} }
@@ -654,49 +634,21 @@ class WC_Subscription extends WC_Order {
$completed_payment_count = ( ( $parent_order = $this->get_parent() ) && ( null !== wcs_get_objects_property( $parent_order, 'date_paid' ) || $parent_order->has_status( $this->get_paid_order_statuses() ) ) ) ? 1 : 0; $completed_payment_count = ( ( $parent_order = $this->get_parent() ) && ( null !== wcs_get_objects_property( $parent_order, 'date_paid' ) || $parent_order->has_status( $this->get_paid_order_statuses() ) ) ) ? 1 : 0;
// Get all renewal orders - for large sites its more efficient to find the two different sets of renewal orders below using post__in than complicated meta queries $paid_renewal_orders = array();
$renewal_orders = get_posts( array( $renewal_order_ids = $this->get_related_order_ids( 'renewal' );
'posts_per_page' => -1,
'post_status' => 'any',
'post_type' => 'shop_order',
'fields' => 'ids',
'orderby' => 'date',
'order' => 'desc',
'meta_key' => '_subscription_renewal',
'meta_compare' => '=',
'meta_type' => 'numeric',
'meta_value' => $this->get_id(),
'update_post_term_cache' => false,
) );
if ( ! empty( $renewal_orders ) ) { if ( ! empty( $renewal_order_ids ) ) {
// Not all gateways will call $order->payment_complete() so we need to find renewal orders with a paid status rather than just a _paid_date // Looping over the known orders is faster than database queries on large sites
$paid_status_renewal_orders = get_posts( array( foreach ( $renewal_order_ids as $renewal_order_id ) {
'posts_per_page' => -1,
'post_status' => $this->get_paid_order_statuses(),
'post_type' => 'shop_order',
'fields' => 'ids',
'orderby' => 'date',
'order' => 'desc',
'post__in' => $renewal_orders,
) );
// Some stores may be using custom order status plugins, we also can't rely on order status to find paid orders, so also check for a _paid_date $renewal_order = wc_get_order( $renewal_order_id );
$paid_date_renewal_orders = get_posts( array(
'posts_per_page' => -1,
'post_status' => 'any',
'post_type' => 'shop_order',
'fields' => 'ids',
'orderby' => 'date',
'order' => 'desc',
'post__in' => $renewal_orders,
'meta_key' => '_paid_date',
'meta_compare' => 'EXISTS',
'update_post_term_cache' => false,
) );
$paid_renewal_orders = array_unique( array_merge( $paid_date_renewal_orders, $paid_status_renewal_orders ) ); // Not all gateways call $order->payment_complete(), so with WC < 3.0 we need to find renewal orders with a paid date or a paid status. WC 3.0+ takes care of setting the paid date when payment_complete() wasn't called, so isn't needed with WC 3.0 or newer.
if ( $renewal_order && ( null !== wcs_get_objects_property( $renewal_order, 'date_paid' ) || $renewal_order->has_status( $this->get_paid_order_statuses() ) ) ) {
$paid_renewal_orders[] = $renewal_order_id;
}
}
if ( ! empty( $paid_renewal_orders ) ) { if ( ! empty( $paid_renewal_orders ) ) {
$completed_payment_count += count( $paid_renewal_orders ); $completed_payment_count += count( $paid_renewal_orders );
@@ -723,25 +675,10 @@ class WC_Subscription extends WC_Order {
$failed_payment_count = ( ( $parent_order = $this->get_parent() ) && $parent_order->has_status( 'failed' ) ) ? 1 : 0; $failed_payment_count = ( ( $parent_order = $this->get_parent() ) && $parent_order->has_status( 'failed' ) ) ? 1 : 0;
$failed_renewal_orders = get_posts( array( foreach ( $this->get_related_orders( 'all', 'renewal' ) as $renewal_order ) {
'posts_per_page' => -1, if ( $renewal_order->has_status( 'failed' ) ) {
'post_status' => 'wc-failed', $failed_payment_count++;
'post_type' => 'shop_order', }
'fields' => 'ids',
'orderby' => 'date',
'order' => 'desc',
'meta_query' => array(
array(
'key' => '_subscription_renewal',
'compare' => '=',
'value' => $this->get_id(),
'type' => 'numeric',
),
),
) );
if ( ! empty( $failed_renewal_orders ) ) {
$failed_payment_count += count( $failed_renewal_orders );
} }
return apply_filters( 'woocommerce_subscription_payment_failed_count', $failed_payment_count, $this ); return apply_filters( 'woocommerce_subscription_payment_failed_count', $failed_payment_count, $this );
@@ -1079,10 +1016,10 @@ class WC_Subscription extends WC_Order {
* *
* @since 2.2.0 * @since 2.2.0
* @param string $date_type Any valid WC 3.0 date property, including 'date_paid', 'date_completed', 'date_created', or 'date_modified' * @param string $date_type Any valid WC 3.0 date property, including 'date_paid', 'date_completed', 'date_created', or 'date_modified'
* @param string $order_type The type of orders to return, can be 'last', 'parent', 'switch', 'renewal' or 'all'. Default 'all'. Use 'last' to only check the last order. * @param string $order_type The type of orders to return, can be 'last', 'parent', 'switch', 'renewal' or 'any'. Default 'any'. Use 'last' to only check the last order.
* @return WC_DateTime|NULL object if the date is set or null if there is no date. * @return WC_DateTime|NULL object if the date is set or null if there is no date.
*/ */
protected function get_related_orders_date( $date_type, $order_type = 'all' ) { protected function get_related_orders_date( $date_type, $order_type = 'any' ) {
$date = null; $date = null;
@@ -1091,7 +1028,7 @@ class WC_Subscription extends WC_Order {
$date = ( ! $last_order ) ? null : wcs_get_objects_property( $last_order, $date_type ); $date = ( ! $last_order ) ? null : wcs_get_objects_property( $last_order, $date_type );
} else { } else {
// Loop over orders until we find a valid date of this type or run out of related orders // Loop over orders until we find a valid date of this type or run out of related orders
foreach ( $this->get_related_orders( 'ids', $order_type ) as $related_order_id ) { foreach ( $this->get_related_orders( 'all', $order_type ) as $related_order_id ) {
$related_order = wc_get_order( $related_order_id ); $related_order = wc_get_order( $related_order_id );
$date = ( ! $related_order ) ? null : wcs_get_objects_property( $related_order, $date_type ); $date = ( ! $related_order ) ? null : wcs_get_objects_property( $related_order, $date_type );
if ( is_a( $date, 'WC_Datetime' ) ) { if ( is_a( $date, 'WC_Datetime' ) ) {
@@ -1813,69 +1750,77 @@ class WC_Subscription extends WC_Order {
* Extracting the query from get_related_orders and get_last_order so it can be moved in a cached * Extracting the query from get_related_orders and get_last_order so it can be moved in a cached
* value. * value.
* *
* @deprecated 2.3.0 Moved to WCS_Subscription_Data_Store_CPT::get_related_order_ids() to separate cache logic from subscription instances and to avoid confusion from the misnomer on this method's name - it gets renewal orders, not related orders - and its ambiguity - it runs a query and returns order IDs, it does not return a SQL query string or order objects.
* @return array * @return array
*/ */
public function get_related_orders_query( $id ) { public function get_related_orders_query( $subscription_id ) {
$related_post_ids = get_posts( array( wcs_deprecated_function( __METHOD__, '2.3.0', 'WCS_Subscription_Data_Store_CPT::get_related_order_ids( $subscription_id ) via WCS_Subscription_Data_Store::instance()' );
'posts_per_page' => -1, return WCS_Related_Order_Store::instance()->get_related_order_ids( $subscription_id, 'renewal' );
'post_type' => 'shop_order',
'post_status' => 'any',
'fields' => 'ids',
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => '_subscription_renewal',
'compare' => '=',
'value' => $id,
'type' => 'numeric',
),
),
) );
return $related_post_ids;
} }
/** /**
* Get the related orders for a subscription, including renewal orders and the initial order (if any) * Get the related orders for a subscription, including renewal orders and the initial order (if any)
* *
* @param string $return_fields The columns to return, either 'all' or 'ids' * @param string $return_fields The columns to return, either 'all' or 'ids'
* @param string $order_type The type of orders to return, either 'renewal' or 'all'. Default 'all'. * @param array|string $order_types Can include 'any', 'parent', 'renewal', 'resubscribe' and/or 'switch'. Custom types possible via the 'woocommerce_subscription_related_orders' filter. Defaults to array( 'parent', 'renewal' ).
* @since 2.0 * @since 2.0
* @return array
*/ */
public function get_related_orders( $return_fields = 'ids', $order_type = 'all' ) { public function get_related_orders( $return_fields = 'ids', $order_types = array( 'parent', 'renewal' ) ) {
$return_fields = ( 'ids' == $return_fields ) ? $return_fields : 'all'; $return_fields = ( 'ids' == $return_fields ) ? $return_fields : 'all';
if ( 'all' === $order_types ) {
wcs_deprecated_argument( __METHOD__, '2.3.0', sprintf( __( 'The "all" value for $order_type parameter is deprecated. It was a misnomer, as it did not return resubscribe orders. It was also inconsistent with order type values accepted by wcs_get_subscription_orders(). Use array( "parent", "renewal", "switch" ) to maintain previous behaviour, or "any" to receive all order types, including switch and resubscribe.', 'woocommerce-subscriptions' ), __CLASS__ ) );
$order_types = array( 'parent', 'renewal', 'switch' );
} elseif ( ! is_array( $order_types ) ) {
// Accept either an array or string (to make it more convenient for singular types, like 'parent' or 'any')
$order_types = array( $order_types );
}
$related_orders = array(); $related_orders = array();
foreach ( $order_types as $order_type ) {
$related_post_ids = WC_Subscriptions::$cache->cache_and_get( 'wcs-related-orders-to-' . $this->get_id(), array( $this, 'get_related_orders_query' ), array( $this->get_id() ) ); $related_orders_for_order_type = array();
foreach ( $this->get_related_order_ids( $order_type ) as $order_id ) {
if ( 'all' == $return_fields ) { $related_orders_for_order_type[ $order_id ] = ( 'all' == $return_fields ) ? wc_get_order( $order_id ) : $order_id;
foreach ( $related_post_ids as $post_id ) {
$related_orders[ $post_id ] = wc_get_order( $post_id );
} }
if ( false != $this->get_parent_id() && 'renewal' !== $order_type ) { $related_orders += apply_filters( 'woocommerce_subscription_related_orders', $related_orders_for_order_type, $this, $return_fields, $order_type );
$related_orders[ $this->get_parent_id() ] = $this->get_parent(); }
}
} else {
// Return IDs only arsort( $related_orders );
if ( false != $this->get_parent_id() && 'renewal' !== $order_type ) {
$related_orders[ $this->get_parent_id() ] = $this->get_parent_id();
}
foreach ( $related_post_ids as $post_id ) { return $related_orders;
$related_orders[ $post_id ] = $post_id; }
/**
* Get the related order IDs for a subscription based on an order type.
*
* @param string $order_type Can include 'any', 'parent', 'renewal', 'resubscribe' and/or 'switch'. Defaults to 'any'.
* @return array List of related order IDs.
* @since 2.3.0
*/
protected function get_related_order_ids( $order_type = 'any' ) {
$related_order_ids = array();
if ( in_array( $order_type, array( 'any', 'parent' ) ) && $this->get_parent_id() ) {
$related_order_ids[ $this->get_parent_id() ] = $this->get_parent_id();
}
if ( 'parent' !== $order_type ) {
$relation_types = ( 'any' === $order_type ) ? array( 'renewal', 'resubscribe', 'switch' ) : array( $order_type );
foreach ( $relation_types as $relation_type ) {
$related_order_ids = array_merge( $related_order_ids, WCS_Related_Order_Store::instance()->get_related_order_ids( $this, $relation_type ) );
} }
} }
return apply_filters( 'woocommerce_subscription_related_orders', $related_orders, $this, $return_fields, $order_type ); return $related_order_ids;
} }
/** /**
* Gets the most recent order that relates to a subscription, including renewal orders and the initial order (if any). * Gets the most recent order that relates to a subscription, including renewal orders and the initial order (if any).
* *
@@ -1896,13 +1841,8 @@ class WC_Subscription extends WC_Order {
$related_orders[] = $this->get_parent_id(); $related_orders[] = $this->get_parent_id();
} }
break; break;
case 'renewal':
$related_orders = array_merge( $related_orders, WC_Subscriptions::$cache->cache_and_get( 'wcs-related-orders-to-' . $this->get_id(), array( $this, 'get_related_orders_query' ), array( $this->get_id() ) ) );
break;
case 'switch':
$related_orders = array_merge( $related_orders, array_keys( wcs_get_switch_orders_for_subscription( $this->get_id() ) ) );
break;
default: default:
$related_orders = array_merge( $related_orders, $this->get_related_order_ids( $order_type ) );
break; break;
} }
} }
@@ -2094,8 +2034,7 @@ class WC_Subscription extends WC_Order {
/** /**
* The total sign-up fee for the subscription if any. * The total sign-up fee for the subscription if any.
* *
* @param array|int Either an order item (in the array format returned by self::get_items()) or the ID of an order item. * @return int
* @return bool
* @since 2.0 * @since 2.0
*/ */
public function get_sign_up_fee() { public function get_sign_up_fee() {
@@ -2157,6 +2096,8 @@ class WC_Subscription extends WC_Order {
} elseif ( 'true' === $line_item->get_meta( '_has_trial' ) ) { } elseif ( 'true' === $line_item->get_meta( '_has_trial' ) ) {
// Sign up is amount paid for this item on original order, we can safely use 3.0 getters here because we know from the above condition 3.0 is active // Sign up is amount paid for this item on original order, we can safely use 3.0 getters here because we know from the above condition 3.0 is active
$sign_up_fee = ( (float) $original_order_item->get_total( 'edit' ) ) / $original_order_item->get_quantity( 'edit' ); $sign_up_fee = ( (float) $original_order_item->get_total( 'edit' ) ) / $original_order_item->get_quantity( 'edit' );
} elseif ( $original_order_item->meta_exists( '_synced_sign_up_fee' ) ) {
$sign_up_fee = ( (float) $original_order_item->get_meta( '_synced_sign_up_fee' ) ) / $original_order_item->get_quantity( 'edit' );
} else { } else {
// Sign-up fee is any amount on top of recurring amount // Sign-up fee is any amount on top of recurring amount
$order_line_total = ( (float) $original_order_item->get_total( 'edit' ) ) / $original_order_item->get_quantity( 'edit' ); $order_line_total = ( (float) $original_order_item->get_total( 'edit' ) ) / $original_order_item->get_quantity( 'edit' );
@@ -2165,10 +2106,17 @@ class WC_Subscription extends WC_Order {
$sign_up_fee = max( $order_line_total - $subscription_line_total, 0 ); $sign_up_fee = max( $order_line_total - $subscription_line_total, 0 );
} }
// If prices inc tax, ensure that the sign up fee amount includes the tax if ( ! empty( $original_order_item ) && ! empty( $sign_up_fee ) ) {
if ( 'inclusive_of_tax' === $tax_inclusive_or_exclusive && ! empty( $original_order_item ) && $this->get_prices_include_tax() ) { $sign_up_fee_proportion = $sign_up_fee / ( $original_order_item->get_total( 'edit' ) / $original_order_item->get_quantity( 'edit' ) );
$proportion = $sign_up_fee / ( $original_order_item->get_total( 'edit' ) / $original_order_item->get_quantity( 'edit' ) ); $sign_up_fee_tax = wc_round_tax_total( $original_order_item->get_total_tax( 'edit' ) * $sign_up_fee_proportion );
$sign_up_fee += round( $original_order_item->get_total_tax( 'edit' ) * $proportion, 2 );
// If prices don't inc tax, ensure that the sign up fee amount includes the tax.
if ( 'inclusive_of_tax' === $tax_inclusive_or_exclusive && ! $this->get_prices_include_tax() ) {
$sign_up_fee += $sign_up_fee_tax;
// If prices inc tax and the request is for prices exclusive of tax, remove the taxes.
} elseif ( 'inclusive_of_tax' !== $tax_inclusive_or_exclusive && $this->get_prices_include_tax() ) {
$sign_up_fee -= $sign_up_fee_tax;
}
} }
} }

View File

@@ -124,6 +124,8 @@ class WC_Subscriptions_Cart {
add_filter( 'woocommerce_add_to_cart_handler', __CLASS__ . '::add_to_cart_handler', 10, 2 ); add_filter( 'woocommerce_add_to_cart_handler', __CLASS__ . '::add_to_cart_handler', 10, 2 );
add_action( 'woocommerce_cart_calculate_fees', __CLASS__ . '::apply_recurring_fees', 1000, 1 ); add_action( 'woocommerce_cart_calculate_fees', __CLASS__ . '::apply_recurring_fees', 1000, 1 );
add_action( 'woocommerce_checkout_update_order_review', __CLASS__ . '::update_chosen_shipping_methods' );
} }
/** /**
@@ -1159,11 +1161,16 @@ class WC_Subscriptions_Cart {
$added_invalid_notice = true; $added_invalid_notice = true;
} }
WC()->checkout()->shipping_methods[ $recurring_shipping_package_key ] = ''; $shipping_methods[ $recurring_shipping_package_key ] = '';
} }
} }
} }
// If there was an invalid recurring shipping method found, we need to apply the changes to WC()->checkout()->shipping_methods.
if ( $added_invalid_notice ) {
WC()->checkout()->shipping_methods = $shipping_methods;
}
self::$calculation_type = $calculation_type; self::$calculation_type = $calculation_type;
self::$recurring_cart_key = $recurring_cart_key_flag; self::$recurring_cart_key = $recurring_cart_key_flag;
} }
@@ -1294,6 +1301,35 @@ class WC_Subscriptions_Cart {
} }
} }
/**
* Update the chosen recurring package shipping methods from posted checkout form data.
*
* Between requests, the presence of recurring package chosen shipping methods in posted
* checkout data can change. For example, when the number of available shipping methods
* change and cause the hidden elements (generated by @see wcs_cart_print_shipping_input())
* to be displayed or not displayed.
*
* When this occurs, we need to remove those chosen shipping methods from the session so
* that those packages no longer use the previously selected shipping method.
*
* @param string $encoded_form_data Encoded checkout form data.
* @since 2.3.0
*/
public static function update_chosen_shipping_methods( $encoded_form_data ) {
$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods', array() );
parse_str( $encoded_form_data, $form_data );
foreach ( $chosen_shipping_methods as $package_index => $method ) {
// Remove the chosen shipping methods for recurring packages which are no longer present in posted checkout data.
if ( ! is_numeric( $package_index ) && ! isset( $form_data['shipping_method'][ $package_index ] ) ) {
unset( $chosen_shipping_methods[ $package_index ] );
}
}
WC()->session->set( 'chosen_shipping_methods', $chosen_shipping_methods );
}
/* Deprecated */ /* Deprecated */
/** /**

View File

@@ -225,7 +225,7 @@ class WC_Subscriptions_Checkout {
$subscription->set_total( $cart->total ); $subscription->set_total( $cart->total );
// Hook to adjust subscriptions before saving with WC 3.0+ (matches WC 3.0's new 'woocommerce_checkout_create_order' hook) // Hook to adjust subscriptions before saving with WC 3.0+ (matches WC 3.0's new 'woocommerce_checkout_create_order' hook)
do_action( 'woocommerce_checkout_create_subscription', $subscription, $posted_data ); do_action( 'woocommerce_checkout_create_subscription', $subscription, $posted_data, $order, $cart );
// Save the subscription if using WC 3.0 & CRUD // Save the subscription if using WC 3.0 & CRUD
$subscription->save(); $subscription->save();

View File

@@ -12,6 +12,13 @@
*/ */
class WC_Subscriptions_Coupon { class WC_Subscriptions_Coupon {
/**
* The meta key used for the number of renewals.
*
* @var string
*/
protected static $coupons_renewals = '_wcs_number_payments';
/** @var string error message for invalid subscription coupons */ /** @var string error message for invalid subscription coupons */
public static $coupon_error; public static $coupon_error;
@@ -19,9 +26,31 @@ class WC_Subscriptions_Coupon {
* Stores the coupons not applied to a given calculation (so they can be applied later) * Stores the coupons not applied to a given calculation (so they can be applied later)
* *
* @since 1.3.5 * @since 1.3.5
* @deprecated
*/ */
private static $removed_coupons = array(); private static $removed_coupons = array();
/**
* Subscription coupon types.
*
* @var array
*/
private static $recurring_coupons = array(
'recurring_fee' => 1,
'recurring_percent' => 1,
);
/**
* Virtual renewal coupon types.
*
* @var array
*/
private static $renewal_coupons = array(
'renewal_cart' => 1,
'renewal_fee' => 1,
'renewal_percent' => 1,
);
/** /**
* Set up the class, including it's hooks & filters, when the file is loaded. * Set up the class, including it's hooks & filters, when the file is loaded.
* *
@@ -50,6 +79,63 @@ class WC_Subscriptions_Coupon {
} }
add_filter( 'woocommerce_cart_totals_coupon_label', __CLASS__ . '::get_pseudo_coupon_label', 10, 2 ); add_filter( 'woocommerce_cart_totals_coupon_label', __CLASS__ . '::get_pseudo_coupon_label', 10, 2 );
add_filter( 'woocommerce_cart_totals_coupon_html', __CLASS__ . '::mark_recurring_coupon_in_initial_cart_for_hiding', 10, 3 );
// Hook recurring coupon functionality.
add_action( 'plugins_loaded', array( __CLASS__, 'maybe_add_recurring_coupon_hooks' ) );
}
/**
* Maybe add Recurring Coupon functionality.
*
* WC 3.2 added many API enhancements, especially around coupons. It would be very challenging to implement
* this functionality in older versions of WC, so we require 3.2+ to enable this.
*
* @author Jeremy Pry
*/
public static function maybe_add_recurring_coupon_hooks() {
if ( WC_Subscriptions::is_woocommerce_pre( '3.2' ) ) {
return;
}
// 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 );
}
/**
* When all items in the cart have free trial, a recurring coupon should not be applied to the main cart.
* Mark such recurring coupons with a dummy span with class wcs-hidden-coupon so that it can be hidden.
*
* @param string $coupon_html Html string of the recurring coupon's cell in the Cart totals table
* @param WC_coupon $coupon WC_Coupon object of the recurring coupon
* @return string $coupon_html Modified html string of the coupon containing the marking
* @since 2.3
*/
public static function mark_recurring_coupon_in_initial_cart_for_hiding( $coupon_html, $coupon ) {
$displaying_initial_cart_totals = false;
if ( is_cart() ) {
$displaying_initial_cart_totals = did_action( 'woocommerce_before_cart_totals' ) > did_action( 'woocommerce_cart_totals_before_order_total' );
} elseif ( is_checkout() ) {
$displaying_initial_cart_totals = did_action( 'woocommerce_review_order_after_cart_contents' ) > did_action( 'woocommerce_review_order_before_order_total' );
}
if ( $displaying_initial_cart_totals && WC_Subscriptions_Cart::all_cart_items_have_free_trial() && in_array( wcs_get_coupon_property( $coupon, 'discount_type' ), array( 'recurring_fee', 'recurring_percent' ) ) ) {
$coupon_html .= '<span class="wcs-hidden-coupon" type="hidden"></span>';
}
return $coupon_html;
} }
/** /**
@@ -435,55 +521,6 @@ class WC_Subscriptions_Coupon {
} }
/**
* Checks a given product / coupon combination to determine if the subscription should be discounted
*
* @since 1.2
*/
private static function is_subscription_discountable( $cart_item, $coupon ) {
$product_cats = wp_get_post_terms( $cart_item['product_id'], 'product_cat', array( 'fields' => 'ids' ) );
$this_item_is_discounted = false;
// Specific products get the discount
if ( sizeof( $coupon_product_ids = wcs_get_coupon_property( $coupon, 'product_ids' ) ) > 0 ) {
if ( in_array( wcs_get_canonical_product_id( $cart_item ), $coupon_product_ids ) || in_array( $cart_item['data']->get_parent(), $coupon_product_ids ) ) {
$this_item_is_discounted = true;
}
// Category discounts
} elseif ( sizeof( $coupon_product_categories = wcs_get_coupon_property( $coupon, 'product_categories' ) ) > 0 ) {
if ( sizeof( array_intersect( $product_cats, $coupon_product_categories ) ) > 0 ) {
$this_item_is_discounted = true;
}
} else {
// No product ids - all items discounted
$this_item_is_discounted = true;
}
// Specific product ID's excluded from the discount
if ( sizeof( $coupon_excluded_product_ids = wcs_get_coupon_property( $coupon, 'exclude_product_ids' ) ) > 0 ) {
if ( in_array( wcs_get_canonical_product_id( $cart_item ), $coupon_excluded_product_ids ) || in_array( $cart_item['data']->get_parent(), $coupon_excluded_product_ids ) ) {
$this_item_is_discounted = false;
}
}
// Specific categories excluded from the discount
if ( sizeof( $coupon_excluded_product_categories = wcs_get_coupon_property( $coupon, 'exclude_product_categories' ) ) > 0 ) {
if ( sizeof( array_intersect( $product_cats, $coupon_excluded_product_categories ) ) > 0 ) {
$this_item_is_discounted = false;
}
}
// Apply filter
return apply_filters( 'woocommerce_item_is_discounted', $this_item_is_discounted, $cart_item, $before_tax = false );
}
/** /**
* Sets which coupons should be applied for this calculation. * Sets which coupons should be applied for this calculation.
* *
@@ -491,53 +528,49 @@ class WC_Subscriptions_Coupon {
* product's total based on the total of it's price per period and sign up fee (if any). * product's total based on the total of it's price per period and sign up fee (if any).
* *
* @since 1.3.5 * @since 1.3.5
*
* @param WC_Cart $cart
*/ */
public static function remove_coupons( $cart ) { public static function remove_coupons( $cart ) {
$calculation_type = WC_Subscriptions_Cart::get_calculation_type(); $calculation_type = WC_Subscriptions_Cart::get_calculation_type();
// Only hook when totals are being calculated completely (on cart & checkout pages) // Only hook when totals are being calculated completely (on cart & checkout pages)
if ( 'none' == $calculation_type || ! WC_Subscriptions_Cart::cart_contains_subscription() || ( ! is_checkout() && ! is_cart() && ! defined( 'WOOCOMMERCE_CHECKOUT' ) && ! defined( 'WOOCOMMERCE_CART' ) ) ) { if (
'none' === $calculation_type ||
! WC_Subscriptions_Cart::cart_contains_subscription() ||
( ! is_checkout() && ! is_cart() && ! defined( 'WOOCOMMERCE_CHECKOUT' ) && ! defined( 'WOOCOMMERCE_CART' ) )
) {
return; return;
} }
$applied_coupons = $cart->get_applied_coupons(); $applied_coupons = $cart->get_applied_coupons();
if ( empty( $applied_coupons ) ) {
return;
}
// If we're calculating a sign-up fee or recurring fee only amount, remove irrelevant coupons // If we're calculating a sign-up fee or recurring fee only amount, remove irrelevant coupons
if ( ! empty( $applied_coupons ) ) { foreach ( $applied_coupons as $coupon_code ) {
$coupon = new WC_Coupon( $coupon_code );
$coupon_type = wcs_get_coupon_property( $coupon, 'discount_type' );
if ( ! isset( self::$recurring_coupons[ $coupon_type ] ) ) {
$cart->remove_coupon( $coupon_code );
continue;
}
// Keep track of which coupons, if any, need to be reapplied immediately if ( 'recurring_total' === $calculation_type ) {
$coupons_to_reapply = array(); // Special handling for a single payment coupon.
if ( 1 === self::get_coupon_limit( $coupon_code ) && 0 < $cart->get_coupon_discount_amount( $coupon_code ) ) {
foreach ( $applied_coupons as $coupon_code ) { $cart->remove_coupon( $coupon_code );
$coupon = new WC_Coupon( $coupon_code );
$coupon_type = wcs_get_coupon_property( $coupon, 'discount_type' );
if ( in_array( $coupon_type, array( 'recurring_fee', 'recurring_percent' ) ) ) { // always apply coupons to their specific calculation case
if ( 'recurring_total' == $calculation_type ) {
$coupons_to_reapply[] = $coupon_code;
} elseif ( 'none' == $calculation_type && ! WC_Subscriptions_Cart::all_cart_items_have_free_trial() ) { // sometimes apply recurring coupons to initial total
$coupons_to_reapply[] = $coupon_code;
} else {
self::$removed_coupons[] = $coupon_code;
}
} elseif ( ( 'none' == $calculation_type ) && ! in_array( $coupon_type, array( 'recurring_fee', 'recurring_percent' ) ) ) { // apply all coupons to the first payment
$coupons_to_reapply[] = $coupon_code;
} else {
self::$removed_coupons[] = $coupon_code;
} }
continue;
} }
// Now remove all coupons (WC only provides a function to remove all coupons) if ( ! WC_Subscriptions_Cart::all_cart_items_have_free_trial() ) {
$cart->remove_coupons(); continue;
// And re-apply those which relate to this calculation
$cart->applied_coupons = $coupons_to_reapply;
if ( isset( $cart->coupons ) ) { // WC 2.3+
$cart->coupons = $cart->get_coupons();
} }
$cart->remove_coupon( $coupon_code );
} }
} }
@@ -658,6 +691,335 @@ class WC_Subscriptions_Coupon {
return $label; return $label;
} }
/**
* Determine whether the cart contains a recurring coupon with set number of renewals.
*
* @author Jeremy Pry
* @return bool
*/
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;
}
/**
* Determine if a given order has a limited use coupon.
*
* @author Jeremy Pry
*
* @param WC_Order|WC_Subscription $order
*
* @return bool
*/
public static function order_has_limited_recurring_coupon( $order ) {
$has_coupon = false;
$coupons = $order->get_used_coupons();
foreach ( $coupons as $code ) {
if ( self::coupon_is_limited( $code ) ) {
$has_coupon = true;
break;
}
}
return $has_coupon;
}
/**
* Determine if a given coupon is limited to a certain number of renewals.
*
* @author Jeremy Pry
*
* @param string $code The coupon code.
*
* @return bool
*/
public static function coupon_is_limited( $code ) {
return (bool) self::get_coupon_limit( $code );
}
/**
* Get the number of renewals for a limited coupon.
*
* @author Jeremy Pry
*
* @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 ( WC_Subscriptions::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 ( isset( self::$renewal_coupons[ $coupon_type ] ) ) {
$coupon = self::map_virtual_coupon( $code );
$coupon_type = $coupon->get_discount_type();
}
$limited = $coupon->get_meta( self::$coupons_renewals );
return isset( self::$recurring_coupons[ $coupon_type ] ) ? intval( $limited ) : false;
}
/**
* Get a normal coupon from one of our virtual coupons.
*
* This is necessary when manually processing a renewal to ensure that we are correctly
* identifying limited payment coupons.
*
* @author Jeremy Pry
*
* @param string $code The virtual coupon code.
*
* @return WC_Coupon The original coupon.
*/
private static function map_virtual_coupon( $code ) {
add_filter( 'woocommerce_get_shop_coupon_data', '__return_false', 100 );
$coupon = new WC_Coupon( $code );
remove_filter( 'woocommerce_get_shop_coupon_data', '__return_false', 100 );
return $coupon;
}
/**
* Limit payment gateways to those that support changing subscription amounts.
*
* @author Jeremy Pry
*
* @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;
}
/**
* Filter the available gateways when there is a recurring coupon.
*
* @author Jeremy Pry
*
* @param WC_Payment_Gateway[] $gateways The available payment gateways.
*
* @return array The filtered payment gateways.
*/
public static function gateways_subscription_amount_changes( $gateways ) {
// If there are already no gateways, bail early.
if ( empty( $gateways ) ) {
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.
*
* @author Jeremy Pry
*
* @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( $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' );
}
/**
* Add custom fields to the coupon data form.
*
* @see WC_Meta_Box_Coupon_Data::output()
* @author Jeremy Pry
*
* @param int $id The coupon ID.
*/
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 ),
) );
}
/**
* Save our custom coupon fields.
*
* @see WC_Meta_Box_Coupon_Data::save()
* @author Jeremy Pry
*
* @param int $post_id
*/
public static function save_coupon_fields( $post_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( $post_id );
$coupon->add_meta_data( self::$coupons_renewals, wc_clean( $_POST['wcs_number_payments'] ), true );
$coupon->save();
}
/**
* Determine how many subscriptions the coupon has been applied to.
*
* @author Jeremy Pry
*
* @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 = $subscription->get_used_coupons();
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 ] = 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 ( null !== $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() ]++;
}
}
}
// Check each coupon to see if it needs to be removed.
foreach ( $limited_coupons as $code => $count ) {
if ( self::get_coupon_limit( $code ) <= $count ) {
$subscription->remove_coupon( $code );
$subscription->add_order_note( sprintf(
_n(
/* translators: %1$s is the coupon code, %2$d is the number of payment usages */
'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.',
$count,
'woocommerce-subscriptions'
),
$code,
number_format_i18n( $count )
) );
}
}
}
/**
* Add our limited coupon data to the Coupon list table.
*
* @author Jeremy Pry
*
* @param string $column_name The name of the current column in the table.
* @param int $post_id The coupon post ID.
*/
public static function add_limit_to_list_table( $column_name, $post_id ) {
if ( 'usage' !== $column_name ) {
return;
}
$limit = self::get_coupon_limit( wc_get_coupon_code_by_id( $post_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' );
}
}
/* Deprecated */ /* Deprecated */
/** /**

View File

@@ -133,7 +133,7 @@ class WC_Subscriptions_Manager {
} else { } else {
if ( $subscription->is_manual() ) { if ( $subscription->is_manual() ) {
do_action( 'woocommerce_generated_manual_renewal_order', wcs_get_objects_property( $renewal_order, 'id' ) ); do_action( 'woocommerce_generated_manual_renewal_order', wcs_get_objects_property( $renewal_order, 'id' ), $subscription );
} else { } else {
$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 $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

View File

@@ -742,12 +742,19 @@ class WC_Subscriptions_Order {
case 'switch' : case 'switch' :
$meta_key = '_subscription_switch'; $meta_key = '_subscription_switch';
break; break;
default:
$meta_key = '';
break;
} }
$vars['meta_query'][] = array( $meta_key = apply_filters( 'woocommerce_subscriptions_admin_order_type_filter_meta_key', $meta_key, $_GET['shop_order_subtype'] );
'key' => $meta_key,
'compare' => 'EXISTS', if ( ! empty( $meta_key ) ) {
); $vars['meta_query'][] = array(
'key' => $meta_key,
'compare' => 'EXISTS',
);
}
} }
// Also exclude parent orders from non-subscription query // Also exclude parent orders from non-subscription query
@@ -1047,7 +1054,7 @@ class WC_Subscriptions_Order {
$order = wc_get_order( $order_id ); $order = wc_get_order( $order_id );
add_filter( 'woocommerce_payment_complete_order_status', __METHOD__, 10, 2 ); add_filter( 'woocommerce_payment_complete_order_status', __METHOD__, 10, 2 );
if ( 'processing' == $new_order_status && $order->get_total() == 0 && wcs_order_contains_subscription( $order ) ) { if ( 'processing' == $new_order_status && $order->get_subtotal() == 0 && wcs_order_contains_subscription( $order ) ) {
if ( wcs_order_contains_resubscribe( $order ) ) { if ( wcs_order_contains_resubscribe( $order ) ) {
$new_order_status = 'completed'; $new_order_status = 'completed';

View File

@@ -310,44 +310,52 @@ class WC_Subscriptions_Product {
if ( $include_length && $subscription_length == $billing_interval ) { if ( $include_length && $subscription_length == $billing_interval ) {
$subscription_string = $price; // Only for one billing period so show "$5 for 3 months" instead of "$5 every 3 months for 3 months" $subscription_string = $price; // Only for one billing period so show "$5 for 3 months" instead of "$5 every 3 months for 3 months"
} elseif ( WC_Subscriptions_Synchroniser::is_product_synced( $product ) && in_array( $billing_period, array( 'week', 'month', 'year' ) ) ) { } elseif ( WC_Subscriptions_Synchroniser::is_product_synced( $product ) && in_array( $billing_period, array( 'week', 'month', 'year' ) ) ) {
$subscription_string = '';
// Include string for upfront payment.
if ( WC_Subscriptions_Synchroniser::is_payment_upfront( $product ) ) {
/* translators: %1$s refers to the price. This string is meant to prefix another string below, e.g. "$5 now, and $5 on March 15th each year" */
$subscription_string = sprintf( __( '%1$s now, and ', 'woocommerce-subscriptions' ), $price );
}
$payment_day = WC_Subscriptions_Synchroniser::get_products_payment_day( $product ); $payment_day = WC_Subscriptions_Synchroniser::get_products_payment_day( $product );
switch ( $billing_period ) { switch ( $billing_period ) {
case 'week': case 'week':
$payment_day_of_week = WC_Subscriptions_Synchroniser::get_weekday( $payment_day ); $payment_day_of_week = WC_Subscriptions_Synchroniser::get_weekday( $payment_day );
if ( 1 == $billing_interval ) { if ( 1 == $billing_interval ) {
// translators: 1$: recurring amount string, 2$: day of the week (e.g. "$10 every Wednesday") // translators: 1$: recurring amount string, 2$: day of the week (e.g. "$10 every Wednesday")
$subscription_string = sprintf( __( '%1$s every %2$s', 'woocommerce-subscriptions' ), $price, $payment_day_of_week ); $subscription_string .= sprintf( __( '%1$s every %2$s', 'woocommerce-subscriptions' ), $price, $payment_day_of_week );
} else { } else {
// translators: 1$: recurring amount string, 2$: period, 3$: day of the week (e.g. "$10 every 2nd week on Wednesday") // translators: 1$: recurring amount string, 2$: period, 3$: day of the week (e.g. "$10 every 2nd week on Wednesday")
$subscription_string = sprintf( __( '%1$s every %2$s on %3$s', 'woocommerce-subscriptions' ), $price, wcs_get_subscription_period_strings( $billing_interval, $billing_period ), $payment_day_of_week ); $subscription_string .= sprintf( __( '%1$s every %2$s on %3$s', 'woocommerce-subscriptions' ), $price, wcs_get_subscription_period_strings( $billing_interval, $billing_period ), $payment_day_of_week );
} }
break; break;
case 'month': case 'month':
if ( 1 == $billing_interval ) { if ( 1 == $billing_interval ) {
if ( $payment_day > 27 ) { if ( $payment_day > 27 ) {
// translators: placeholder is recurring amount // translators: placeholder is recurring amount
$subscription_string = sprintf( __( '%s on the last day of each month', 'woocommerce-subscriptions' ), $price ); $subscription_string .= sprintf( __( '%s on the last day of each month', 'woocommerce-subscriptions' ), $price );
} else { } else {
// translators: 1$: recurring amount, 2$: day of the month (e.g. "23rd") (e.g. "$5 every 23rd of each month") // translators: 1$: recurring amount, 2$: day of the month (e.g. "23rd") (e.g. "$5 every 23rd of each month")
$subscription_string = sprintf( __( '%1$s on the %2$s of each month', 'woocommerce-subscriptions' ), $price, WC_Subscriptions::append_numeral_suffix( $payment_day ) ); $subscription_string .= sprintf( __( '%1$s on the %2$s of each month', 'woocommerce-subscriptions' ), $price, WC_Subscriptions::append_numeral_suffix( $payment_day ) );
} }
} else { } else {
if ( $payment_day > 27 ) { if ( $payment_day > 27 ) {
// translators: 1$: recurring amount, 2$: interval (e.g. "3rd") (e.g. "$10 on the last day of every 3rd month") // translators: 1$: recurring amount, 2$: interval (e.g. "3rd") (e.g. "$10 on the last day of every 3rd month")
$subscription_string = sprintf( __( '%1$s on the last day of every %2$s month', 'woocommerce-subscriptions' ), $price, WC_Subscriptions::append_numeral_suffix( $billing_interval ) ); $subscription_string .= sprintf( __( '%1$s on the last day of every %2$s month', 'woocommerce-subscriptions' ), $price, WC_Subscriptions::append_numeral_suffix( $billing_interval ) );
} else { } else {
// translators: 1$: <price> on the, 2$: <date> day of every, 3$: <interval> month (e.g. "$10 on the 23rd day of every 2nd month") // translators: 1$: <price> on the, 2$: <date> day of every, 3$: <interval> month (e.g. "$10 on the 23rd day of every 2nd month")
$subscription_string = sprintf( __( '%1$s on the %2$s day of every %3$s month', 'woocommerce-subscriptions' ), $price, WC_Subscriptions::append_numeral_suffix( $payment_day ), WC_Subscriptions::append_numeral_suffix( $billing_interval ) ); $subscription_string .= sprintf( __( '%1$s on the %2$s day of every %3$s month', 'woocommerce-subscriptions' ), $price, WC_Subscriptions::append_numeral_suffix( $payment_day ), WC_Subscriptions::append_numeral_suffix( $billing_interval ) );
} }
} }
break; break;
case 'year': case 'year':
if ( 1 == $billing_interval ) { if ( 1 == $billing_interval ) {
// translators: 1$: <price> on, 2$: <date>, 3$: <month> each year (e.g. "$15 on March 15th each year") // translators: 1$: <price> on, 2$: <date>, 3$: <month> each year (e.g. "$15 on March 15th each year")
$subscription_string = sprintf( __( '%1$s on %2$s %3$s each year', 'woocommerce-subscriptions' ), $price, $wp_locale->month[ $payment_day['month'] ], WC_Subscriptions::append_numeral_suffix( $payment_day['day'] ) ); $subscription_string .= sprintf( __( '%1$s on %2$s %3$s each year', 'woocommerce-subscriptions' ), $price, $wp_locale->month[ $payment_day['month'] ], WC_Subscriptions::append_numeral_suffix( $payment_day['day'] ) );
} else { } else {
// translators: 1$: recurring amount, 2$: month (e.g. "March"), 3$: day of the month (e.g. "23rd") (e.g. "$15 on March 15th every 3rd year") // translators: 1$: recurring amount, 2$: month (e.g. "March"), 3$: day of the month (e.g. "23rd") (e.g. "$15 on March 15th every 3rd year")
$subscription_string = sprintf( __( '%1$s on %2$s %3$s every %4$s year', 'woocommerce-subscriptions' ), $price, $wp_locale->month[ $payment_day['month'] ], WC_Subscriptions::append_numeral_suffix( $payment_day['day'] ), WC_Subscriptions::append_numeral_suffix( $billing_interval ) ); $subscription_string .= sprintf( __( '%1$s on %2$s %3$s every %4$s year', 'woocommerce-subscriptions' ), $price, $wp_locale->month[ $payment_day['month'] ], WC_Subscriptions::append_numeral_suffix( $payment_day['day'] ), WC_Subscriptions::append_numeral_suffix( $billing_interval ) );
} }
break; break;
} }
@@ -855,6 +863,27 @@ class WC_Subscriptions_Product {
* @since 1.5.29 * @since 1.5.29
*/ */
public static function bulk_edit_variations( $bulk_action, $data, $variable_product_id, $variation_ids ) { public static function bulk_edit_variations( $bulk_action, $data, $variable_product_id, $variation_ids ) {
if ( 'delete_all_no_subscriptions' === $bulk_action && isset( $data['allowed'] ) && 'true' == $data['allowed'] ) {
$deleted = 0;
foreach ( $variation_ids as $variation_id ) {
$variation = wc_get_product( $variation_id );
$subscriptions = wcs_get_subscriptions_for_product( $variation_id );
if ( empty( $subscriptions ) ) {
if ( is_callable( array( $variation, 'delete' ) ) ) {
$variation->delete( true );
} else {
wp_delete_post( $variation_id );
}
$deleted++;
}
}
echo intval( $deleted );
return;
}
if ( ! isset( $data['value'] ) ) { if ( ! isset( $data['value'] ) ) {
return; return;
@@ -1059,6 +1088,10 @@ class WC_Subscriptions_Product {
$min_max_data = wcs_get_min_max_variation_data( $product, $child_variation_ids ); $min_max_data = wcs_get_min_max_variation_data( $product, $child_variation_ids );
if ( is_callable( array( $product, 'set_min_and_max_variation_data' ) ) ) {
$product->set_min_and_max_variation_data( $min_max_data, $child_variation_ids );
}
$product->add_meta_data( '_min_price_variation_id', $min_max_data['min']['variation_id'], true ); $product->add_meta_data( '_min_price_variation_id', $min_max_data['min']['variation_id'], true );
$product->add_meta_data( '_max_price_variation_id', $min_max_data['max']['variation_id'], true ); $product->add_meta_data( '_max_price_variation_id', $min_max_data['max']['variation_id'], true );
@@ -1098,7 +1131,7 @@ class WC_Subscriptions_Product {
global $wpdb; global $wpdb;
$parent_product_ids = array(); $parent_product_ids = array();
if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) && $product->get_parent() ) { if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) && isset( $product->post->post_parent ) ) {
$parent_product_ids[] = $product->get_parent(); $parent_product_ids[] = $product->get_parent();
} else { } else {
$parent_product_ids = $wpdb->get_col( $wpdb->prepare( $parent_product_ids = $wpdb->get_col( $wpdb->prepare(
@@ -1112,6 +1145,30 @@ class WC_Subscriptions_Product {
return $parent_product_ids; return $parent_product_ids;
} }
/**
* Get a product's list of parent IDs which are a grouped type.
*
* Unlike @see WC_Subscriptions_Product::get_parent_ids(), this function will return parent products which still exist, are visible and are a grouped product.
*
* @param WC_Product The product object to get parents from.
* @return array The product's grouped parent IDs.
* @since 2.3.0
*/
public static function get_visible_grouped_parent_product_ids( $product ) {
$parent_product_ids = self::get_parent_ids( $product );
// Verify that the parent products exist and are indeed grouped products
foreach ( $parent_product_ids as $index => $product_id ) {
$parent_product = wc_get_product( $product_id );
if ( ! is_a( $parent_product, 'WC_Product' ) || ! $parent_product->is_type( 'grouped' ) || 'publish' !== wcs_get_objects_property( $parent_product, 'post_status' ) ) {
unset( $parent_product_ids[ $index ] );
}
}
return $parent_product_ids;
}
/************************ /************************
* Deprecated Functions * * Deprecated Functions *
************************/ ************************/

View File

@@ -20,18 +20,18 @@ class WC_Subscriptions_Renewal_Order {
public static function init() { public static function init() {
// Trigger special hook when payment is completed on renewal orders // Trigger special hook when payment is completed on renewal orders
add_action( 'woocommerce_payment_complete', __CLASS__ . '::trigger_renewal_payment_complete', 10 ); add_action( 'woocommerce_payment_complete', array( __CLASS__, 'trigger_renewal_payment_complete' ), 10 );
// When a renewal order's status changes, check if a corresponding subscription's status should be changed by marking it as paid (we can't use the 'woocommerce_payment_complete' here because it's not triggered by all payment gateways) // When a renewal order's status changes, check if a corresponding subscription's status should be changed by marking it as paid (we can't use the 'woocommerce_payment_complete' here because it's not triggered by all payment gateways)
add_filter( 'woocommerce_order_status_changed', __CLASS__ . '::maybe_record_subscription_payment', 10, 3 ); add_action( 'woocommerce_order_status_changed', array( __CLASS__, 'maybe_record_subscription_payment' ), 10, 3 );
add_filter( 'wcs_renewal_order_created', __CLASS__ . '::add_order_note', 10, 2 ); add_filter( 'wcs_renewal_order_created', array( __CLASS__, 'add_order_note' ), 10, 2 );
// Prevent customers from cancelling renewal orders. Needs to be hooked before WC_Form_Handler::cancel_order() (20) // Prevent customers from cancelling renewal orders. Needs to be hooked before WC_Form_Handler::cancel_order() (20)
add_filter( 'wp_loaded', __CLASS__ . '::prevent_cancelling_renewal_orders', 19, 3 ); add_action( 'wp_loaded', array( __CLASS__, 'prevent_cancelling_renewal_orders' ), 19, 3 );
// Don't copy switch order item meta to renewal order items // Don't copy switch order item meta to renewal order items
add_filter( 'wcs_new_order_items', __CLASS__ . '::remove_switch_item_meta_keys', 10, 1 ); add_filter( 'wcs_new_order_items', array( __CLASS__, 'remove_switch_item_meta_keys' ), 10, 1 );
} }
/* Helper functions */ /* Helper functions */

View File

@@ -82,9 +82,6 @@ class WC_Subscriptions_Switcher {
// Make sure sign-up fees paid on switch orders are accounted for in an items sign-up fee // Make sure sign-up fees paid on switch orders are accounted for in an items sign-up fee
add_filter( 'woocommerce_subscription_items_sign_up_fee', __CLASS__ . '::subscription_items_sign_up_fee', 10, 4 ); add_filter( 'woocommerce_subscription_items_sign_up_fee', __CLASS__ . '::subscription_items_sign_up_fee', 10, 4 );
// Make sure switch orders are included in related orders returned for a subscription
add_filter( 'woocommerce_subscription_related_orders', __CLASS__ . '::add_related_orders', 10, 4 );
// Display/indicate whether a cart switch item is a upgrade/downgrade/crossgrade // Display/indicate whether a cart switch item is a upgrade/downgrade/crossgrade
add_filter( 'woocommerce_cart_item_subtotal', __CLASS__ . '::add_cart_item_switch_direction', 10, 3 ); add_filter( 'woocommerce_cart_item_subtotal', __CLASS__ . '::add_cart_item_switch_direction', 10, 3 );
@@ -467,7 +464,7 @@ class WC_Subscriptions_Switcher {
} }
$product = wc_get_product( $item['product_id'] ); $product = wc_get_product( $item['product_id'] );
$parent_products = WC_Subscriptions_Product::get_parent_ids( $product ); $parent_products = WC_Subscriptions_Product::get_visible_grouped_parent_product_ids( $product );
$additional_query_args = array(); $additional_query_args = array();
// Grouped product // Grouped product
@@ -584,14 +581,14 @@ class WC_Subscriptions_Switcher {
$order = wc_get_order( $order_id ); $order = wc_get_order( $order_id );
// delete all the existing subscription switch links before adding new ones // delete all the existing subscription switch links before adding new ones
wcs_delete_objects_property( $order, 'subscription_switch' ); WCS_Related_Order_Store::instance()->delete_relations( $order, 'switch' );
$switches = self::cart_contains_switches(); $switches = self::cart_contains_switches();
if ( false !== $switches ) { if ( false !== $switches ) {
foreach ( $switches as $switch_details ) { foreach ( $switches as $switch_details ) {
wcs_set_objects_property( $order, 'subscription_switch', $switch_details['subscription_id'] ); WCS_Related_Order_Store::instance()->add_relation( $order, wcs_get_subscription( $switch_details['subscription_id'] ), 'switch' );
} }
} }
} }
@@ -1323,7 +1320,7 @@ class WC_Subscriptions_Switcher {
// Because product add-ons etc. don't apply to sign-up fees, it's safe to use the product's sign-up fee value rather than the cart item's // Because product add-ons etc. don't apply to sign-up fees, it's safe to use the product's sign-up fee value rather than the cart item's
$sign_up_fee_due = WC_Subscriptions_Product::get_sign_up_fee( $product ); $sign_up_fee_due = WC_Subscriptions_Product::get_sign_up_fee( $product );
$sign_up_fee_paid = $subscription->get_items_sign_up_fee( $existing_item, 'inclusive_of_tax' ); $sign_up_fee_paid = $subscription->get_items_sign_up_fee( $existing_item, get_option( 'woocommerce_prices_include_tax' ) === 'yes' ? 'inclusive_of_tax' : 'exclusive_of_tax' );
// Make sure total prorated sign-up fee is prorated across total amount of sign-up fee so that customer doesn't get extra discounts // Make sure total prorated sign-up fee is prorated across total amount of sign-up fee so that customer doesn't get extra discounts
if ( $cart_item['quantity'] > $existing_item['qty'] ) { if ( $cart_item['quantity'] > $existing_item['qty'] ) {
@@ -1764,32 +1761,6 @@ class WC_Subscriptions_Switcher {
return $table_content; return $table_content;
} }
/**
* Filter the WC_Subscription::get_related_orders() method to include switch orders.
*
* @since 2.0
*/
public static function add_related_orders( $related_orders, $subscription, $return_fields, $order_type ) {
if ( in_array( $order_type, array( 'all', 'switch' ) ) ) {
$switch_orders = wcs_get_switch_orders_for_subscription( $subscription->get_id() );
if ( 'all' == $return_fields ) {
$related_orders += $switch_orders;
} else {
foreach ( $switch_orders as $order_id => $order ) {
$related_orders[ $order_id ] = $order_id;
}
}
// This will change the ordering to be by ID instead of the default of date
krsort( $related_orders );
}
return $related_orders;
}
/** /**
* Add the cart item upgrade/downgrade/crossgrade direction for display * Add the cart item upgrade/downgrade/crossgrade direction for display
* *
@@ -2428,8 +2399,6 @@ class WC_Subscriptions_Switcher {
return $cart_contains_subscription_creating_switch; return $cart_contains_subscription_creating_switch;
} }
/** Deprecated Methods **/
/** /**
* Don't allow switched subscriptions to be cancelled. * Don't allow switched subscriptions to be cancelled.
* *
@@ -2688,5 +2657,39 @@ class WC_Subscriptions_Switcher {
} }
} }
} }
/**
* Filter the WC_Subscription::get_related_orders() method to include switch orders.
*
* @since 2.0
* @deprecated
*
* @param array $related_orders
* @param WC_Subscription $subscription
* @param string $return_fields
* @param string $order_type
*
* @return array
*/
public static function add_related_orders( $related_orders, $subscription, $return_fields, $order_type ) {
wcs_deprecated_function( __METHOD__, '2.3.0', 'wcs_get_switch_orders_for_subscription()' );
if ( in_array( $order_type, array( 'all', 'switch' ) ) ) {
$switch_orders = wcs_get_switch_orders_for_subscription( $subscription->get_id() );
if ( 'all' == $return_fields ) {
$related_orders += $switch_orders;
} else {
foreach ( $switch_orders as $order_id => $order ) {
$related_orders[ $order_id ] = $order_id;
}
}
// This will change the ordering to be by ID instead of the default of date
krsort( $related_orders );
}
return $related_orders;
}
} }
WC_Subscriptions_Switcher::init(); WC_Subscriptions_Switcher::init();

View File

@@ -12,6 +12,7 @@ class WC_Subscriptions_Synchroniser {
public static $setting_id; public static $setting_id;
public static $setting_id_proration; public static $setting_id_proration;
public static $setting_id_days_no_fee;
public static $post_meta_key = '_subscription_payment_sync_date'; public static $post_meta_key = '_subscription_payment_sync_date';
public static $post_meta_key_day = '_subscription_payment_sync_date_day'; public static $post_meta_key_day = '_subscription_payment_sync_date_day';
@@ -40,9 +41,9 @@ class WC_Subscriptions_Synchroniser {
* @since 1.5 * @since 1.5
*/ */
public static function init() { public static function init() {
self::$setting_id = WC_Subscriptions_Admin::$option_prefix . '_sync_payments';
self::$setting_id = WC_Subscriptions_Admin::$option_prefix . '_sync_payments'; self::$setting_id_proration = WC_Subscriptions_Admin::$option_prefix . '_prorate_synced_payments';
self::$setting_id_proration = WC_Subscriptions_Admin::$option_prefix . '_prorate_synced_payments'; self::$setting_id_days_no_fee = WC_Subscriptions_Admin::$option_prefix . '_days_no_fee';
self::$sync_field_label = __( 'Synchronise renewals', 'woocommerce-subscriptions' ); self::$sync_field_label = __( 'Synchronise renewals', 'woocommerce-subscriptions' );
self::$sync_description = __( 'Align the payment date for all customers who purchase this subscription to a specific day of the week or month.', 'woocommerce-subscriptions' ); self::$sync_description = __( 'Align the payment date for all customers who purchase this subscription to a specific day of the week or month.', 'woocommerce-subscriptions' );
@@ -77,11 +78,11 @@ class WC_Subscriptions_Synchroniser {
add_action( 'woocommerce_subscriptions_product_first_renewal_payment_time', __CLASS__ . '::products_first_renewal_payment_time', 10, 4 ); add_action( 'woocommerce_subscriptions_product_first_renewal_payment_time', __CLASS__ . '::products_first_renewal_payment_time', 10, 4 );
// Maybe mock a free trial on the product for calculating totals and displaying correct shipping costs // Maybe mock a free trial on the product for calculating totals and displaying correct shipping costs
add_filter( 'woocommerce_before_calculate_totals', __CLASS__ . '::maybe_set_free_trial', 0, 1 ); add_action( 'woocommerce_before_calculate_totals', __CLASS__ . '::maybe_set_free_trial', 0, 1 );
add_action( 'woocommerce_subscription_cart_before_grouping', __CLASS__ . '::maybe_unset_free_trial' ); add_action( 'woocommerce_subscription_cart_before_grouping', __CLASS__ . '::maybe_unset_free_trial' );
add_action( 'woocommerce_subscription_cart_after_grouping', __CLASS__ . '::maybe_set_free_trial' ); add_action( 'woocommerce_subscription_cart_after_grouping', __CLASS__ . '::maybe_set_free_trial' );
add_action( 'wcs_recurring_cart_start_date', __CLASS__ . '::maybe_unset_free_trial', 0, 1 ); add_filter( 'wcs_recurring_cart_start_date', __CLASS__ . '::maybe_unset_free_trial', 0, 1 );
add_action( 'wcs_recurring_cart_end_date', __CLASS__ . '::maybe_set_free_trial', 100, 1 ); add_filter( 'wcs_recurring_cart_end_date', __CLASS__ . '::maybe_set_free_trial', 100, 1 );
add_filter( 'woocommerce_subscriptions_calculated_total', __CLASS__ . '::maybe_unset_free_trial', 10000, 1 ); add_filter( 'woocommerce_subscriptions_calculated_total', __CLASS__ . '::maybe_unset_free_trial', 10000, 1 );
add_action( 'woocommerce_cart_totals_before_shipping', __CLASS__ . '::maybe_set_free_trial' ); add_action( 'woocommerce_cart_totals_before_shipping', __CLASS__ . '::maybe_set_free_trial' );
add_action( 'woocommerce_cart_totals_after_shipping', __CLASS__ . '::maybe_unset_free_trial' ); add_action( 'woocommerce_cart_totals_after_shipping', __CLASS__ . '::maybe_unset_free_trial' );
@@ -99,8 +100,10 @@ class WC_Subscriptions_Synchroniser {
if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) { if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) {
add_action( 'woocommerce_order_add_product', __CLASS__ . '::maybe_add_meta_for_new_product', 10, 3 ); add_action( 'woocommerce_order_add_product', __CLASS__ . '::maybe_add_meta_for_new_product', 10, 3 );
add_action( 'woocommerce_add_order_item_meta', array( __CLASS__, 'maybe_add_order_item_meta' ), 10, 2 );
} else { } else {
add_action( 'woocommerce_new_order_item', __CLASS__ . '::maybe_add_meta_for_new_line_item', 10, 3 ); add_action( 'woocommerce_new_order_item', __CLASS__ . '::maybe_add_meta_for_new_line_item', 10, 3 );
add_action( 'woocommerce_checkout_create_order_line_item', array( __CLASS__, 'maybe_add_line_item_meta' ), 10, 3 );
} }
// Make sure the sign-up fee for a synchronised subscription is correct // Make sure the sign-up fee for a synchronised subscription is correct
@@ -110,6 +113,58 @@ class WC_Subscriptions_Synchroniser {
add_filter( 'woocommerce_order_item_quantity', __CLASS__ . '::maybe_do_not_reduce_stock', 10, 3 ); add_filter( 'woocommerce_order_item_quantity', __CLASS__ . '::maybe_do_not_reduce_stock', 10, 3 );
add_filter( 'woocommerce_subscriptions_recurring_cart_key', __CLASS__ . '::add_to_recurring_cart_key', 10, 2 ); add_filter( 'woocommerce_subscriptions_recurring_cart_key', __CLASS__ . '::add_to_recurring_cart_key', 10, 2 );
// Add defaults for our options.
add_filter( 'default_option_' . self::$setting_id_days_no_fee, array( __CLASS__, 'option_default' ), 10, 3 );
// Sanitize options when saving.
add_filter( 'woocommerce_admin_settings_sanitize_option_' . self::$setting_id_days_no_fee, array( __CLASS__, 'sanitize_option' ), 10, 2 );
// Ensure options are the proper type.
add_filter( 'option_' . self::$setting_id_days_no_fee, 'intval' );
}
/**
* Set default value of 'no' for our options.
*
* This only sets the default
*
* @author Jeremy Pry
*
* @param mixed $default The default value for the option.
* @param string $option The option name.
* @param bool $passed_default Whether get_option() was passed a default value.
*
* @return mixed The default option value.
*/
public static function option_default( $default, $option, $passed_default = null ) {
switch ( $option ) {
case self::$setting_id_days_no_fee:
$default = $passed_default ? $default : 0;
break;
}
return $default;
}
/**
* Sanitize our options when they are saved in the admin area.
*
* @author Jeremy Pry
*
* @param mixed $value The value being saved.
* @param array $option The option data array.
*
* @return mixed The sanitized option value.
*/
public static function sanitize_option( $value, $option ) {
switch ( $option['id'] ) {
case self::$setting_id_days_no_fee:
$value = absint( $value );
break;
}
return $value;
} }
/** /**
@@ -118,16 +173,16 @@ class WC_Subscriptions_Synchroniser {
* @since 1.5 * @since 1.5
*/ */
public static function is_syncing_enabled() { public static function is_syncing_enabled() {
return ( 'yes' == get_option( self::$setting_id, 'no' ) ) ? true : false; return 'yes' === get_option( self::$setting_id, 'no' );
} }
/** /**
* Check if payment syncing is enabled on the store. * Check if payments can be prorated on the store.
* *
* @since 1.5 * @since 1.5
*/ */
public static function is_sync_proration_enabled() { public static function is_sync_proration_enabled() {
return ( 'no' != get_option( self::$setting_id_proration, 'no' ) ) ? true : false; return 'no' !== get_option( self::$setting_id_proration, 'no' );
} }
/** /**
@@ -137,7 +192,8 @@ class WC_Subscriptions_Synchroniser {
*/ */
public static function add_settings( $settings ) { public static function add_settings( $settings ) {
// Get the index of the index of the // Get the index of the setting.
$index = 0;
foreach ( $settings as $i => $setting ) { foreach ( $settings as $i => $setting ) {
if ( 'title' == $setting['type'] && 'woocommerce_subscriptions_miscellaneous' == $setting['id'] ) { if ( 'title' == $setting['type'] && 'woocommerce_subscriptions_miscellaneous' == $setting['id'] ) {
$index = $i; $index = $i;
@@ -164,18 +220,28 @@ class WC_Subscriptions_Synchroniser {
), ),
array( array(
'name' => __( 'Prorate First Payment', 'woocommerce-subscriptions' ), 'name' => __( 'Prorate First Renewal', 'woocommerce-subscriptions' ),
'desc' => __( 'If a subscription is synchronised to a specific day of the week, month or year, charge a prorated amount for the subscription at the time of sign up.', 'woocommerce-subscriptions' ), 'desc' => __( 'If a subscription is synchronised to a specific day of the week, month or year, charge a prorated amount for the subscription at the time of sign up.', 'woocommerce-subscriptions' ),
'id' => self::$setting_id_proration, 'id' => self::$setting_id_proration,
'css' => 'min-width:150px;', 'css' => 'min-width:150px;',
'default' => 'no', 'default' => 'no',
'type' => 'select', 'type' => 'select',
'options' => array( 'options' => array(
'no' => _x( 'Never', 'when to allow a setting', 'woocommerce-subscriptions' ), 'no' => _x( 'Never (do not charge any recurring amount)', 'when to prorate first payment / subscription length', 'woocommerce-subscriptions' ),
'virtual' => _x( 'For Virtual Subscription Products Only', 'when to prorate first payment / subscription length', 'woocommerce-subscriptions' ), 'recurring' => _x( 'Never (charge the full recurring amount at sign-up)', 'when to prorate first payment / subscription length', 'woocommerce-subscriptions' ),
'yes' => _x( 'For All Subscription Products', 'when to prorate first payment / subscription length', 'woocommerce-subscriptions' ), 'virtual' => _x( 'For Virtual Subscription Products Only', 'when to prorate first payment / subscription length', 'woocommerce-subscriptions' ),
'yes' => _x( 'For All Subscription Products', 'when to prorate first payment / subscription length', 'woocommerce-subscriptions' ),
), ),
'desc_tip' => true, 'desc_tip' => true,
),
array(
'name' => __( 'Sign-up grace period', 'woocommerce-subscriptions' ),
'desc' => _x( 'days prior to Renewal Day', "there's a number immediately in front of this text", 'woocommerce-subscriptions' ),
'id' => self::$setting_id_days_no_fee,
'default' => 0,
'type' => 'number',
'desc_tip' => __( 'Subscriptions created within this many days prior to the Renewal Day will not be charged at sign-up. Set to zero for all new Subscriptions to be charged the full recurring amount. Must be a positive number.', 'woocommerce-subscriptions' ),
), ),
array( 'type' => 'sectionend', 'id' => self::$setting_id . '_title' ), array( 'type' => 'sectionend', 'id' => self::$setting_id . '_title' ),
@@ -414,9 +480,12 @@ class WC_Subscriptions_Synchroniser {
* at the time of sign-up but prorated to the sync day. * at the time of sign-up but prorated to the sync day.
* *
* @since 1.5.10 * @since 1.5.10
*
* @param WC_Product $product
*
* @return bool
*/ */
public static function is_product_prorated( $product ) { public static function is_product_prorated( $product ) {
if ( false === self::is_sync_proration_enabled() || false === self::is_product_synced( $product ) ) { if ( false === self::is_sync_proration_enabled() || false === self::is_product_synced( $product ) ) {
$is_product_prorated = false; $is_product_prorated = false;
} elseif ( 'yes' == get_option( self::$setting_id_proration, 'no' ) && 0 == WC_Subscriptions_Product::get_trial_length( $product ) ) { } elseif ( 'yes' == get_option( self::$setting_id_proration, 'no' ) && 0 == WC_Subscriptions_Product::get_trial_length( $product ) ) {
@@ -430,6 +499,66 @@ class WC_Subscriptions_Synchroniser {
return $is_product_prorated; return $is_product_prorated;
} }
/**
* Determine whether the payment for a subscription should be the full price upfront.
*
* This method is particularly concerned with synchronized subscriptions. It will only return
* true when the following conditions are met:
*
* - There is no free trial
* - The subscription is synchronized
* - The store owner has determined that new subscribers need to pay for their subscription upfront.
*
* Additionally, if the store owner sets a number of days prior to the synchronization day that do not
* require an upfront payment, this method will check to see whether the current date falls within that
* period for the given product.
*
* @author Jeremy Pry
*
* @param WC_Product $product The product to check.
*
* @return bool Whether an upfront payment is required for the product.
*/
public static function is_payment_upfront( $product ) {
static $results = array();
$is_upfront = null;
if ( array_key_exists( $product->get_id(), $results ) ) {
return $results[ $product->get_id() ];
}
// Normal cases where we aren't concerned with an upfront payment.
if (
0 !== WC_Subscriptions_Product::get_trial_length( $product ) ||
! self::is_product_synced( $product ) ||
'recurring' !== get_option( self::$setting_id_proration, 'no' )
) {
$is_upfront = false;
}
// Maybe account for number of days without a fee.
if ( null === $is_upfront ) {
$no_fee_days = get_option( self::$setting_id_days_no_fee );
if ( $no_fee_days > 0 ) {
$payment_date = self::calculate_first_payment_date( $product, 'timestamp' );
$buffer_date = $payment_date - ( $no_fee_days * DAY_IN_SECONDS );
$is_upfront = wcs_strtotime_dark_knight( 'now' ) < $buffer_date;
} else {
$is_upfront = true;
}
}
/**
* Filter whether payment is upfront for a given product.
*
* @param bool $is_upfront Whether the product needs to be paid upfront.
* @param WC_Product $product The current product.
*/
$results[ $product->get_id() ] = apply_filters( 'woocommerce_subscriptions_payment_upfront', $is_upfront, $product );
return $results[ $product->get_id() ];
}
/** /**
* Get the day of the week, month or year on which a subscription's payments should be * Get the day of the week, month or year on which a subscription's payments should be
* synchronised to. * synchronised to.
@@ -708,7 +837,12 @@ class WC_Subscriptions_Synchroniser {
public static function maybe_set_free_trial( $total = '' ) { public static function maybe_set_free_trial( $total = '' ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( self::is_product_synced( $cart_item['data'] ) && ! self::is_product_prorated( $cart_item['data'] ) && ! self::is_today( self::calculate_first_payment_date( $cart_item['data'], 'timestamp' ) ) ) { if (
self::is_product_synced( $cart_item['data'] ) &&
! self::is_payment_upfront( $cart_item['data'] ) &&
! self::is_product_prorated( $cart_item['data'] ) &&
! self::is_today( self::calculate_first_payment_date( $cart_item['data'], 'timestamp' ) )
) {
$current_trial_length = WC_Subscriptions_Product::get_trial_length( WC()->cart->cart_contents[ $cart_item_key ]['data'] ); $current_trial_length = WC_Subscriptions_Product::get_trial_length( WC()->cart->cart_contents[ $cart_item_key ]['data'] );
$new_trial_length = ( $current_trial_length > 1 ) ? $current_trial_length : 1; $new_trial_length = ( $current_trial_length > 1 ) ? $current_trial_length : 1;
wcs_set_objects_property( WC()->cart->cart_contents[ $cart_item_key ]['data'], 'subscription_trial_length', $new_trial_length, 'set_prop_only' ); wcs_set_objects_property( WC()->cart->cart_contents[ $cart_item_key ]['data'], 'subscription_trial_length', $new_trial_length, 'set_prop_only' );
@@ -851,6 +985,11 @@ class WC_Subscriptions_Synchroniser {
* Removes the "set_subscription_prices_for_calculation" filter from the WC Product's woocommerce_get_price hook once * Removes the "set_subscription_prices_for_calculation" filter from the WC Product's woocommerce_get_price hook once
* *
* @since 1.5.10 * @since 1.5.10
*
* @param int $price The current price.
* @param WC_Product $product The product object.
*
* @return int
*/ */
public static function set_prorated_price_for_calculation( $price, $product ) { public static function set_prorated_price_for_calculation( $price, $product ) {
@@ -1052,6 +1191,40 @@ class WC_Subscriptions_Synchroniser {
} }
} }
/**
* Store a synced product's signup fee on the line item on the subscription and order.
*
* When calculating prorated sign up fees during switches it's necessary to get the sign-up fee paid.
* For synced product purchases we cannot rely on the order line item price as that might include a prorated recurring price or no recurring price all.
*
* Attached to WC 3.0+ hooks and uses WC 3.0 methods.
*
* @param WC_Order_Item_Product $item The order item object.
* @param string $cart_item_key The hash used to identify the item in the cart
* @param array $cart_item The cart item's data.
* @since 2.3.0
*/
public static function maybe_add_line_item_meta( $item, $cart_item_key, $cart_item ) {
if ( self::is_product_synced( $cart_item['data'] ) && ! self::is_today( self::calculate_first_payment_date( $cart_item['data'], 'timestamp' ) ) ) {
$item->add_meta_data( '_synced_sign_up_fee', WC_Subscriptions_Product::get_sign_up_fee( $cart_item['data'] ) );
}
}
/**
* Store a synced product's signup fee on the line item on the subscription and order.
*
* This function is a pre WooCommerce 3.0 version of @see WC_Subscriptions_Synchroniser::maybe_add_line_item_meta()
*
* @param int $item_id The order item ID.
* @param array $cart_item The cart item's data.
* @since 2.3.0
*/
public static function maybe_add_order_item_meta( $item_id, $cart_item ) {
if ( self::is_product_synced( $cart_item['data'] ) && ! self::is_today( self::calculate_first_payment_date( $cart_item['data'], 'timestamp' ) ) ) {
wc_update_order_item_meta( $item_id, '_synced_sign_up_fee', WC_Subscriptions_Product::get_sign_up_fee( $cart_item['data'] ) );
}
}
/* Deprecated Functions */ /* Deprecated Functions */
/** /**

View File

@@ -1,189 +0,0 @@
<?php
/**
* Subscription Cache Manager Class using TLC transients
*
* Implements methods to deal with the soft caching layer
*
* @class WCS_Cache_Manager_TLC
* @version 2.0
* @package WooCommerce Subscriptions/Classes
* @category Class
* @author Gabor Javorszky
*/
class WCS_Cache_Manager_TLC extends WCS_Cache_Manager {
public $logger = null;
public function __construct() {
_deprecated_function( __METHOD__, '2.1.2' );
add_action( 'woocommerce_loaded', array( $this, 'load_logger' ) );
// Add filters for update / delete / trash post to purge cache
add_action( 'trashed_post', array( $this, 'purge_delete' ), 9999 ); // trashed posts aren't included in 'any' queries
add_action( 'untrashed_post', array( $this, 'purge_delete' ), 9999 ); // however untrashed posts are
add_action( 'deleted_post', array( $this, 'purge_delete' ), 9999 ); // if forced delete is enabled
add_action( 'updated_post_meta', array( $this, 'purge_from_metadata' ), 9999, 4 ); // tied to _subscription_renewal
add_action( 'deleted_post_meta', array( $this, 'purge_from_metadata' ), 9999, 4 ); // tied to _subscription_renewal
add_action( 'added_post_meta', array( $this, 'purge_from_metadata' ), 9999, 4 ); // tied to _subscription_renewal
}
/**
* Attaches logger
*/
public function load_logger() {
_deprecated_function( __METHOD__, '2.1.2', 'WC_Subscriptions::$cache->' . __FUNCTION__ );
$this->logger = new WC_Logger();
}
/**
* Wrapper function around WC_Logger->log
*
* @param string $message Message to log
*/
public function log( $message ) {
_deprecated_function( __METHOD__, '2.1.2', 'WC_Subscriptions::$cache->' . __FUNCTION__ );
if ( defined( 'WCS_DEBUG' ) && WCS_DEBUG ) {
$this->logger->add( 'wcs-cache', $message );
}
}
/**
* Wrapper function around our cache library.
*
* @param string $key The key to cache the data with
* @param string|array $callback name of function, or array of class - method that fetches the data
* @param array $params arguments passed to $callback
* @param integer $expires number of seconds for how long to keep the cache. Don't set it to 0, as the cache will be autoloaded. Default is a week.
*
* @return bool|mixed
*/
public function cache_and_get( $key, $callback, $params = array(), $expires = WEEK_IN_SECONDS ) {
_deprecated_function( __METHOD__, '2.1.2', 'WC_Subscriptions::$cache->' . __FUNCTION__ );
$expires = absint( $expires );
$transient = tlc_transient( $key )
->updates_with( $callback, $params )
->expires_in( $expires );
return $transient->get();
}
/**
* Clearing for orders / subscriptions with sanitizing bits
*
* @param $post_id integer the ID of an order / subscription
*/
public function purge_subscription_cache_on_update( $post_id ) {
_deprecated_function( __METHOD__, '2.1.2', 'WC_Subscriptions::$cache->' . __FUNCTION__ );
$post_type = get_post_type( $post_id );
if ( 'shop_subscription' !== $post_type && 'shop_order' !== $post_type ) {
return;
}
if ( 'shop_subscription' === $post_type ) {
$this->log( 'ID is subscription, calling wcs_clear_related_order_cache for ' . $post_id );
$this->wcs_clear_related_order_cache( $post_id );
} else {
$this->log( 'ID is order, getting subscription.' );
$subscription = wcs_get_subscriptions_for_order( $post_id );
if ( empty( $subscription ) ) {
$this->log( 'No sub for this ID: ' . $post_id );
return;
}
$subscription = array_shift( $subscription );
$this->log( 'Got subscription, calling wcs_clear_related_order_cache for ' . $subscription->get_id() );
$this->wcs_clear_related_order_cache( $subscription->get_id() );
}
}
/**
* Clearing cache when a post is deleted
*
* @param $post_id integer the ID of a post
*/
public function purge_delete( $post_id ) {
_deprecated_function( __METHOD__, '2.1.2', 'WC_Subscriptions::$cache->' . __FUNCTION__ );
if ( 'shop_order' !== get_post_type( $post_id ) ) {
return;
}
$linked_subscription = get_post_meta( $post_id, '_subscription_renewal', false );
// don't call this if there's nothing to call on
if ( $linked_subscription ) {
$this->log( 'Calling purge from ' . current_filter() . ' on ' . $linked_subscription[0] );
$this->purge_subscription_cache_on_update( $linked_subscription[0] );
}
}
/**
* When the _subscription_renewal metadata is added / deleted / updated on the Order, we need to initiate cache invalidation for both the new
* value of the meta ($_meta_value), and the object it's being added to: $object_id.
*
* @param $meta_id integer the ID of the meta in the meta table
* @param $object_id integer the ID of the post we're updating on
* @param $meta_key string the meta_key in the table
* @param $_meta_value mixed the value we're deleting / adding / updating
*/
public function purge_from_metadata( $meta_id, $object_id, $meta_key, $_meta_value ) {
_deprecated_function( __METHOD__, '2.1.2', 'WC_Subscriptions::$cache->' . __FUNCTION__ );
if ( '_subscription_renewal' !== $meta_key || 'shop_order' !== get_post_type( $object_id ) ) {
return;
}
$this->log( 'Calling purge from ' . current_filter() . ' on object ' . $object_id . ' and meta value ' . $_meta_value . ' due to _subscription_renewal meta.' );
$this->purge_subscription_cache_on_update( $_meta_value );
$this->purge_subscription_cache_on_update( $object_id );
}
/**
* Wrapper function to clear cache that relates to related orders
*
* @param null $id
*/
public function wcs_clear_related_order_cache( $id = null ) {
_deprecated_function( __METHOD__, '2.1.2', 'WC_Subscriptions::$cache->' . __FUNCTION__ );
// if nothing was passed in, there's nothing to delete
if ( null === $id ) {
return;
}
// if it's not a Subscription, we don't deal with it
if ( is_object( $id ) && $id instanceof WC_Subscription ) {
$id = $id->get_id();
} elseif ( is_numeric( $id ) ) {
$id = absint( $id );
} else {
return;
}
$key = tlc_transient( 'wcs-related-orders-to-' . $id )->key;
$this->log( 'In the clearing, key being purged is this: ' . "\n\n{$key}\n\n" );
$this->delete_cached( $key );
}
/**
* Delete cached data with key
*
* @param string $key Key that needs deleting
*/
public function delete_cached( $key ) {
_deprecated_function( __METHOD__, '2.1.2', 'WC_Subscriptions::$cache->' . __FUNCTION__ );
if ( ! is_string( $key ) || empty( $key ) ) {
return;
}
// have to do this manually for now
delete_transient( 'tlc__' . $key );
delete_transient( 'tlc_up__' . $key );
}
}

View File

@@ -3,7 +3,8 @@
* Subscription Cached Data Manager Class * Subscription Cached Data Manager Class
* *
* @class WCS_Cached_Data_Manager * @class WCS_Cached_Data_Manager
* @version 2.1.2 * @version 2.3.0
* @since 2.1.2
* @package WooCommerce Subscriptions/Classes * @package WooCommerce Subscriptions/Classes
* @category Class * @category Class
* @author Prospress * @author Prospress
@@ -15,20 +16,8 @@ class WCS_Cached_Data_Manager extends WCS_Cache_Manager {
public function __construct() { public function __construct() {
add_action( 'woocommerce_loaded', array( $this, 'load_logger' ) ); add_action( 'woocommerce_loaded', array( $this, 'load_logger' ) );
// Add filters for update / delete / trash post to purge cache
add_action( 'trashed_post', array( $this, 'purge_delete' ), 9999 ); // trashed posts aren't included in 'any' queries
add_action( 'untrashed_post', array( $this, 'purge_delete' ), 9999 ); // however untrashed posts are
add_action( 'before_delete_post', array( $this, 'purge_delete' ), 9999 ); // if forced delete is enabled
add_action( 'update_post_meta', array( $this, 'purge_from_metadata' ), 9999, 4 );
add_action( 'updated_post_meta', array( $this, 'purge_from_metadata' ), 9999, 4 ); // tied to '_subscription_renewal', '_subscription_resubscribe' & '_subscription_switch' keys
add_action( 'deleted_post_meta', array( $this, 'purge_from_metadata' ), 9999, 4 ); // tied to '_subscription_renewal', '_subscription_resubscribe' & '_subscription_switch' keys
add_action( 'added_post_meta', array( $this, 'purge_from_metadata' ), 9999, 4 ); // tied to '_subscription_renewal', '_subscription_resubscribe' & '_subscription_switch' keys
add_action( 'admin_init', array( $this, 'initialize_cron_check_size' ) ); // setup cron task to truncate big logs. add_action( 'admin_init', array( $this, 'initialize_cron_check_size' ) ); // setup cron task to truncate big logs.
add_filter( 'cron_schedules', array( $this, 'add_weekly_cron_schedule' ) ); // create a weekly cron schedule add_filter( 'cron_schedules', array( $this, 'add_weekly_cron_schedule' ) ); // create a weekly cron schedule
// Add actions to handle cache purge for users.
add_action( 'save_post', array( $this, 'purge_delete' ), 9999, 2 );
} }
/** /**
@@ -79,15 +68,20 @@ class WCS_Cached_Data_Manager extends WCS_Cache_Manager {
* @param WP_Post $post The post object (on certain hooks). * @param WP_Post $post The post object (on certain hooks).
*/ */
public function purge_delete( $post_id, $post = null ) { public function purge_delete( $post_id, $post = null ) {
wcs_deprecated_function( __METHOD__, '2.3.0' );
$post_type = get_post_type( $post_id ); $post_type = get_post_type( $post_id );
if ( 'shop_order' === $post_type ) { if ( 'shop_order' === $post_type ) {
foreach ( wcs_get_subscriptions_for_order( $post_id, array( 'order_type' => 'renewal' ) ) as $subscription ) { wcs_deprecated_argument( __METHOD__, '2.3.0', sprintf( __( 'Related order caching is now handled by %1$s.', 'woocommerce-subscriptions' ), 'WCS_Related_Order_Store' ) );
$this->log( 'Calling purge delete on ' . current_filter() . ' for ' . $subscription->get_id() ); if ( is_callable( array( WCS_Related_Order_Store::instance(), 'delete_related_order_id_from_caches' ) ) ) {
$this->clear_related_order_cache( $subscription ); WCS_Related_Order_Store::instance()->delete_related_order_id_from_caches( $post_id );
} }
} }
if ( 'shop_subscription' === $post_type ) { if ( 'shop_subscription' === $post_type ) {
wcs_deprecated_argument( __METHOD__, '2.3.0', sprintf( __( 'Customer subscription caching is now handled by %1$s.', 'woocommerce-subscriptions' ), 'WCS_Customer_Store_Cached_CPT' ) );
// Purge wcs_do_subscriptions_exist cache, but only on the before_delete_post hook. // Purge wcs_do_subscriptions_exist cache, but only on the before_delete_post hook.
if ( doing_action( 'before_delete_post' ) ) { if ( doing_action( 'before_delete_post' ) ) {
$this->log( "Subscription {$post_id} deleted. Purging subscription cache." ); $this->log( "Subscription {$post_id} deleted. Purging subscription cache." );
@@ -106,49 +100,28 @@ class WCS_Cached_Data_Manager extends WCS_Cache_Manager {
* *
* @param $meta_id integer the ID of the meta in the meta table * @param $meta_id integer the ID of the meta in the meta table
* @param $object_id integer the ID of the post we're updating on, only concerned with order IDs * @param $object_id integer the ID of the post we're updating on, only concerned with order IDs
* @param $meta_key string the meta_key in the table, only concerned with '_subscription_renewal', '_subscription_resubscribe' & '_subscription_switch' keys * @param $meta_key string the meta_key in the table, only concerned with the '_customer_user' key
* @param $meta_value mixed the ID of the subscription that relates to the order * @param $meta_value mixed the ID of the subscription that relates to the order
*/ */
public function purge_from_metadata( $meta_id, $object_id, $meta_key, $meta_value ) { public function purge_from_metadata( $meta_id, $object_id, $meta_key, $meta_value ) {
static $combined_keys = null; wcs_deprecated_argument( __METHOD__, '2.3.0', sprintf( __( 'Customer subscription caching is now handled by %1$s and %2$s.', 'woocommerce-subscriptions' ), 'WCS_Customer_Store_Cached_CPT', 'WCS_Post_Meta_Cache_Manager' ) );
static $order_keys = array(
'_subscription_renewal' => 1,
'_subscription_resubscribe' => 1,
'_subscription_switch' => 1,
);
static $subscription_keys = array(
'_customer_user' => 1,
);
if ( null === $combined_keys ) {
$combined_keys = array_merge( $order_keys, $subscription_keys );
}
// Ensure we're handling a meta key we actually care about. // Ensure we're handling a meta key we actually care about.
if ( ! isset( $combined_keys[ $meta_key ] ) ) { if ( '_customer_user' !== $meta_key || 'shop_subscription' !== get_post_type( $object_id ) ) {
return; return;
} }
if ( 'shop_order' === get_post_type( $object_id ) && isset( $order_keys[ $meta_key ] ) ) { $this->purge_subscription_user_cache( $object_id );
$this->log( sprintf(
'Calling purge from %1$s on object %2$s and meta value %3$s due to %4$s meta key.',
current_filter(),
$object_id,
$meta_value,
$meta_key
) );
$this->clear_related_order_cache( $meta_value );
} elseif ( 'shop_subscription' === get_post_type( $object_id ) && isset( $subscription_keys[ $meta_key ] ) ) {
$this->purge_subscription_user_cache( $object_id );
}
} }
/** /**
* Wrapper function to clear the cache that relates to related orders * Wrapper function to clear the cache that relates to related orders
* *
* @param null $subscription_id * @param null $subscription_id
* @deprecated 2.3.0
*/ */
protected function clear_related_order_cache( $subscription_id ) { protected function clear_related_order_cache( $subscription_id ) {
wcs_deprecated_function( __METHOD__, '2.3.0', __( 'new related order methods in WCS_Related_Order_Store', 'woocommerce-subscriptions' ) );
// if it's not a Subscription, we don't deal with it // if it's not a Subscription, we don't deal with it
if ( is_object( $subscription_id ) && $subscription_id instanceof WC_Subscription ) { if ( is_object( $subscription_id ) && $subscription_id instanceof WC_Subscription ) {
@@ -159,6 +132,12 @@ class WCS_Cached_Data_Manager extends WCS_Cache_Manager {
return; return;
} }
// Clear the new cache, to honour the method call
if ( is_callable( array( WCS_Related_Order_Store::instance(), 'delete_caches_for_subscription' ) ) ) {
WCS_Related_Order_Store::instance()->delete_caches_for_subscription( $subscription_id );
}
// Clear the old cache, just in case it's still got data
$key = 'wcs-related-orders-to-' . $subscription_id; $key = 'wcs-related-orders-to-' . $subscription_id;
$this->log( 'In the clearing, key being purged is this: ' . print_r( $key, true ) ); $this->log( 'In the clearing, key being purged is this: ' . print_r( $key, true ) );
@@ -174,6 +153,8 @@ class WCS_Cached_Data_Manager extends WCS_Cache_Manager {
* @return bool * @return bool
*/ */
public function delete_cached( $key ) { public function delete_cached( $key ) {
wcs_deprecated_argument( __METHOD__, '2.3.0' );
if ( ! is_string( $key ) || empty( $key ) ) { if ( ! is_string( $key ) || empty( $key ) ) {
return false; return false;
} }
@@ -253,6 +234,8 @@ class WCS_Cached_Data_Manager extends WCS_Cache_Manager {
* @param int $subscription_id The subscription to purge. * @param int $subscription_id The subscription to purge.
*/ */
protected function purge_subscription_user_cache( $subscription_id ) { protected function purge_subscription_user_cache( $subscription_id ) {
wcs_deprecated_argument( __METHOD__, '2.3.0', sprintf( __( 'Customer subscription caching is now handled by %1$s and %2$s.', 'woocommerce-subscriptions' ), 'WCS_Customer_Store_Cached_CPT', 'WCS_Post_Meta_Cache_Manager' ) );
$subscription = wcs_get_subscription( $subscription_id ); $subscription = wcs_get_subscription( $subscription_id );
$subscription_user_id = $subscription->get_user_id(); $subscription_user_id = $subscription->get_user_id();
$this->log( sprintf( $this->log( sprintf(
@@ -262,45 +245,4 @@ class WCS_Cached_Data_Manager extends WCS_Cache_Manager {
) ); ) );
$this->delete_cached( "wcs_user_subscriptions_{$subscription_user_id}" ); $this->delete_cached( "wcs_user_subscriptions_{$subscription_user_id}" );
} }
/* Deprecated Functions */
/**
* Wrapper function to clear cache that relates to related orders
*
* @param null $subscription_id
*/
public function wcs_clear_related_order_cache( $subscription_id = null ) {
_deprecated_function( __METHOD__, '2.1.2', __CLASS__ . '::clear_related_order_cache( $subscription_id )' );
$this->clear_related_order_cache( $subscription_id );
}
/**
* Clearing for orders / subscriptions with sanitizing bits
*
* @param $post_id integer the ID of an order / subscription
*/
public function purge_subscription_cache_on_update( $post_id ) {
_deprecated_function( __METHOD__, '2.1.2', __CLASS__ . '::clear_related_order_cache( $subscription_id )' );
$post_type = get_post_type( $post_id );
if ( 'shop_subscription' === $post_type ) {
$this->clear_related_order_cache( $post_id );
} elseif ( 'shop_order' === $post_type ) {
$subscriptions = wcs_get_subscriptions_for_order( $post_id, array( 'order_type' => 'any' ) );
if ( empty( $subscriptions ) ) {
$this->log( 'No subscriptions for this ID: ' . $post_id );
} else {
foreach ( $subscriptions as $subscription ) {
$this->log( 'Got subscription, calling clear_related_order_cache for ' . $subscription->get_id() );
$this->clear_related_order_cache( $subscription );
}
}
}
}
} }

View File

@@ -22,6 +22,9 @@ class WCS_Cart_Initial_Payment extends WCS_Cart_Renewal {
public function __construct() { public function __construct() {
$this->setup_hooks(); $this->setup_hooks();
// When an order is paid for via checkout, ensure a new order isn't created due to mismatched cart hashes
add_filter( 'woocommerce_create_order', array( &$this, 'update_cart_hash' ), 10, 1 );
} }
/** /**

View File

@@ -39,7 +39,7 @@ class WCS_Cart_Renewal {
add_filter( 'woocommerce_default_order_status', array( &$this, 'maybe_preserve_order_status' ) ); add_filter( 'woocommerce_default_order_status', array( &$this, 'maybe_preserve_order_status' ) );
// When a failed/pending renewal order is paid for via checkout, ensure a new order isn't created due to mismatched cart hashes // When a failed/pending renewal order is paid for via checkout, ensure a new order isn't created due to mismatched cart hashes
add_filter( 'woocommerce_create_order', array( &$this, 'set_renewal_order_cart_hash' ), 10, 1 ); add_filter( 'woocommerce_create_order', array( &$this, 'update_cart_hash' ), 10, 1 );
// When a user is prevented from paying for a failed/pending renewal order because they aren't logged in, redirect them back after login // When a user is prevented from paying for a failed/pending renewal order because they aren't logged in, redirect them back after login
add_filter( 'woocommerce_login_redirect', array( &$this, 'maybe_redirect_after_login' ), 10 , 1 ); add_filter( 'woocommerce_login_redirect', array( &$this, 'maybe_redirect_after_login' ), 10 , 1 );
@@ -48,6 +48,9 @@ class WCS_Cart_Renewal {
add_action( 'woocommerce_checkout_order_processed', array( &$this, 'update_session_cart_after_updating_renewal_order' ), 10 ); add_action( 'woocommerce_checkout_order_processed', array( &$this, 'update_session_cart_after_updating_renewal_order' ), 10 );
add_filter( 'wc_dynamic_pricing_apply_cart_item_adjustment', array( &$this, 'prevent_compounding_dynamic_discounts' ), 10, 2 ); add_filter( 'wc_dynamic_pricing_apply_cart_item_adjustment', array( &$this, 'prevent_compounding_dynamic_discounts' ), 10, 2 );
// Remove non-recurring fees from renewal carts. Hooked in late (priority 1000), to ensure we handle all fees added by third-parties.
add_action( 'woocommerce_cart_calculate_fees', array( $this, 'remove_non_recurring_fees' ), 1000 );
} }
/** /**
@@ -326,7 +329,9 @@ class WCS_Cart_Renewal {
/** /**
* Check if a renewal order subscription has any coupons applied and if so add pseudo renewal coupon equivalents to ensure the discount is still applied * Check if a renewal order subscription has any coupons applied and if so add pseudo renewal coupon equivalents to ensure the discount is still applied
* *
* @param object $subscription subscription * @param WC_Subscription $subscription subscription
* @param WC_Order $order
*
* @since 2.0.10 * @since 2.0.10
*/ */
public function maybe_setup_discounts( $subscription, $order = null ) { public function maybe_setup_discounts( $subscription, $order = null ) {
@@ -1029,12 +1034,23 @@ class WCS_Cart_Renewal {
* *
* @param Mixed | An order generated by third party plugins * @param Mixed | An order generated by third party plugins
* @return Mixed | The unchanged order param * @return Mixed | The unchanged order param
* @since 2.1.0 * @since 2.2.11
*/ */
public function set_renewal_order_cart_hash( $order ) { public function update_cart_hash( $order ) {
if ( $item = wcs_cart_contains_renewal() ) { if ( $item = $this->cart_contains() ) {
$this->set_cart_hash( $item[ $this->cart_item_key ]['renewal_order_id'] );
if ( isset( $item[ $this->cart_item_key ]['renewal_order_id'] ) ) {
$order_id = $item[ $this->cart_item_key ]['renewal_order_id'];
} elseif ( isset( $item[ $this->cart_item_key ]['order_id'] ) ) {
$order_id = $item[ $this->cart_item_key ]['order_id'];
} else {
$order_id = '';
}
if ( $order_id ) {
$this->set_cart_hash( $order_id );
}
} }
return $order; return $order;
@@ -1257,6 +1273,37 @@ class WCS_Cart_Renewal {
} }
} }
/**
* Remove any fees applied to the renewal cart which aren't recurring.
*
* @param WC_Cart $cart A WooCommerce cart object.
*/
public function remove_non_recurring_fees( $cart ) {
if ( ! $this->cart_contains() ) {
return;
}
$cart_fees = $cart->get_fees();
// WC doesn't have a method for removing fees individually so we clear them and re-add them where applicable.
if ( is_callable( array( $cart, 'fees_api' ) ) ) { // WC 3.2 +
$cart->fees_api()->remove_all_fees();
} else {
$cart->fees = array();
}
foreach ( $cart_fees as $fee ) {
if ( true === apply_filters( 'woocommerce_subscriptions_is_recurring_fee', false, $fee, $cart ) ) {
if ( is_callable( array( $cart, 'fees_api' ) ) ) { // WC 3.2 +
$cart->fees_api()->add_fee( $fee );
} else {
$cart->add_fee( $fee->name, $fee->amount, $fee->taxable, $fee->tax_class );
}
}
}
}
/* Deprecated */ /* Deprecated */
/** /**
@@ -1321,5 +1368,19 @@ class WCS_Cart_Renewal {
_deprecated_function( __METHOD__, '2.2.1', __CLASS__ . '::add_line_item_meta( $order_item, $cart_item_key, $cart_item )' ); _deprecated_function( __METHOD__, '2.2.1', __CLASS__ . '::add_line_item_meta( $order_item, $cart_item_key, $cart_item )' );
$this->add_line_item_meta( $order_item, $cart_item_key, $cart_item ); $this->add_line_item_meta( $order_item, $cart_item_key, $cart_item );
} }
/**
* Right before WC processes a renewal cart through the checkout, set the cart hash.
* This ensures legitimate changes to taxes and shipping methods don't cause a new order to be created.
*
* @param Mixed | An order generated by third party plugins
* @return Mixed | The unchanged order param
* @since 2.1.0
*/
public function set_renewal_order_cart_hash( $order ) {
_deprecated_function( __METHOD__, '2.3', __CLASS__ . '::update_cart_hash( $order )' );
$this->update_cart_hash( $order );
return $order;
}
} }
new WCS_Cart_Renewal(); new WCS_Cart_Renewal();

View File

@@ -149,9 +149,9 @@ class WCS_Cart_Resubscribe extends WCS_Cart_Renewal {
$cart_item = $this->cart_contains( $recurring_cart ); $cart_item = $this->cart_contains( $recurring_cart );
if ( false !== $cart_item ) { if ( false !== $cart_item ) {
wcs_set_objects_property( $order, 'subscription_resubscribe', $cart_item[ $this->cart_item_key ]['subscription_id'] ); $old_subscription = wcs_get_subscription( $cart_item[ $this->cart_item_key ]['subscription_id'] );
$new_subscription->update_meta_data( '_subscription_resubscribe', $cart_item[ $this->cart_item_key ]['subscription_id'] ); WCS_Related_Order_Store::instance()->add_relation( $order, $old_subscription, 'resubscribe' );
$new_subscription->save(); WCS_Related_Order_Store::instance()->add_relation( $new_subscription, $old_subscription, 'resubscribe' );
} }
} }

View File

@@ -7,7 +7,7 @@
*/ */
class WCS_Cart_Switch extends WCS_Cart_Renewal { class WCS_Cart_Switch extends WCS_Cart_Renewal {
/* The flag used to indicate if a cart item is a renewal */ /* The flag used to indicate if a cart item is a subscription switch */
public $cart_item_key = 'subscription_switch'; public $cart_item_key = 'subscription_switch';
/** /**

View File

@@ -140,7 +140,7 @@ class WCS_Limiter {
if ( isset( $_GET['switch-subscription'] ) ) { if ( isset( $_GET['switch-subscription'] ) ) {
$is_purchasable = true; $is_purchasable = true;
//Validating when restring cart from session //Validating when restoring cart from session
} elseif ( WC_Subscriptions_Switcher::cart_contains_switches() ) { } elseif ( WC_Subscriptions_Switcher::cart_contains_switches() ) {
$is_purchasable = true; $is_purchasable = true;

View File

@@ -0,0 +1,31 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class for managing caches of post meta data that have a many-to-one relationship, meaning
* only one cache should exist for the meta value. This differs to WCS_Post_Meta_Cache_Manager
* which allows multiple caches for the same meta value i.e. a many-to-many relationship.
*
* @version 2.3.0
* @category Class
* @author Prospress
*/
class WCS_Post_Meta_Cache_Manager_Many_To_One extends WCS_Post_Meta_Cache_Manager {
/**
* When post meta is updated, check if this class instance cares about updating its cache
* to reflect the change. Always pass the previous value, to make sure that any existing
* relationships are also deleted because we know the data should not allow realtionships
* with multiple other values. e.g. a subscription can only belong to one customer.
*
* @param int $meta_id The ID of the post meta row in the database.
* @param int $post_id The post the meta is being changed on.
* @param string $meta_key The post meta key being changed.
* @param mixed $meta_value The value being deleted from the database.
*/
public function meta_updated( $meta_id, $post_id, $meta_key, $meta_value ) {
$this->meta_updated_with_previous( null, $post_id, $meta_key, $meta_value, get_post_meta( $post_id, $meta_key, true ) );
}
}

View File

@@ -0,0 +1,254 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class for managing caches of post meta
*
* @version 2.3.0
* @category Class
* @author Prospress
*/
class WCS_Post_Meta_Cache_Manager {
/** @var string The post type this cache manage acts on. */
protected $post_type;
/** @var array The post meta keys this cache manager should act on. */
protected $meta_keys;
/**
* Constructor
*
* @param string The post type this cache manage acts on.
* @param array The post meta keys this cache manager should act on.
*/
public function __construct( $post_type, $meta_keys ) {
$this->post_type = $post_type;
// We store the meta keys as the array keys to take advantage of the better query performance of isset() vs. in_array()
$this->meta_keys = array_flip( $meta_keys );
}
/**
* Attach callbacks to keep related order caches up-to-date.
*/
public function init() {
// When the post for a related order is deleted or untrashed, make sure the corresponding related order cache is updated
add_action( 'before_delete_post', array( $this, 'post_deleted' ) );
add_action( 'trashed_post', array( $this, 'post_deleted' ) );
add_action( 'untrashed_post', array( $this, 'post_untrashed' ) );
// When a related order post meta flag is modified, make sure the corresponding related order cache is updated
add_action( 'added_post_meta', array( $this, 'meta_added' ), 10, 4 );
add_action( 'update_post_meta', array( $this, 'meta_updated' ), 10, 4 );
add_action( 'deleted_post_meta', array( $this, 'meta_deleted' ), 10, 4 );
// Special handling for meta updates containing a previous order ID to make sure we also delete any previously linked relationship
add_action( 'update_post_metadata', array( $this, 'meta_updated_with_previous' ), 10, 5 );
// Special handling for meta deletion on all posts/orders, not a specific post/order ID
add_action( 'delete_post_metadata', array( $this, 'meta_deleted_all' ), 100, 5 );
}
/**
* Check if the post meta change is one to act on or ignore, based on the post type and meta key being changed.
*
* One gotcha here: the 'delete_post_metadata' hook can be triggered with a $post_id of null. This is done when
* meta is deleted by key (i.e. delete_post_meta_by_key()) or when meta is being deleted for a specific value for
* all posts (as done by wp_delete_attachment() to remove the attachment from posts). To handle these cases,
* we only check the post type when the $post_id is non-null.
*
* @param int $post_id The post the meta is being changed on.
* @param string $meta_key The post meta key being changed.
* @return bool False if the change should not be ignored, true otherwise.
*/
protected function is_change_to_ignore( $post_id, $meta_key = '' ) {
if ( ! is_null( $post_id ) && false === $this->is_managed_post_type( $post_id ) ) {
return true;
} elseif ( empty( $meta_key ) || ! isset( $this->meta_keys[ $meta_key ] ) ) {
return true;
} else {
return false;
}
}
/* Callbacks for post meta hooks */
/**
* When post meta is added, check if this class instance cares about updating its cache
* to reflect the change.
*
* @param int $meta_id The ID of the post meta row in the database.
* @param int $post_id The post the meta is being changed on.
* @param string $meta_key The post meta key being changed.
* @param mixed $meta_value The value being set in the database.
*/
public function meta_added( $meta_id, $post_id, $meta_key, $meta_value ) {
$this->maybe_trigger_update_cache_hook( 'add', $post_id, $meta_key, $meta_value );
}
/**
* When post meta is deleted, check if this class instance cares about updating its cache
* to reflect the change.
*
* @param int $meta_id The ID of the post meta row in the database.
* @param int $post_id The post the meta is being changed on.
* @param string $meta_key The post meta key being changed.
* @param mixed $meta_value The value being delete from the database.
*/
public function meta_deleted( $meta_id, $post_id, $meta_key, $meta_value ) {
$this->maybe_trigger_update_cache_hook( 'delete', $post_id, $meta_key, $meta_value );
}
/**
* When post meta is updated from a previous value, check if this class instance cares about
* updating its cache to reflect the change.
*
* @param mixed $check Whether to update the meta or not. By default, this is null, meaning it will be updated. Callbacks may override it to prevent that.
* @param int $post_id The post the meta is being changed on.
* @param string $meta_key The post meta key being changed.
* @param mixed $meta_value The new value being saved in the database.
* @param mixed $prev_value The previous value stored in the database.
* @return mixed $check This method is attached to the "update_{$meta_type}_metadata" filter, which is used as a pre-check on whether to update meta data, so it needs to return the $check value passed in.
*/
public function meta_updated_with_previous( $check, $post_id, $meta_key, $meta_value, $prev_value ) {
// If the meta data isn't actually being changed, we don't need to do anything. The use of == instead of === is deliberate to account for typecasting that can happen in WC's CRUD classes (e.g. ints cast as strings or bools as ints)
if ( $check || $prev_value == $meta_value ) {
return $check;
}
$this->maybe_trigger_update_cache_hook( 'update', $post_id, $meta_key, $meta_value, $prev_value );
return $check;
}
/**
* When post meta is updated, check if this class instance cares about updating its cache
* to reflect the change.
*
* @param int $meta_id The ID of the post meta row in the database.
* @param int $post_id The post the meta is being changed on.
* @param string $meta_key The post meta key being changed.
* @param mixed $meta_value The value being deleted from the database.
*/
public function meta_updated( $meta_id, $post_id, $meta_key, $meta_value ) {
$this->meta_updated_with_previous( null, $post_id, $meta_key, $meta_value, '' );
}
/**
* When all post meta rows for a given key are about to be deleted, check if this class instance
* cares about updating its cache to reflect the change.
*
* WordPress has special handling for meta deletion on all posts rather than a specific post ID.
* This method handles that case.
*
* @param mixed $check Whether to delete the meta or not. By default, this is null, meaning it will be deleted. Callbacks may override it to prevent that.
* @param int $post_id The post the meta is being changed on.
* @param string $meta_key The post meta key being changed.
* @param mixed $meta_value The value being deleted from the database.
* @param bool $delete_all Whether meta data is being deleted on all posts, not a specific post.
* @return mixed $check This method is attached to the "update_{$meta_type}_metadata" filter, which is used as a pre-check on whether to update meta data, so it needs to return the $check value passed in.
*/
public function meta_deleted_all( $check, $post_id, $meta_key, $meta_value, $delete_all ) {
if ( $delete_all && null === $check && false === $this->is_change_to_ignore( $post_id, $meta_key ) ) {
$this->trigger_delete_all_caches_hook( $meta_key );
}
return $check;
}
/* Callbacks for post hooks */
/**
* When a post object is restored from the trash, check if this class instance cares about updating its cache
* to reflect the change.
*
* @param int $post_id The post being restroed.
*/
public function post_untrashed( $post_id ) {
$this->maybe_update_for_post_change( 'add', $post_id );
}
/**
* When a post object is deleted or trashed, check if this class instance cares about updating its cache
* to reflect the change.
*
* @param int $post_id The post being restroed.
*/
public function post_deleted( $post_id ) {
$this->maybe_update_for_post_change( 'delete', $post_id );
}
/**
* When a post object is changed, check if this class instance cares about updating its cache
* to reflect the change.
*
* @param string $update_type The type of update to check. Only 'add' or 'delete' should be used.
* @param int $post_id The post being changed.
* @throws InvalidArgumentException If the given update type is not 'add' or 'delete'.
*/
protected function maybe_update_for_post_change( $update_type, $post_id ) {
if ( ! in_array( $update_type, array( 'add', 'delete' ) ) ) {
throw new InvalidArgumentException( sprintf( __( 'Invalid update type: %s. Post update types supported are "add" or "delete". Updates are done on post meta directly.', 'woocommerce-subscriptions' ), $update_type ) );
}
foreach ( $this->meta_keys as $meta_key => $value ) {
$meta_value = ( 'add' === $update_type ) ? get_post_meta( $post_id, $meta_key, true ) : '';
$this->maybe_trigger_update_cache_hook( $update_type, $post_id, $meta_key, $meta_value );
}
}
/**
* When post data is changed, check if this class instance cares about updating its cache
* to reflect the change.
*
* @param string $update_type The type of update to check. Only 'add' or 'delete' should be used.
* @param int $post_id The post the meta is being changed on.
* @param string $meta_key The post meta key being changed.
* @param mixed $meta_value The meta value.
* @param mixed $prev_value The previous value stored in the database. Optional.
*/
protected function maybe_trigger_update_cache_hook( $update_type, $post_id, $meta_key, $meta_value, $prev_value = '' ) {
if ( false === $this->is_change_to_ignore( $post_id, $meta_key ) ) {
$this->trigger_update_cache_hook( $update_type, $post_id, $meta_key, $meta_value, $prev_value );
}
}
/**
* Trigger a hook to allow 3rd party code to update its cache for data that it cares about.
*
* @param string $update_type The type of update to check. Only 'add' or 'delete' should be used.
* @param int $post_id The post the meta is being changed on.
* @param string $meta_key The post meta key being changed.
* @param mixed $meta_value The meta value.
* @param mixed $prev_value The previous value stored in the database. Optional.
*/
protected function trigger_update_cache_hook( $update_type, $post_id, $meta_key, $meta_value, $prev_value = '' ) {
do_action( 'wcs_update_post_meta_caches', $update_type, $post_id, $meta_key, $meta_value, $prev_value );
}
/**
* Trigger a hook to allow 3rd party code to delete its cache for data that it cares about.
*
* @param string $meta_key The post meta key being changed.
*/
protected function trigger_delete_all_caches_hook( $meta_key ) {
do_action( 'wcs_delete_all_post_meta_caches', $meta_key );
}
/**
* Abstract the check against get_post_type() so that it can be mocked for unit tests.
*
* @param int $post_id Post ID or post object.
* @return bool Whether the post type for the given post ID is the post type this instance manages.
*/
protected function is_managed_post_type( $post_id ) {
return $this->post_type === get_post_type( $post_id );
}
}

View File

@@ -18,6 +18,7 @@ class WCS_Query extends WC_Query {
add_action( 'parse_request', array( $this, 'parse_request' ), 0 ); add_action( 'parse_request', array( $this, 'parse_request' ), 0 );
add_filter( 'woocommerce_get_breadcrumb', array( $this, 'add_breadcrumb' ), 10 ); add_filter( 'woocommerce_get_breadcrumb', array( $this, 'add_breadcrumb' ), 10 );
add_action( 'pre_get_posts', array( $this, 'pre_get_posts' ), 11 ); add_action( 'pre_get_posts', array( $this, 'pre_get_posts' ), 11 );
add_filter( 'woocommerce_get_query_vars', array( $this, 'add_wcs_query_vars' ) );
// Inserting your new tab/page into the My Account page. // Inserting your new tab/page into the My Account page.
add_filter( 'woocommerce_account_menu_items', array( $this, 'add_menu_items' ) ); add_filter( 'woocommerce_account_menu_items', array( $this, 'add_menu_items' ) );
@@ -27,7 +28,12 @@ class WCS_Query extends WC_Query {
} }
$this->init_query_vars(); $this->init_query_vars();
add_filter( 'woocommerce_account_settings', array( $this, 'add_endpoint_account_settings' ) );
if ( WC_Subscriptions::is_woocommerce_pre( '3.4' ) ) {
add_filter( 'woocommerce_account_settings', array( $this, 'add_endpoint_account_settings' ) );
} else {
add_filter( 'woocommerce_get_settings_advanced', array( $this, 'add_endpoint_account_settings' ) );
}
} }
/** /**
@@ -117,7 +123,7 @@ class WCS_Query extends WC_Query {
* @return array * @return array
*/ */
public function add_menu_items( $menu_items ) { public function add_menu_items( $menu_items ) {
if ( 1 == count( wcs_get_users_subscriptions() ) ) { if ( 1 == count( wcs_get_users_subscriptions() ) && apply_filters( 'wcs_my_account_redirect_to_single_subscription', true ) ) {
$label = __( 'My Subscription', 'woocommerce-subscriptions' ); $label = __( 'My Subscription', 'woocommerce-subscriptions' );
} else { } else {
$label = __( 'Subscriptions', 'woocommerce-subscriptions' ); $label = __( 'Subscriptions', 'woocommerce-subscriptions' );
@@ -145,7 +151,7 @@ class WCS_Query extends WC_Query {
if ( 'subscriptions' == $endpoint && is_account_page() ) { if ( 'subscriptions' == $endpoint && is_account_page() ) {
$subscriptions = wcs_get_users_subscriptions(); $subscriptions = wcs_get_users_subscriptions();
if ( 1 == count( $subscriptions ) ) { if ( is_array( $subscriptions ) && 1 == count( $subscriptions ) && apply_filters( 'wcs_my_account_redirect_to_single_subscription', true ) ) {
$subscription = reset( $subscriptions ); $subscription = reset( $subscriptions );
$url = $subscription->get_view_order_url(); $url = $subscription->get_view_order_url();
} }
@@ -238,8 +244,6 @@ class WCS_Query extends WC_Query {
* @return mixed $account_settings * @return mixed $account_settings
*/ */
public function add_endpoint_account_settings( $settings ) { public function add_endpoint_account_settings( $settings ) {
$new_settings = array();
$order_endpoint_found = false;
$subscriptions_endpoint_setting = array( $subscriptions_endpoint_setting = array(
'title' => __( 'Subscriptions', 'woocommerce-subscriptions' ), 'title' => __( 'Subscriptions', 'woocommerce-subscriptions' ),
'desc' => __( 'Endpoint for the My Account &rarr; Subscriptions page', 'woocommerce-subscriptions' ), 'desc' => __( 'Endpoint for the My Account &rarr; Subscriptions page', 'woocommerce-subscriptions' ),
@@ -258,23 +262,9 @@ class WCS_Query extends WC_Query {
'desc_tip' => true, 'desc_tip' => true,
); );
// Loop over and look for View Order Endpoint and include Subscriptions endpoint options after that. WC_Subscriptions_Admin::insert_setting_after( $settings, 'woocommerce_myaccount_view_order_endpoint', array( $subscriptions_endpoint_setting, $view_subscription_endpoint_setting ), 'multiple_settings' );
foreach ( $settings as $value ) {
if ( 'woocommerce_myaccount_view_order_endpoint' === $value['id'] ) { return $settings;
$order_endpoint_found = true;
$new_settings[] = $value;
$new_settings[] = $subscriptions_endpoint_setting;
$new_settings[] = $view_subscription_endpoint_setting;
continue;
} elseif ( ! $order_endpoint_found && 'sectionend' === $value['type'] && 'account_endpoint_options' === $value['id'] ) {
// If we got to the end of the settings and didn't add our endpoints, add them to the end.
$new_settings[] = $subscriptions_endpoint_setting;
$new_settings[] = $view_subscription_endpoint_setting;
}
$new_settings[] = $value;
}
return $new_settings;
} }
/** /**
@@ -298,5 +288,17 @@ class WCS_Query extends WC_Query {
} }
return $url; return $url;
} }
/**
* Hooks into `woocommerce_get_query_vars` to make sure query vars defined in
* this class are also considered `WC_Query` query vars.
*
* @param array $query_vars
* @return array
* @since 2.3.0
*/
public function add_wcs_query_vars( $query_vars ) {
return array_merge( $query_vars, $this->query_vars );
}
} }
new WCS_Query(); new WCS_Query();

View File

@@ -100,9 +100,17 @@ class WCS_Select2 {
$html = "\n<!--select2 -->\n"; $html = "\n<!--select2 -->\n";
if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) { if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) {
$html .= '<input '; if ( isset( $this->attributes['class'] ) && $this->attributes['class'] === 'wc-enhanced-select' ) {
$html .= $this->attributes_to_html( $this->attributes ); $html .= '<select ';
$html .= '/>'; $html .= $this->attributes_to_html( $this->attributes );
$html .= '>';
$html .= '<option value=""></option>';
$html .= '</select>';
} else {
$html .= '<input ';
$html .= $this->attributes_to_html( $this->attributes );
$html .= '/>';
}
} else { } else {
$attributes = $this->attributes; $attributes = $this->attributes;
$selected_value = isset( $attributes['selected'] ) ? $attributes['selected'] : ''; $selected_value = isset( $attributes['selected'] ) ? $attributes['selected'] : '';

52
includes/class-wcs-staging.php Executable file
View File

@@ -0,0 +1,52 @@
<?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 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 ) {
$renewal_order->add_order_note( __( 'Payment processing skipped - renewal order created under staging site lock.', 'woocommerce-subscriptions' ) );
}
}
/**
* 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;
}
}

View File

@@ -0,0 +1,279 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Customer data store for subscriptions stored in Custom Post Types, with caching.
*
* Adds a persistent caching layer on top of WCS_Customer_Store_CPT for more
* performant queries to find a user's subscriptions.
*
* @version 2.3.0
* @category Class
* @author Prospress
*/
class WCS_Customer_Store_Cached_CPT extends WCS_Customer_Store_CPT implements WCS_Cache_Updater {
/**
* Keep cache up-to-date with changes to our meta data via WordPress post meta APIs
* by using a post meta cache manager.
*
* @var WCS_Post_Meta_Cache_Manager_Many_To_One
*/
protected $post_meta_cache_manager;
/**
* Meta key used to store all of a customer's subscription IDs in their user meta.
*
* @var string
*/
private $cache_meta_key = '_wcs_subscription_ids_cache';
/**
* Constructor
*/
public function __construct() {
$this->post_meta_cache_manager = new WCS_Post_Meta_Cache_Manager_Many_To_One( 'shop_subscription', array( $this->get_meta_key() ) );
}
/**
* Attach callbacks to keep user subscription caches up-to-date and provide debug tools for managing the cache.
*/
protected function init() {
$this->post_meta_cache_manager->init();
// When a user is first added, make sure the subscription cache is empty because it can not have any data yet, and we want to avoid running the query needlessly
add_filter( 'user_register', array( $this, 'set_empty_cache' ) );
// When the post for a subscription is change, make sure the corresponding cache is updated
add_action( 'wcs_update_post_meta_caches', array( $this, 'maybe_update_for_post_meta_change' ), 10, 5 );
add_action( 'wcs_delete_all_post_meta_caches', array( $this, 'maybe_delete_all_for_post_meta_change' ), 10, 1 );
WCS_Debug_Tool_Factory::add_cache_tool( 'generator', __( 'Generate Customer Subscription Cache', 'woocommerce-subscriptions' ), __( 'This will generate the persistent cache for linking users with subscriptions. The caches will be generated overtime in the background (via Action Scheduler).', 'woocommerce-subscriptions' ), self::instance() );
WCS_Debug_Tool_Factory::add_cache_tool( 'eraser', __( 'Delete Customer Subscription Cache', 'woocommerce-subscriptions' ), __( 'This will clear the persistent cache of all of subscriptions stored against users in your store. Expect slower performance of checkout, renewal and other subscription related functions after taking this action. The caches will be regenerated overtime as queries to find a given user\'s subscriptions are run.', 'woocommerce-subscriptions' ), self::instance() );
}
/* Public methods required by WCS_Customer_Store */
/**
* Get the IDs for a given user's subscriptions.
*
* Wrapper to support getting a user's subscription regardless of whether they are cached or not yet,
* either in the old transient cache, or new persistent cache.
*
* @param int $user_id The id of the user whose subscriptions you want.
* @return array
*/
public function get_users_subscription_ids( $user_id ) {
$subscription_ids = $this->get_users_subscription_ids_from_cache( $user_id );
// get user meta returns an empty string when no matching row is found for the given key, meaning it's not set yet
if ( '' === $subscription_ids ) {
$transient_key = "wcs_user_subscriptions_{$user_id}";
// We do this here rather than in get_users_subscription_ids_from_cache(), because we want to make sure the new persistent cache is updated too
$subscription_ids = wcs_get_transient_even_if_expired( $transient_key );
if ( false === $subscription_ids ) {
$subscription_ids = parent::get_users_subscription_ids( $user_id ); // no data in transient, query directly
} else {
rsort( $subscription_ids ); // the results from the database query are ordered by date/ID in DESC, so make sure the transient value is too
delete_transient( $transient_key ); // migrate the data to our new cache
}
$this->update_subscription_id_cache( $user_id, $subscription_ids );
}
return $subscription_ids;
}
/* Internal methods for managing the cache */
/**
* Find subscriptions for a given user from the cache.
*
* Applies the 'wcs_get_cached_users_subscription_ids' filter for backward compatibility with
* the now deprecated wcs_get_cached_user_subscription_ids() method.
*
* @param int $user_id The id of the user whose subscriptions you want.
* @return string|array An array of subscriptions in the cache, or an empty string when no matching row is found for the given key, meaning it's cache is not set yet or has been deleted
*/
protected function get_users_subscription_ids_from_cache( $user_id ) {
// Empty user IDs, like 0 or '', are never cached
$subscription_ids = empty( $user_id ) ? array() : get_user_meta( $user_id, $this->cache_meta_key, true );
return apply_filters( 'wcs_get_cached_users_subscription_ids', $subscription_ids, $user_id );
}
/**
* Add a subscription ID to the cached subscriptions for a given user.
*
* @param int $user_id The user the subscription belongs to.
* @param int $subscription_id A subscription to link the user in the cache.
*/
protected function add_subscription_id_to_cache( $user_id, $subscription_id ) {
$subscription_ids = $this->get_users_subscription_ids( $user_id );
if ( ! in_array( $subscription_id, $subscription_ids ) ) {
$subscription_ids[] = $subscription_id;
$this->update_subscription_id_cache( $user_id, $subscription_ids );
}
}
/**
* Delete a subscription ID from the cached IDs for a given user.
*
* @param int $user_id The user the subscription belongs to.
* @param int $subscription_id A subscription to link the user in the cache.
*/
protected function delete_subscription_id_from_cache( $user_id, $subscription_id ) {
$subscription_ids = $this->get_users_subscription_ids( $user_id );
if ( ( $index = array_search( $subscription_id, $subscription_ids ) ) !== false ) {
unset( $subscription_ids[ $index ] );
$this->update_subscription_id_cache( $user_id, $subscription_ids );
}
}
/**
* Helper function for setting subscription cache.
*
* @param int $user_id The id of the user who the subscriptions belongs to.
* @param array $subscription_ids Set of subscriptions to link with the given user.
* @return bool|int Returns meta ID if the key didn't exist; true on successful update; false on failure or if $subscription_ids is the same as the existing meta value in the database.
*/
protected function update_subscription_id_cache( $user_id, array $subscription_ids ) {
// Never cache empty user IDs, like 0 or ''
if ( empty( $user_id ) ) {
return false;
}
return update_user_meta( $user_id, $this->cache_meta_key, $subscription_ids );
}
/* Public methods used to bulk edit cache */
/**
* Clear all caches for all subscriptions against all users.
*/
public function delete_caches_for_all_users() {
delete_metadata( 'user', null, $this->cache_meta_key, null, true );
}
/* Public methods used as callbacks on hooks for managing cache */
/**
* Set empty subscription cache on a user.
*
* Newly registered users can't have subscriptions yet, so we set that cache to empty whenever a new user is added
* by attaching this to the 'user_register' hook.
*
* @param int $user_id The id of the user just created
*/
public function set_empty_cache( $user_id ) {
$this->update_subscription_id_cache( $user_id, array() );
}
/* Public methods attached to WCS_Post_Meta_Cache_Manager_Many_To_One hooks for managing the cache */
/**
* If there is a change to a subscription's post meta key, update the user meta cache.
*
* @param string $update_type The type of update to check. Can be 'add', 'update' or 'delete'.
* @param int $subscription_id The subscription's post ID where the customer is being changed.
* @param string $meta_key The post meta key being changed.
* @param mixed $user_id The meta value, which will be subscriber's user ID when $meta_key is '_customer_user'.
* @param mixed $old_user_id The previous value stored in the database for the subscription's '_customer_user'. Optional.
*/
public function maybe_update_for_post_meta_change( $update_type, $subscription_id, $meta_key, $user_id, $old_user_id = '' ) {
if ( $this->get_meta_key() !== $meta_key ) {
return;
}
switch ( $update_type ) {
case 'add' :
$this->add_subscription_id_to_cache( $user_id, $subscription_id );
break;
case 'delete' :
// If we don't have a specific user ID, the post is being deleted as WCS_Post_Meta_Cache_Manager_Many_To_One doesn't pass the associated meta value for that event, so find the corresponding user ID from post meta directly
if ( empty( $user_id ) ) {
$user_id = get_post_meta( $subscription_id, $this->get_meta_key(), true );
}
$this->delete_subscription_id_from_cache( $user_id, $subscription_id );
break;
case 'update' :
if ( ! empty( $old_user_id ) ) {
$this->delete_subscription_id_from_cache( $old_user_id, $subscription_id );
}
$this->add_subscription_id_to_cache( $user_id, $subscription_id );
break;
}
}
/**
* Remove all caches for a given meta key if all entries for that meta key are being deleted.
*
* This is very unlikely to ever happen, because it would be equivalent to deleting the linked
* customer on all orders and subscriptions. But it is handled here anyway in case of things
* like removing WooCommerce entirely.
*
* @param string $meta_key The post meta key being changed.
*/
public function maybe_delete_all_for_post_meta_change( $meta_key ) {
if ( $this->get_meta_key() === $meta_key ) {
$this->delete_caches_for_all_users();
}
}
/**
* Get the IDs of users without a cache set.
*
* @param int $number The number of users to return. Use -1 to return all users.
* @return array
*/
protected function get_user_ids_without_cache( $number = 10 ) {
return get_users( array(
'fields' => 'ids',
'number' => $number,
'meta_key' => $this->cache_meta_key,
'meta_compare' => 'NOT EXISTS',
) );
}
/** Methods to implement WCS_Cache_Updater - wrap more accurately named methods for the sake of clarity */
/**
* Get the items to be updated, if any.
*
* @return array An array of items to update, or empty array if there are no items to update.
*/
public function get_items_to_update() {
return $this->get_user_ids_without_cache();
}
/**
* Run the update for a single item.
*
* @param mixed $item The item to update.
*/
public function update_items_cache( $user_id ) {
// Getting the subscription IDs also sets the cache when it's not already set
$this->get_users_subscription_ids( $user_id );
}
/**
* Clear all caches.
*/
public function delete_all_caches() {
$this->delete_caches_for_all_users();
}}

View File

@@ -0,0 +1,66 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Customer data store for subscriptions stored in Custom Post Types.
*
* Gets subscriptions for users via the '_customer_user' post meta value.
*
* @version 2.3.0
* @category Class
* @author Prospress
*/
class WCS_Customer_Store_CPT extends WCS_Customer_Store {
/**
* The meta key used to link a customer with a subscription.
*
* @var string
*/
private $meta_key = '_customer_user';
/**
* Get the meta key used to link a customer with a subscription.
*
* @return string
*/
protected function get_meta_key() {
return $this->meta_key;
}
/**
* Get the IDs for a given user's subscriptions by querying post meta.
*
* @param int $user_id The id of the user whose subscriptions you want.
* @return array
*/
public function get_users_subscription_ids( $user_id ) {
if ( 0 === $user_id ) {
return array();
}
$query = new WP_Query();
return $query->query( array(
'post_type' => 'shop_subscription',
'posts_per_page' => -1,
'post_status' => 'any',
'orderby' => array(
'date' => 'DESC',
'ID' => 'DESC',
),
'fields' => 'ids',
'no_found_rows' => true,
'ignore_sticky_posts' => true,
'meta_query' => array(
array(
'key' => $this->get_meta_key(),
'value' => $user_id,
),
),
) );
}
}

View File

@@ -0,0 +1,38 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* WCS Variable Product Data Store: Stored in CPT.
*
* @version 2.3.0
* @author Prospress
*/
class WCS_Product_Variable_Data_Store_CPT extends WC_Product_Variable_Data_Store_CPT {
/**
* Method to read a product from the database.
*
* @param WC_Product_Variable_Subscription $product Product object.
* @throws Exception If invalid product.
*/
public function read( &$product ) {
parent::read( $product );
$this->read_min_max_variation_data( $product );
}
/**
* Read min and max variation data from post meta.
*
* @param WC_Product_Variable_Subscription $product Product object.
*/
protected function read_min_max_variation_data( &$product ) {
if ( ! $product->meta_exists( '_min_max_variation_ids_hash' ) ) {
$product->set_min_and_max_variation_data();
update_post_meta( $product->get_id(), '_min_max_variation_data', $product->get_meta( '_min_max_variation_data', true ), true );
update_post_meta( $product->get_id(), '_min_max_variation_ids_hash', $product->get_meta( '_min_max_variation_ids_hash', true ), true );
}
}
}

View File

@@ -0,0 +1,492 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Related order data store for orders and subscriptions stored in Custom Post Types, with caching.
*
* Adds a persistent caching layer on top of WCS_Related_Order_Store_CPT for more
* performant queries on related orders.
*
* @version 2.3.0
* @category Class
* @author Prospress
*/
class WCS_Related_Order_Store_Cached_CPT extends WCS_Related_Order_Store_CPT implements WCS_Cache_Updater {
/**
* Keep cache up-to-date with changes to our meta data via WordPress post meta APIs
* by using a post meta cache manager.
*
* @var WCS_Post_Meta_Cache_Manager
*/
protected $post_meta_cache_manager;
/**
* Store order relations using post meta keys as the array key for more performant searches
* in @see $this->get_relation_type_for_meta_key() than using array_search().
*
* @var array $relation_keys Post meta key => Order Relationship
*/
private $relation_keys;
/**
* Constructor
*/
public function __construct() {
parent::__construct();
foreach ( $this->get_meta_keys() as $relation_type => $meta_key ) {
$this->relation_keys[ $meta_key ] = $relation_type;
}
$this->post_meta_cache_manager = new WCS_Post_Meta_Cache_Manager( 'shop_order', $this->get_meta_keys() );
}
/**
* Attach callbacks to keep related order caches up-to-date and make sure
* the cache doesn't mess with other data stores.
*/
protected function init() {
$this->post_meta_cache_manager->init();
// Don't load cached related order meta data into subscriptions
add_filter( 'wcs_subscription_data_store_props_to_ignore', array( $this, 'add_related_order_cache_props' ), 10, 2 );
// When a subscription is first created, make sure its renewal order cache is empty because it can not have any renewals yet, and we want to avoid running the query needlessly
add_filter( 'wcs_created_subscription', array( $this, 'set_empty_renewal_order_cache' ), -1000 );
// When the post for a related order is deleted or untrashed, make sure the corresponding related order cache is updated
add_action( 'wcs_update_post_meta_caches', array( $this, 'maybe_update_for_post_meta_change' ), 10, 5 );
add_action( 'wcs_delete_all_post_meta_caches', array( $this, 'maybe_delete_all_for_post_meta_change' ), 10, 1 );
// When copying meta from a subscription to a renewal order, don't copy cache related order meta keys.
add_filter( 'wcs_renewal_order_meta', array( $this, 'remove_related_order_cache_keys' ), 10, 1 );
WCS_Debug_Tool_Factory::add_cache_tool( 'generator', __( 'Generate Related Order Cache', 'woocommerce-subscriptions' ), __( 'This will generate the persistent cache of all renewal, switch, resubscribe and other order types for all subscriptions in your store. The caches will be generated overtime in the background (via Action Scheduler).', 'woocommerce-subscriptions' ), self::instance() );
WCS_Debug_Tool_Factory::add_cache_tool( 'eraser', __( 'Delete Related Order Cache', 'woocommerce-subscriptions' ), __( 'This will clear the persistent cache of all renewal, switch, resubscribe and other order types for all subscriptions in your store. Expect slower performance of checkout, renewal and other subscription related functions after taking this action. The caches will be regenerated overtime as related order queries are run.', 'woocommerce-subscriptions' ), self::instance() );
}
/* Public methods required by WCS_Related_Order_Store */
/**
* Find orders related to a given subscription in a given way.
*
* Wrapper to support getting related orders regardless of whether they are cached or not yet,
* either in the old transient cache, or new persistent cache.
*
* @param WC_Order $subscription The ID of the subscription for which calling code wants the related orders.
* @param string $relation_type The relationship between the subscription and the orders. Must be 'renewal', 'switch' or 'resubscribe.
*
* @return array
*/
public function get_related_order_ids( WC_Order $subscription, $relation_type ) {
$subscription_id = wcs_get_objects_property( $subscription, 'id' ); // We can't rely on $subscription->get_id() being available because we only require a WC_Order, not a WC_Subscription, and WC_Order does not have get_id() available with WC < 3.0
$related_order_ids = $this->get_related_order_ids_from_cache( $subscription_id, $relation_type );
// get post meta returns an empty string when no matching row is found for the given key, meaning it's not set yet
if ( '' === $related_order_ids ) {
if ( 'renewal' === $relation_type ) {
$transient_key = "wcs-related-orders-to-{$subscription_id}"; // despite the name, this transient only stores renewal orders, not all related orders, so we can only use it for finding renewal orders
// We do this here rather than in get_related_order_ids_from_cache(), because we want to make sure the new persistent cache is updated too
$related_order_ids = wcs_get_transient_even_if_expired( $transient_key );
} else {
$related_order_ids = false;
}
if ( false === $related_order_ids ) {
$related_order_ids = parent::get_related_order_ids( $subscription, $relation_type ); // no data in transient, query directly
} else {
rsort( $related_order_ids ); // queries are ordered from newest ID to oldest, so make sure the transient value is too
delete_transient( $transient_key ); // we migrate the data to our new cache so want to remote this cache
}
$this->update_related_order_id_cache( $subscription_id, $related_order_ids, $relation_type );
}
return $related_order_ids;
}
/**
* Helper function for linking an order to a subscription via a given relationship.
*
* @param WC_Order $order The order to link with the subscription.
* @param WC_Order $subscription The order or subscription to link the order to.
* @param string $relation_type The relationship between the subscription and the order. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented.
*/
public function add_relation( WC_Order $order, WC_Order $subscription, $relation_type ) {
$this->add_related_order_id_to_cache( wcs_get_objects_property( $order, 'id' ), wcs_get_objects_property( $subscription, 'id' ), $relation_type );
parent::add_relation( $order, $subscription, $relation_type );
}
/**
* Remove the relationship between a given order and subscription.
*
* @param WC_Order $order An order that may be linked with subscriptions.
* @param WC_Order $subscription A subscription or order to unlink the order with, if a relation exists.
* @param string $relation_type The relationship between the subscription and the order. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented.
*/
public function delete_relation( WC_Order $order, WC_Order $subscription, $relation_type ) {
$this->delete_related_order_id_from_cache( wcs_get_objects_property( $order, 'id' ), wcs_get_objects_property( $subscription, 'id' ), $relation_type );
parent::delete_relation( $order, $subscription, $relation_type );
}
/**
* Remove all related orders/subscriptions of a given type from an order.
*
* @param WC_Order $order An order that may be linked with subscriptions.
* @param string $relation_type The relationship between the subscription and the order. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented.
*/
public function delete_relations( WC_Order $order, $relation_type ) {
$this->delete_related_order_id_from_caches( wcs_get_objects_property( $order, 'id' ), $relation_type );
parent::delete_relations( $order, $relation_type );
}
/* Internal methods for managing the cache */
/**
* Find orders related to a given subscription in a given way from the cache.
*
* @param int $subscription_id The ID of the subscription for which calling code wants the related orders.
* @param string $relation_type The relationship between the subscription and the orders. Must be 'renewal', 'switch' or 'resubscribe.
* @return string|array An array of related orders in the cache, or an empty string when no matching row is found for the given key, meaning it's cache is not set yet or has been deleted
*/
protected function get_related_order_ids_from_cache( $subscription_id, $relation_type ) {
return get_post_meta( $subscription_id, $this->get_cache_meta_key( $relation_type ), true );
}
/**
* Add a related order ID to the cached related order IDs for a given order relationship.
*
* @param int $order_id An order to link with the subscription.
* @param int $subscription_id A subscription to link the order to.
* @param string $relation_type The relationship between the subscription and the orders. Must be 'renewal', 'switch' or 'resubscribe.
*/
protected function add_related_order_id_to_cache( $order_id, $subscription_id, $relation_type ) {
$subscription = wcs_get_subscription( $subscription_id );
// If we can't get a valid subscription, we can't update its cache
if ( false === $subscription ) {
return;
}
$related_order_ids = $this->get_related_order_ids( $subscription, $relation_type );
if ( ! in_array( $order_id, $related_order_ids ) ) {
// Add the new order to the beginning of the array to preserve sort order from newest to oldest
array_unshift( $related_order_ids, $order_id );
$this->update_related_order_id_cache( $subscription_id, $related_order_ids, $relation_type );
}
}
/**
* Delete a related order ID from the cached related order IDs for a given order relationship.
*
* @param int $order_id The order that may be linked with subscriptions.
* @param int $subscription_id A subscription to remove a linked order from.
* @param string $relation_type The relationship between the subscription and the orders. Must be 'renewal', 'switch' or 'resubscribe.
*/
protected function delete_related_order_id_from_cache( $order_id, $subscription_id, $relation_type ) {
$subscription = wcs_get_subscription( $subscription_id );
// If we can't get a valid subscription, we can't udpate its cache
if ( false === $subscription ) {
return;
}
$related_order_ids = $this->get_related_order_ids( $subscription, $relation_type );
if ( ( $index = array_search( $order_id, $related_order_ids ) ) !== false ) {
unset( $related_order_ids[ $index ] );
$this->update_related_order_id_cache( $subscription_id, $related_order_ids, $relation_type );
}
}
/**
* Helper function for setting related order cache.
*
* @param int $subscription_id A subscription to update the linked order IDs for.
* @param array $related_order_ids Set of orders related to the given subscription.
* @param string $relation_type The relationship between the subscription and the order. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented.
* @return bool|int Returns related order cache's meta ID if it doesn't exist yet, otherwise returns true on success and false on failure. NOTE: If the $related_order_ids passed to this function are the same as those already in the database, this function returns false.
*/
protected function update_related_order_id_cache( $subscription_id, array $related_order_ids, $relation_type ) {
return update_post_meta( $subscription_id, $this->get_cache_meta_key( $relation_type ), $related_order_ids );
}
/**
* Get the meta key used to store the cache of linked order with a subscription, based on the type of relationship.
*
* @param string $relation_type The order's relationship with the subscription. Must be 'renewal', 'switch' or 'resubscribe'.
* @param string $prefix_meta_key Whether to add the underscore prefix to the meta key or not. 'prefix' to prefix the key. 'do_not_prefix' to not prefix the key.
* @return string
*/
protected function get_cache_meta_key( $relation_type, $prefix_meta_key = 'prefix' ) {
return sprintf( '%s_order_ids_cache', $this->get_meta_key( $relation_type, $prefix_meta_key ) );
}
/* Public methods used to bulk edit cache */
/**
* Clear related order caches for a given subscription.
*
* @param int $subscription_id The ID of a subscription that may have linked orders.
* @param string $relation_type The relationship between the subscription and the order. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented. Use 'any' to delete all cached.
*/
public function delete_caches_for_subscription( $subscription_id, $relation_type = 'any' ) {
foreach ( $this->get_relation_types() as $possible_relation_type ) {
if ( 'any' === $relation_type || $relation_type === $possible_relation_type ) {
delete_post_meta( $subscription_id, $this->get_cache_meta_key( $possible_relation_type ) );
}
}
}
/**
* Remove an order from all related order caches.
*
* @param int $order_id The order that may be linked with subscriptions.
* @param string $relation_type The relationship between the subscription and the order. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented. Use 'any' to delete all cached.
*/
public function delete_related_order_id_from_caches( $order_id, $relation_type = 'any' ) {
$relation_types = 'any' === $relation_type ? $this->get_relation_types() : array( $relation_type );
foreach ( wcs_get_subscriptions_for_order( $order_id, array( 'order_type' => $relation_types ) ) as $subscription_id => $subscription ) {
foreach ( $relation_types as $type ) {
$this->delete_related_order_id_from_cache( $order_id, $subscription_id, $type );
}
}
}
/**
* Clear all related order caches for all subscriptions.
*
* @param array $relation_types The relations to clear, or an empty array to clear all relations (default).
*/
public function delete_caches_for_all_subscriptions( $relation_types = array() ) {
if ( empty( $relation_types ) ) {
$relation_types = $this->get_relation_types();
}
// Set variables to workaround ambiguous parameters of delete_metadata()
$delete_all = true;
$null_post_id = $null_meta_value = null;
foreach ( $relation_types as $relation_type ) {
delete_metadata( 'post', $null_post_id, $this->get_cache_meta_key( $relation_type ), $null_meta_value, $delete_all );
}
}
/* Public methods used as callbacks on hooks for managing cache */
/**
* Add related order cache meta keys to a set of props for a subscription data store.
*
* Related order cache APIs need to be handled by querying a central data source directly, instead of using
* data set on an instance of the subscription, as it can be changed by other events outside of that instance's
* knowledge or access. For now, this is done via the database. That may be changed in future to use an object
* cache, but regardless, the prop should never be a source of that data. This method is attached to the filter
* 'wcs_subscription_data_store_props_to_ignore' so that cache keys are ignored.
*
* @param array $props_to_ignore A mapping of meta keys => prop names.
* @param WCS_Subscription_Data_Store_CPT $data_store
* @return array A mapping of meta keys => prop names, filtered by ones that should be updated.
*/
public function add_related_order_cache_props( $props_to_ignore, $data_store ) {
if ( is_a( $data_store, 'WCS_Subscription_Data_Store_CPT' ) ) {
foreach ( $this->get_meta_keys() as $relation_type => $meta_key ) {
$props_to_ignore[ $this->get_cache_meta_key( $relation_type ) ] = $this->get_cache_meta_key( $relation_type, 'do_not_prefix' );
}
}
return $props_to_ignore;
}
/**
* Set empty renewal order cache on a subscription.
*
* Newly created subscriptions can't have renewal orders yet, so we set that cache to empty whenever a new
* subscription is created. They can have switch or resubscribe orders, which may have been created before them on
* checkout, so we don't touch those caches.
*
* @param WC_Subscription $subscription A subscription to set empty renewal cache against.
* @return WC_Subscription Return the instance of the subscription, required as method is attached to the 'wcs_created_subscription' filter
*/
public function set_empty_renewal_order_cache( WC_Subscription $subscription ) {
$this->update_related_order_id_cache( $subscription->get_id(), array(), 'renewal' );
return $subscription;
}
/* Public methods attached to WCS_Post_Meta_Cache_Manager hooks for managing the cache */
/**
* If there is a change to a related order post meta key, update the cache.
*
* @param string $update_type The type of update to check. Can be 'add', 'update' or 'delete'.
* @param int $order_id The post the meta is being changed on.
* @param string $post_meta_key The post meta key being changed.
* @param mixed $subscription_id The related subscription's ID, as stored in meta value (only when the meta key is a related order meta key).
* @param mixed $old_subscription_id The previous value stored in the database for the related subscription. Optional.
*/
public function maybe_update_for_post_meta_change( $update_type, $order_id, $post_meta_key, $subscription_id, $old_subscription_id = '' ) {
$relation_type = $this->get_relation_type_for_meta_key( $post_meta_key );
if ( false === $relation_type ) {
return;
}
switch ( $update_type ) {
case 'add' :
$this->add_related_order_id_to_cache( $order_id, $subscription_id, $relation_type );
break;
case 'delete' :
// If we don't have a specific subscription ID, the order/post is being deleted, so clear it from all caches
if ( empty( $subscription_id ) ) {
$this->delete_related_order_id_from_caches( $order_id, $relation_type );
} else {
$this->delete_related_order_id_from_cache( $order_id, $subscription_id, $relation_type );
}
break;
case 'update' :
if ( ! empty( $old_subscription_id ) ) {
$this->delete_related_order_id_from_cache( $order_id, $old_subscription_id, $relation_type );
}
$this->add_related_order_id_to_cache( $order_id, $subscription_id, $relation_type );
break;
}
}
/**
* Remove all caches for a given meta key if all entries for that meta key are being deleted.
*
* @param string $post_meta_key The post meta key being changed.
*/
public function maybe_delete_all_for_post_meta_change( $post_meta_key ) {
$relation_type = $this->get_relation_type_for_meta_key( $post_meta_key );
if ( $relation_type ) {
$this->delete_caches_for_all_subscriptions( array( $relation_type ) );
}
}
/**
* Get the IDs of subscriptions without related order cache set for a give relation type or types.
*
* If more than one relation is specified, a batch of subscription IDs will be returned that are missing
* either of those relations, not both.
*
* @param array $relation_types The relations to check, or an empty array to check for any relation type (default).
* @param int $batch_size The number of subscriptions to return. Use -1 to return all subscriptions.
* @return array
*/
protected function get_subscription_ids_without_cache( $relation_types = array(), $batch_size = 10 ) {
global $wpdb;
if ( empty( $relation_types ) ) {
$relation_types = $this->get_relation_types();
}
$subscription_ids = array();
foreach ( $relation_types as $relation_type ) {
$limit = $batch_size - count( $subscription_ids );
// Use a subquery instead of a meta query with get_posts() as it's more performant than the multiple joins created by get_posts()
$post_ids = $wpdb->get_col( $wpdb->prepare(
"SELECT ID FROM $wpdb->posts
WHERE post_type = 'shop_subscription'
AND post_status NOT IN ('trash','auto-draft')
AND ID NOT IN (
SELECT post_id FROM $wpdb->postmeta
WHERE meta_key = %s
)
LIMIT 0, %d",
$this->get_cache_meta_key( $relation_type ),
$limit
) );
if ( $post_ids ) {
$subscription_ids += $post_ids;
if ( count( $subscription_ids ) >= $batch_size ) {
break;
}
}
}
return $subscription_ids;
}
/**
* Get the order relation for a given post meta key.
*
* @param string $meta_key The post meta key being changed.
* @return bool|string The order relation if it exists, or false if no such meta key exists.
*/
private function get_relation_type_for_meta_key( $meta_key ) {
return isset( $this->relation_keys[ $meta_key ] ) ? $this->relation_keys[ $meta_key ] : false;
}
/**
* Remove related order cache meta data from order meta copied from subscriptions to renewal orders.
*
* @param array $meta An order's meta data.
* @return array Filtered order meta data to be copied.
*/
public function remove_related_order_cache_keys( $meta ) {
$cache_meta_keys = array_map( array( $this, 'get_cache_meta_key' ), $this->get_relation_types() );
foreach ( $meta as $index => $meta_data ) {
if ( ! empty( $meta_data['meta_key'] ) && in_array( $meta_data['meta_key'], $cache_meta_keys ) ) {
unset( $meta[ $index ] );
}
}
return $meta;
}
/** Methods to implement WCS_Cache_Updater - wrap more accurately named methods for the sake of clarity */
/**
* Get the items to be updated, if any.
*
* @return array An array of items to update, or empty array if there are no items to update.
*/
public function get_items_to_update() {
return $this->get_subscription_ids_without_cache();
}
/**
* Run the update for a single item.
*
* @param mixed $item The item to update.
*/
public function update_items_cache( $subscription_id ) {
$subscription = wcs_get_subscription( $subscription_id );
if ( $subscription ) {
foreach ( $this->get_relation_types() as $relation_type ) {
// Getting the related IDs also sets the cache when it's not already set
$this->get_related_order_ids( $subscription, $relation_type );
}
}
}
/**
* Clear all caches.
*/
public function delete_all_caches() {
$this->delete_caches_for_all_subscriptions();
}
}

View File

@@ -0,0 +1,264 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Related order data store for orders stored in Custom Post Types.
*
* Importantly, this class uses WC_Data API methods, like WC_Data::add_meta_data() and WC_Data::get_meta(), to manage the
* relationships instead of add_post_meta() or get_post_meta(). This ensures that the relationship is stored, regardless
* of the order data store being used. However, it also creates potential for relationships to fall out of sync if a
* custom order data store is active, because @see $this->get_related_order_ids() queries the posts table via wp_posts(),
* not the order's data store. This is unavoidable as wc_get_orders() and WC_Order_Query do not provide any way to query
* meta data abstracted from the data store. Instead, it relies on 3rd party code to add custom parameter support for meta.
* Source: https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query#adding-custom-parameter-support
*
* Adding custom parameter support to order querying APIs won't help solve this issue, as the code would still directly
* query post meta by default, and require additional code for different order data stores.
*
* The solution will be to eventually move away from the use of meta data on the order to a standalone relationship table.
* This can be done already on sites running custom order data stores as WCS_Related_Order_Store::instance() is
* filterable. It will eventually also be the default implementation in a future version of Subscriptions.
*
* @version 2.3.0
* @category Class
* @author Prospress
*/
class WCS_Related_Order_Store_CPT extends WCS_Related_Order_Store {
/**
* Meta keys used to link an order with a subscription for each type of relationship.
*
* @since 2.3.0
* @var array $meta_keys Relationship => Meta key
*/
private $meta_keys;
/**
* Constructor: sets meta keys used for storing each order relation.
*/
public function __construct() {
foreach ( $this->get_relation_types() as $relation_type ) {
$this->meta_keys[ $relation_type ] = sprintf( '_subscription_%s', $relation_type );
}
}
/**
* Find orders related to a given subscription in a given way.
*
* This method uses the WordPress Posts API instead of the WooCommerce Order's API, because
* order's can not be queried by meta data with either wc_get_orders() or WC_Order_Query, so
* a custom query parameter would need to be added to WC_Order_Query to run that query, which
* is not something we want to add public APIs for because in future, that relationship will
* be moved out of order meta and into its own table and queries on it should come through
* here instead of the order querying API.
*
* @param WC_Order $subscription The ID of the subscription for which calling code wants the related orders.
* @param string $relation_type The relationship between the subscription and the orders. Must be 'renewal', 'switch' or 'resubscribe.
*
* @return array
*/
public function get_related_order_ids( WC_Order $subscription, $relation_type ) {
$related_order_ids = get_posts( array(
'posts_per_page' => -1,
'post_type' => 'shop_order',
'post_status' => 'any',
'fields' => 'ids',
'orderby' => array(
'date' => 'DESC',
'ID' => 'DESC',
),
'meta_query' => array(
array(
'key' => $this->get_meta_key( $relation_type ),
'compare' => '=',
'value' => wcs_get_objects_property( $subscription, 'id' ), // We can't rely on get_id() being available here, because we only require a WC_Order, not a WC_Subscription, and WC_Order does not have get_id() available with WC < 3.0
'type' => 'numeric',
),
),
'update_post_term_cache' => false,
) );
return $related_order_ids;
}
/**
* Find subscriptions related to a given order in a given way, if any.
*
* @param WC_Order $order The ID of an order that may be linked with subscriptions.
* @param string $relation_type The relationship between the subscription and the orders. Must be 'renewal', 'switch' or 'resubscribe.
*
* @return array
*/
public function get_related_subscription_ids( WC_Order $order, $relation_type ) {
$related_order_meta_key = $this->get_meta_key( $relation_type );
if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) {
$related_subscription_ids = get_post_meta( wcs_get_objects_property( $order, 'id' ), $related_order_meta_key, false );
} else {
$related_subscription_ids = $order->get_meta( $related_order_meta_key, false );
// Normalise the return value: WooCommerce returns a set of WC_Meta_Data objects, with values cast to strings, even if they're integers
$related_subscription_ids = wp_list_pluck( $related_subscription_ids, 'value' );
$related_subscription_ids = array_map( 'absint', $related_subscription_ids );
$related_subscription_ids = array_values( $related_subscription_ids );
}
$related_subscription_ids = $this->apply_deprecated_related_order_filter( $related_subscription_ids, $order, $relation_type );
return apply_filters( 'wcs_orders_related_subscription_ids', $related_subscription_ids, $order, $relation_type );
}
/**
* Apply the deprecated 'wcs_subscriptions_for_renewal_order' and 'wcs_subscriptions_for_resubscribe_order' filters
* to maintain backward compatibility.
*
* @param array $subscription_ids The IDs of subscription linked to the given order, if any.
* @param WC_Order $order An instance of an order that may be linked with subscriptions.
* @param string $relation_type The relationship between the subscription and the orders. Must be 'renewal', 'switch' or 'resubscribe'.
*
* @return array
*/
protected function apply_deprecated_related_order_filter( $subscription_ids, WC_Order $order, $relation_type ) {
$deprecated_filter_hook = "wcs_subscriptions_for_{$relation_type}_order";
if ( has_filter( $deprecated_filter_hook ) ) {
wcs_deprecated_function( sprintf( '"%s" hook should no longer be used and', esc_html( $deprecated_filter_hook ) ), '2.3.2', '"wcs_orders_related_subscription_ids" with a check on the 3rd param, to take advantage of the new persistent caching layer for related subscription IDs' );
$subscriptions = array();
foreach ( $subscription_ids as $subscription_id ) {
if ( wcs_is_subscription( $subscription_id ) ) {
$subscriptions[ $subscription_id ] = wcs_get_subscription( $subscription_id );
}
}
$filtered_subscriptions = apply_filters( $deprecated_filter_hook, $subscriptions, $order );
// Although this array was previously ordered by ID => instance, that key requirement wasn't enforced so it's possible 3rd party code was not using the ID as the key, and instead, numerical indexes are being used, so its safest not to rely on IDs as keys
if ( $filtered_subscriptions != $subscriptions ) {
$subscription_ids = array();
foreach ( $filtered_subscriptions as $subscription ) {
$subscription_ids[] = $subscription->get_id();
}
}
}
return $subscription_ids;
}
/**
* Helper function for linking an order to a subscription via a given relationship.
*
* Existing order relationships of the same type will not be overwritten. This only adds a relationship. To overwrite,
* you must also remove any existing relationship with @see $this->delete_relation().
*
* This data store links the relationship for a renewal order and a subscription in meta data against the order.
* That's inefficient for queries, so will be changed in future with a different data store. It also leads to potential
* bugs when WooCommerce 3.0 or newer is running with a custom data store for order data, as related orders are queried
* in $this->get_related_order_ids() using post meta directly, but set here using the CRUD WC_Data::add_meta_data() method.
* This is unfortunately unavoidable. See the WCS_Related_Order_Store_CPT docblock for more details.
*
* @param WC_Order $order The order to link with the subscription.
* @param WC_Order $subscription The order or subscription to link the order to.
* @param string $relation_type The relationship between the subscription and the order. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented.
*/
public function add_relation( WC_Order $order, WC_Order $subscription, $relation_type ) {
// We can't rely on $subscription->get_id() being available here, because we only require a WC_Order, not a WC_Subscription, and WC_Order does not have get_id() available with WC < 3.0
$subscription_id = wcs_get_objects_property( $subscription, 'id' );
$related_order_meta_key = $this->get_meta_key( $relation_type );
if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) {
$order_id = wcs_get_objects_property( $order, 'id' );
$existing_related_ids = get_post_meta( $order_id, $related_order_meta_key, false );
if ( empty( $existing_related_ids ) || ! in_array( $subscription_id, $existing_related_ids ) ) {
add_post_meta( $order_id, $related_order_meta_key, $subscription_id, false );
}
} else {
// We want to allow more than one piece of meta per key on the order, but we don't want to duplicate the same meta key => value combination, so we need to check if it is set first
$existing_relations = $order->get_meta( $related_order_meta_key, false );
$existing_related_ids = wp_list_pluck( $existing_relations, 'value' );
if ( empty( $existing_relations ) || ! in_array( $subscription_id, $existing_related_ids ) ) {
$order->add_meta_data( $related_order_meta_key, $subscription_id, false );
$order->save_meta_data();
}
}
}
/**
* Remove the relationship between a given order and subscription.
*
* This data store links the relationship for a renewal order and a subscription in meta data against the order.
* That's inefficient for queries, so will be changed in future with a different data store. It also leads to bugs
* with custom data stores for order data, as $this->get_related_order_ids() queries post meta directly. This is
* unavoidable. See the WCS_Related_Order_Store_CPT docblock for more details.
*
* @param WC_Order $order An order that may be linked with subscriptions.
* @param WC_Order $subscription A subscription or order to unlink the order with, if a relation exists.
* @param string $relation_type The relationship between the subscription and the order. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented.
*/
public function delete_relation( WC_Order $order, WC_Order $subscription, $relation_type ) {
$related_order_meta_key = $this->get_meta_key( $relation_type );
if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) {
delete_post_meta( wcs_get_objects_property( $order, 'id' ), $related_order_meta_key, wcs_get_objects_property( $subscription, 'id' ) );
} else {
foreach ( $order->get_meta_data() as $meta ) {
if ( $meta->key == $related_order_meta_key && $meta->value == wcs_get_objects_property( $subscription, 'id' ) ) { // we can't do strict comparison here, because WC_Meta_Data casts the subscription ID to be a string
$order->delete_meta_data_by_mid( $meta->id );
}
}
$order->save_meta_data();
}
}
/**
* Remove all related orders/subscriptions of a given type from an order.
*
* @param WC_Order $order An order that may be linked with subscriptions.
* @param string $relation_type The relationship between the subscription and the order. Must be 'renewal', 'switch' or 'resubscribe' unless custom relationships are implemented.
*/
public function delete_relations( WC_Order $order, $relation_type ) {
$related_order_meta_key = $this->get_meta_key( $relation_type );
if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) {
delete_post_meta( wcs_get_objects_property( $order, 'id' ), $related_order_meta_key, null );
} else {
$order->delete_meta_data( $related_order_meta_key );
$order->save_meta_data();
}
}
/**
* Get the meta keys used to link orders with subscriptions.
*
* @return array
*/
protected function get_meta_keys() {
return $this->meta_keys;
}
/**
* Get the meta key used to link an order with a subscription based on the type of relationship.
*
* @param string $relation_type The order's relationship with the subscription. Must be 'renewal', 'switch' or 'resubscribe'.
* @param string $prefix_meta_key Whether to add the underscore prefix to the meta key or not. 'prefix' to prefix the key. 'do_not_prefix' to not prefix the key.
* @return string
*/
protected function get_meta_key( $relation_type, $prefix_meta_key = 'prefix' ) {
$this->check_relation_type( $relation_type );
$meta_key = $this->meta_keys[ $relation_type ];
if ( 'do_not_prefix' === $prefix_meta_key ) {
$meta_key = wcs_maybe_unprefix_key( $meta_key );
}
return $meta_key;
}
}

View File

@@ -77,6 +77,29 @@ class WCS_Subscription_Data_Store_CPT extends WC_Order_Data_Store_CPT implements
do_action( 'woocommerce_new_subscription', $subscription->get_id() ); do_action( 'woocommerce_new_subscription', $subscription->get_id() );
} }
/**
* Returns an array of meta for an object.
*
* Ignore meta data that we don't want accessible on the object via meta APIs.
*
* @since 2.3.0
* @param WC_Data $object
* @return array
*/
public function read_meta( &$object ) {
$meta_data = parent::read_meta( $object );
$props_to_ignore = $this->get_props_to_ignore();
foreach ( $meta_data as $index => $meta_object ) {
if ( array_key_exists( $meta_object->meta_key, $props_to_ignore ) ) {
unset( $meta_data[ $index ] );
}
}
return $meta_data;
}
/** /**
* Read subscription data. * Read subscription data.
* *
@@ -331,6 +354,22 @@ class WCS_Subscription_Data_Store_CPT extends WC_Order_Data_Store_CPT implements
*/ */
protected function get_props_to_update( $object, $meta_key_to_props, $meta_type = 'post' ) { protected function get_props_to_update( $object, $meta_key_to_props, $meta_type = 'post' ) {
$props_to_update = parent::get_props_to_update( $object, $meta_key_to_props, $meta_type ); $props_to_update = parent::get_props_to_update( $object, $meta_key_to_props, $meta_type );
$props_to_ignore = $this->get_props_to_ignore();
foreach ( $props_to_ignore as $meta_key => $prop ) {
unset( $props_to_update[ $meta_key ] );
}
return $props_to_update;
}
/**
* Get the props set on a subscription which we don't want used on a subscription, which may be
* inherited order meta data, or other values using the post meta data store but not as props.
*
* @return array A mapping of meta keys => prop names
*/
protected function get_props_to_ignore() {
$props_to_ignore = array( $props_to_ignore = array(
'_transaction_id' => 'transaction_id', '_transaction_id' => 'transaction_id',
@@ -339,10 +378,67 @@ class WCS_Subscription_Data_Store_CPT extends WC_Order_Data_Store_CPT implements
'_cart_hash' => 'cart_hash', '_cart_hash' => 'cart_hash',
); );
foreach ( $props_to_ignore as $meta_key => $prop ) { return apply_filters( 'wcs_subscription_data_store_props_to_ignore', $props_to_ignore, $this );
unset( $props_to_update[ $meta_key ] ); }
/**
* Search subscription data for a term and returns subscription ids
*
* @param string $term Term to search
* @return array of subscription ids
* @since 2.3.0
*/
public function search_subscriptions( $term ) {
global $wpdb;
$subscription_ids = array();
$search_fields = array_map( 'wc_clean', apply_filters( 'woocommerce_shop_subscription_search_fields', array(
'_order_key',
'_billing_address_index',
'_shipping_address_index',
'_billing_email',
) ) );
if ( is_numeric( $term ) ) {
$subscription_ids[] = absint( $term );
} }
return $props_to_update; if ( ! empty( $search_fields ) ) {
$subscription_ids = array_unique( array_merge(
$wpdb->get_col(
$wpdb->prepare( "
SELECT DISTINCT p1.post_id
FROM {$wpdb->postmeta} p1
WHERE p1.meta_value LIKE '%%%s%%'", $wpdb->esc_like( wc_clean( $term ) ) ) . " AND p1.meta_key IN ('" . implode( "','", array_map( 'esc_sql', $search_fields ) ) . "')"
),
$wpdb->get_col(
$wpdb->prepare( "
SELECT order_id
FROM {$wpdb->prefix}woocommerce_order_items as order_items
WHERE order_item_name LIKE '%%%s%%'
",
$wpdb->esc_like( wc_clean( $term ) )
)
),
$wpdb->get_col(
$wpdb->prepare( "
SELECT p1.ID
FROM {$wpdb->posts} p1
INNER JOIN {$wpdb->postmeta} p2 ON p1.ID = p2.post_id
INNER JOIN {$wpdb->users} u ON p2.meta_value = u.ID
WHERE u.user_email LIKE '%%%s%%'
AND p2.meta_key = '_customer_user'
AND p1.post_type = 'shop_subscription'
",
esc_attr( $term )
)
),
$subscription_ids
) );
}
return apply_filters( 'woocommerce_shop_subscription_search_results', $subscription_ids, $term, $search_fields );
} }
} }

View File

@@ -0,0 +1,395 @@
<?php
/**
* Implement renewing a subscription early via the cart.
*
* @class WCS_Cart_Early_Renewal
* @package WooCommerce Subscriptions
* @subpackage WCS_Early_Renewal
* @category Class
* @since 2.3.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
class WCS_Cart_Early_Renewal extends WCS_Cart_Renewal {
/**
* Bootstraps the class and hooks required actions & filters.
*/
public function __construct() {
// Add the renew now button to the view subscription page.
add_filter( 'wcs_view_subscription_actions', array( $this, 'add_renew_now_action' ), 10, 2 );
// Check if a user is requesting to create an early renewal order for a subscription.
add_action( 'template_redirect', array( $this, 'maybe_setup_cart' ), 100 );
// Record early renewal payments.
if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) {
add_action( 'woocommerce_checkout_order_processed', array( $this, 'maybe_record_early_renewal' ), 100, 2 );
} else {
add_action( 'woocommerce_checkout_create_order', array( $this, 'add_early_renewal_metadata_to_order' ), 100, 2 );
}
// Process early renewal by making sure subscription's dates are updated.
add_action( 'subscriptions_activated_for_order', array( $this, 'maybe_update_dates' ) );
// Handle early renewal orders that are cancelled.
add_action( 'woocommerce_order_status_cancelled', array( $this, 'maybe_reactivate_subscription' ), 100, 2 );
// Add a subscription note to record early renewal order.
add_action( 'woocommerce_checkout_update_order_meta', array( $this, 'add_note_to_record_early_renewal' ) );
// After the renewal order is created on checkout, set the renewal order cart item data now that we have an order. Must be hooked on before WCS_Cart_Renewal->set_order_item_id(), in order for the line item ID set by that function to be correct.
add_action( 'woocommerce_checkout_update_order_meta', array( $this, 'set_cart_item_renewal_order_data' ), 5 );
// Allow customers to cancel early renewal orders from their my account page.
add_filter( 'woocommerce_my_account_my_orders_actions', array( $this, 'add_cancel_order_action' ), 15, 2 );
add_action( 'wp_loaded', array( $this, 'allow_early_renewal_order_cancellation' ), 10, 3 );
}
/**
* Adds a "Renew Now" button to the "View Subscription" page.
*
* @param array $actions The $subscription_key => $actions array with all actions that will be displayed for a subscription on the "View Subscription" page.
* @param WC_Subscription $subscription The current subscription being viewed.
* @since 2.3.0
* @return array $actions The subscription actions with the "Renew Now" action added if it's permitted.
*/
public function add_renew_now_action( $actions, $subscription ) {
if ( wcs_can_user_renew_early( $subscription ) && $subscription->payment_method_supports( 'subscription_date_changes' ) && $subscription->has_status( 'active' ) ) {
$actions['subscription_renewal_early'] = array(
'url' => wcs_get_early_renewal_url( $subscription ),
'name' => __( 'Renew Now', 'woocommerce-subscriptions' ),
);
}
return $actions;
}
/**
* Check if a payment is being made on an early renewal order.
*/
public function maybe_setup_cart() {
global $wp;
if ( ! isset( $_GET['subscription_renewal_early'], $_GET['wcs_nonce'] ) ) {
return;
}
$subscription = wcs_get_subscription( absint( $_GET['subscription_renewal_early'] ) );
$redirect_to = get_permalink( wc_get_page_id( 'myaccount' ) );
if ( false === wp_verify_nonce( $_GET['wcs_nonce'], 'wcs-renew-' . $subscription->get_id() ) ) {
wc_add_notice( __( 'There was an error with your request to renew. Please try again.', 'woocommerce-subscriptions' ), 'error' );
} elseif ( empty( $subscription ) ) {
wc_add_notice( __( 'That subscription does not exist. Has it been deleted?', 'woocommerce-subscriptions' ), 'error' );
} elseif ( ! current_user_can( 'subscribe_again', $subscription->get_id() ) ) {
wc_add_notice( __( "That doesn't appear to be one of your subscriptions.", 'woocommerce-subscriptions' ), 'error' );
} elseif ( ! wcs_can_user_renew_early( $subscription ) ) {
wc_add_notice( __( 'You can not renew this subscription early. Please contact us if you need assistance.', 'woocommerce-subscriptions' ), 'error' );
} else {
wc_add_notice( __( 'Complete checkout to renew now.', 'woocommerce-subscriptions' ), 'success' );
$this->setup_cart( $subscription, array(
'subscription_id' => $subscription->get_id(),
'subscription_renewal_early' => true,
'renewal_order_id' => $subscription->get_id(),
) );
$redirect_to = wc_get_checkout_url();
}
wp_safe_redirect( $redirect_to );
exit;
}
/**
* Records an early renewal against order created on checkout (only for WooCommerce < 3.0).
*
* @param int $order_id The post_id of a shop_order post/WC_Order object.
* @param array $posted_data The data posted on checkout.
* @since 2.3.0
*/
public function maybe_record_early_renewal( $order_id, $posted_data ) {
if ( ! WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) {
wcs_deprecated_function( __METHOD__, '2.0', 'WCS_Cart_Early_Renewal::add_early_renewal_metadata_to_order( $order, $posted_data )' );
}
$cart_item = $this->cart_contains();
if ( ! $cart_item ) {
return;
}
// Get the subscription.
$subscription = wcs_get_subscription( $cart_item[ $this->cart_item_key ]['subscription_id'] );
// Mark this order as a renewal.
update_post_meta( $order_id, '_subscription_renewal', $subscription->get_id() );
// Mark this order as an early renewal.
update_post_meta( $order_id, '_subscription_renewal_early', $subscription->get_id() );
// Put the subscription on hold until payment is complete.
$subscription->update_status( 'on-hold', _x( 'Customer requested to renew early:', 'used in order note as reason for why subscription status changed', 'woocommerce-subscriptions' ) );
}
/**
* Adds the early renewal metadata to the order created on checkout.
*
* @param WC_Order $order The WC Order object.
* @param array $data The data posted on checkout.
* @since 2.3.0
*/
public function add_early_renewal_metadata_to_order( $order, $data ) {
$cart_item = $this->cart_contains();
if ( ! $cart_item ) {
return;
}
// Get the subscription.
$subscription = wcs_get_subscription( $cart_item[ $this->cart_item_key ]['subscription_id'] );
// Mark this order as a renewal.
$order->update_meta_data( '_subscription_renewal', $subscription->get_id() );
// Mark this order as an early renewal.
$order->update_meta_data( '_subscription_renewal_early', $subscription->get_id() );
// Put the subscription on hold until payment is complete.
$subscription->update_status( 'on-hold', _x( 'Customer requested to renew early:', 'used in order note as reason for why subscription status changed', 'woocommerce-subscriptions' ) );
}
/**
* Update the next payment and end dates on a subscription to extend them and account
* for early renewal.
*
* @param int $order_id The WC Order ID which contains an early renewal.
* @since 2.3.0
*/
public function maybe_update_dates( $order_id ) {
$order = wc_get_order( $order_id );
if ( ! $order || ! wcs_order_contains_early_renewal( $order ) ) {
return;
}
$subscription_id = wcs_get_objects_property( $order, 'subscription_renewal_early' );
$subscription = wcs_get_subscription( $subscription_id );
if ( ! $subscription ) {
return;
}
$next_payment_time = $subscription->get_time( 'next_payment' );
$dates_to_update = array();
if ( $next_payment_time > 0 && $next_payment_time > current_time( 'timestamp', true ) ) {
$next_payment_timestamp = wcs_add_time( $subscription->get_billing_interval(), $subscription->get_billing_period(), $next_payment_time );
if ( $subscription->get_time( 'end' ) === 0 || $next_payment_timestamp < $subscription->get_time( 'end' ) ) {
$dates_to_update['next_payment'] = gmdate( 'Y-m-d H:i:s', $next_payment_timestamp );
} else {
// Delete the next payment date if the calculated next payment date occurs after the end date.
$dates_to_update['next_payment'] = 0;
}
} elseif ( $subscription->get_time( 'end' ) > 0 ) {
$dates_to_update['end'] = gmdate( 'Y-m-d H:i:s', wcs_add_time( $subscription->get_billing_interval(), $subscription->get_billing_period(), $subscription->get_time( 'end' ) ) );
}
if ( ! empty( $dates_to_update ) ) {
$order_number = sprintf( _x( '#%s', 'hash before order number', 'woocommerce-subscriptions' ), $order->get_order_number() );
$order_link = sprintf( '<a href="%s">%s</a>', esc_url( wcs_get_edit_post_link( $order->get_id() ) ), $order_number );
try {
$subscription->update_dates( $dates_to_update );
// translators: placeholder contains a link to the order's edit screen.
$subscription->add_order_note( sprintf( __( 'Customer successfully renewed early with order %s.', 'woocommerce-subscriptions' ), $order_link ) );
} catch ( Exception $e ) {
// translators: placeholder contains a link to the order's edit screen.
$subscription->add_order_note( sprintf( __( 'Failed to update subscription dates after customer renewed early with order %s.', 'woocommerce-subscriptions' ), $order_link ) );
}
}
}
/**
* Reactivates an on hold subscription when an early renewal order
* is cancelled by the user.
*
* @param int $order_id The WC Order ID which contains an early renewal.
* @since 2.3.0
*/
public function maybe_reactivate_subscription( $order_id ) {
// Get the order and make sure we have one.
$order = wc_get_order( $order_id );
if ( wcs_order_contains_early_renewal( $order ) ) {
// Get the subscription and make sure we have one.
$subscription = wcs_get_subscription( wcs_get_objects_property( $order, 'subscription_renewal_early' ) );
if ( ! $subscription || ! $subscription->has_status( 'on-hold' ) ) {
return;
}
// Make sure the next payment date isn't in the past.
if ( strtotime( $subscription->get_date( 'next_payment' ) ) < time() ) {
return;
}
// Reactivate the subscription.
$subscription->update_status( 'active' );
}
}
/**
* Checks the cart to see if it contains a subscription renewal item.
*
* @see wcs_cart_contains_early_renewal().
* @return bool|array The cart item containing the renewal, else false.
* @since 2.3.0
*/
protected function cart_contains() {
return wcs_cart_contains_early_renewal();
}
/**
* Get the subscription object used to construct the early renewal cart.
*
* @param array The resubscribe cart item.
* @return WC_Subscription The subscription object.
* @since 2.3.0
*/
protected function get_order( $cart_item = '' ) {
$subscription = false;
if ( empty( $cart_item ) ) {
$cart_item = $this->cart_contains();
}
if ( false !== $cart_item && isset( $cart_item[ $this->cart_item_key ] ) ) {
$subscription = wcs_get_subscription( $cart_item[ $this->cart_item_key ]['subscription_id'] );
}
return $subscription;
}
/**
* Add a note to the subscription to record the creation of the early renewal order.
*
* @param int $order_id The order ID created on checkout.
* @since 2.3.0
*/
public function add_note_to_record_early_renewal( $order_id ) {
$cart_item = $this->cart_contains();
if ( ! $cart_item ) {
return;
}
$order = wc_get_order( $order_id );
$subscription = wcs_get_subscription( $cart_item[ $this->cart_item_key ]['subscription_id'] );
if ( wcs_is_order( $order ) && wcs_is_subscription( $subscription ) ) {
$order_number = sprintf( _x( '#%s', 'hash before order number', 'woocommerce-subscriptions' ), $order->get_order_number() );
$subscription->add_order_note( sprintf( __( 'Order %s created to record early renewal.', 'woocommerce-subscriptions' ), sprintf( '<a href="%s">%s</a> ', esc_url( wcs_get_edit_post_link( $order_id ) ), $order_number ) ) );
}
}
/**
* Set the renewal order ID in early renewal order cart items.
*
* Hooked onto the 'woocommerce_checkout_update_order_meta' hook after the renewal order has been
* created on checkout. Required so the line item ID set by @see WCS_Cart_Renewal->set_order_item_id()
* matches the order.
*
* @param int $order_id The WC Order ID created on checkout.
* @since 2.3.0
*/
public function set_cart_item_renewal_order_data( $order_id ) {
if ( ! wcs_cart_contains_early_renewal() ) {
return;
}
foreach ( WC()->cart->cart_contents as $key => &$cart_item ) {
if ( isset( $cart_item[ $this->cart_item_key ] ) && ! empty( $cart_item[ $this->cart_item_key ]['subscription_renewal_early'] ) ) {
$cart_item[ $this->cart_item_key ]['renewal_order_id'] = $order_id;
}
}
}
/**
* Ensure customers can cancel early renewal orders.
*
* Renewal orders are usually not cancellable because @see WCS_Cart_Renewal::filter_my_account_my_orders_actions() prevents it.
* In the case of early renewals, the customer has opted for early renewal and so should be able to cancel it in order to reactivate their subscription.
*
* @param array $actions A list of actions customers can make on an order from their My Account page
* @param WC_Order $order The order the list of actions relate to.
* @return array $actions
* @since 2.3.0
*/
public static function add_cancel_order_action( $actions, $order ) {
if ( ! isset( $actions['cancel'] ) && wcs_order_contains_early_renewal( $order ) && in_array( $order->get_status(), apply_filters( 'woocommerce_valid_order_statuses_for_cancel', array( 'pending', 'failed' ), $order ) ) ) {
$redirect = wc_get_page_permalink( 'myaccount' );
// Redirect the customer back to the view subscription page if that is where they cancel the order from.
if ( wcs_is_view_subscription_page() ) {
global $wp;
$subscription = wcs_get_subscription( $wp->query_vars['view-subscription'] );
if ( wcs_is_subscription( $subscription ) ) {
$redirect = $subscription->get_view_order_url();
}
}
$actions['cancel'] = array(
'url' => $order->get_cancel_order_url( $redirect ),
'name' => __( 'Cancel', 'woocommerce-subscriptions' ),
);
}
return $actions;
}
/**
* Allow customers to cancel early renewal orders from their account page.
*
* Renewal orders are usually not cancellable because @see WC_Subscriptions_Renewal_Order::prevent_cancelling_renewal_orders() prevents the request from being processed.
* In the case of early renewals, the customer has opted for early renewal and so should be able to cancel it in order to reactivate their subscription.
*
* @since 2.3.0
*/
public static function allow_early_renewal_order_cancellation() {
if ( isset( $_GET['cancel_order'] ) && isset( $_GET['order_id'] ) && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], 'woocommerce-cancel_order' ) ) {
$order_id = absint( $_GET['order_id'] );
$order = wc_get_order( $order_id );
if ( wcs_order_contains_early_renewal( $order ) ) {
remove_action( 'wp_loaded', 'WC_Subscriptions_Renewal_Order::prevent_cancelling_renewal_orders', 19 );
}
}
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* Subscription Early Renewal Manager Class
*
* @package WooCommerce Subscriptions
* @subpackage WCS_Early_Renewal
* @category Class
* @since 2.3.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
class WCS_Early_Renewal_Manager {
/**
* The early renewal enabled setting ID.
*
* @var string
*/
protected static $setting_id;
/**
* Initialize filters and hooks for class.
*
* @since 2.3.0
*/
public static function init() {
self::$setting_id = WC_Subscriptions_Admin::$option_prefix . '_enable_early_renewal';
add_filter( 'woocommerce_subscription_settings', array( __CLASS__, 'add_settings' ) );
}
/**
* Add a setting to enable/disable the early renewal feature.
*
* @since 2.3.0
* @param array Settings array.
* @return array
*/
public static function add_settings( $settings ) {
WC_Subscriptions_Admin::insert_setting_after( $settings, 'woocommerce_subscriptions_turn_off_automatic_payments', array(
'id' => self::$setting_id,
'name' => __( 'Early Renewal', 'woocommerce-subscriptions' ),
'desc' => __( 'Accept Early Renewal Payments', 'woocommerce-subscriptions' ),
'desc_tip' => __( 'With early renewals enabled, customers can renew their subscriptions before the next payment date.', 'woocommerce-subscriptions' ),
'default' => 'no',
'type' => 'checkbox',
) );
return $settings;
}
/**
* A helper function to check if the early renewal feature is enabled or not.
*
* If the setting hasn't been set yet, by default it is off for existing stores and on for new stores.
*
* @since 2.3.0
* @return bool
*/
public static function is_early_renewal_enabled() {
$enabled = get_option( self::$setting_id );
if ( false === $enabled ) {
$enabled = wcs_do_subscriptions_exist() ? 'no' : 'yes';
update_option( self::$setting_id, $enabled );
}
return apply_filters( 'wcs_is_early_renewal_enabled', 'yes' === $enabled );
}
}

View File

@@ -0,0 +1,141 @@
<?php
/**
* WooCommerce Subscriptions Early Renewal functions.
*
* @author Prospress
* @category Core
* @package WooCommerce Subscriptions/Functions
* @since 2.3.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
/**
* Checks the cart to see if it contains an early subscription renewal.
*
* @return bool|array The cart item containing the early renewal, else false.
* @since 2.3.0
*/
function wcs_cart_contains_early_renewal() {
$cart_item = wcs_cart_contains_renewal();
if ( $cart_item && ! empty( $cart_item['subscription_renewal']['subscription_renewal_early'] ) ) {
return $cart_item;
}
return false;
}
/**
* Checks if a user can renew an active subscription early.
*
* @param int|WC_Subscription $subscription Post ID of a 'shop_subscription' post, or instance of a WC_Subscription object.
* @param int $user_id The ID of a user.
* @since 2.3.0
* @return bool Whether the user can renew a subscription early.
*/
function wcs_can_user_renew_early( $subscription, $user_id = 0 ) {
if ( ! is_object( $subscription ) ) {
$subscription = wcs_get_subscription( $subscription );
}
if ( empty( $user_id ) ) {
$user_id = get_current_user_id();
}
if ( ! $subscription ) {
$can_renew_early = false;
} elseif ( ! $subscription->has_status( array( 'active' ) ) ) {
$can_renew_early = false;
} elseif ( 0 === $subscription->get_total() ) {
$can_renew_early = false;
} elseif ( $subscription->get_time( 'trial_end' ) > gmdate( 'U' ) ) {
$can_renew_early = false;
} elseif ( ! $subscription->get_time( 'next_payment' ) ) {
$can_renew_early = false;
} elseif ( WC_Subscriptions_Synchroniser::subscription_contains_synced_product( $subscription ) ) {
$can_renew_early = false;
} elseif ( ! $subscription->payment_method_supports( 'subscription_date_changes' ) ) {
$can_renew_early = false;
} else {
// Make sure all line items still exist.
$all_line_items_exist = true;
foreach ( $subscription->get_items() as $line_item ) {
$product = wc_get_product( wcs_get_canonical_product_id( $line_item ) );
if ( false === $product ) {
$all_line_items_exist = false;
break;
}
}
$can_renew_early = $all_line_items_exist;
}
/**
* Allow third-parties to filter whether the customer can renew a subscription early.
*
* @since 2.3.0
* @param bool $can_renew_early Whether early renewal is permitted.
* @param WC_Subscription $subscription The subscription being renewed early.
* @param int $user_id The user's ID.
*/
return apply_filters( 'woocommerce_subscriptions_can_user_renew_early', $can_renew_early, $subscription, $user_id );
}
/**
* 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.
*
* @param int|WC_Subscription $subscription WC_Subscription ID, or instance of a WC_Subscription object.
* @return string The early renewal URL.
* @since 2.3.0
*/
function wcs_get_early_renewal_url( $subscription ) {
$subscription_id = is_a( $subscription, 'WC_Subscription' ) ? $subscription->get_id() : absint( $subscription );
$url = add_query_arg( array(
'subscription_renewal_early' => $subscription_id,
'subscription_renewal' => 'true',
'wcs_nonce' => wp_create_nonce( 'wcs-renew-' . $subscription_id ),
), get_permalink( wc_get_page_id( 'myaccount' ) ) );
/**
* Allow third-parties to filter the early renewal URL.
*
* @since 2.3.0
* @param string $url The early renewal URL.
* @param int $subscription_id The ID of the subscription to renew to.
*/
return apply_filters( 'woocommerce_subscriptions_get_early_renewal_url', $url, $subscription_id );
}

View File

@@ -73,7 +73,7 @@ class WC_Subscriptions_Payment_Gateways {
if ( WC_Subscriptions_Cart::cart_contains_subscription() || ( isset( $_GET['order_id'] ) && wcs_order_contains_subscription( $_GET['order_id'] ) ) ) { if ( WC_Subscriptions_Cart::cart_contains_subscription() || ( isset( $_GET['order_id'] ) && wcs_order_contains_subscription( $_GET['order_id'] ) ) ) {
$accept_manual_renewals = ( 'no' !== get_option( WC_Subscriptions_Admin::$option_prefix . '_accept_manual_renewals', 'no' ) ) ? true : false; $accept_manual_renewals = ( 'no' !== get_option( WC_Subscriptions_Admin::$option_prefix . '_accept_manual_renewals', 'no' ) ) ? true : false;
$subscriptions_in_cart = count( WC()->cart->recurring_carts ); $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 ) {

View File

@@ -0,0 +1,43 @@
<?php
/**
* WCS_Cache_Updater Interface
*
* Define methods that can be reliably used to update a cache on an object.
*
* @author Prospress
* @category Admin
* @package WooCommerce Subscriptions/Admin
* @version 2.3
* @since 2.3
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
} // Exit if accessed directly
/**
* WCS_Cache_Updater Interface
*
* Define a set of methods that can be used to update a cache
*/
interface WCS_Cache_Updater {
/**
* Get the items to be updated, if any.
*
* @return array An array of items to update, or empty array if there are no items to update.
*/
public function get_items_to_update();
/**
* Update for a single item, of the form returned by get_items_to_update().
*
* @param mixed $item The item to update.
*/
public function update_items_cache( $item );
/**
* Clear all caches for all items.
*/
public function delete_all_caches();
}

View File

@@ -133,7 +133,7 @@ class WC_Product_Variable_Subscription_Legacy extends WC_Product_Variable_Subscr
$children = array_keys( $this->prices_array[ $price_hash ]['price'] ); $children = array_keys( $this->prices_array[ $price_hash ]['price'] );
sort( $children ); sort( $children );
$min_max_data = wcs_get_min_max_variation_data( $this, $children ); $min_max_data = $this->get_min_and_max_variation_data( $children );
$min_variation_id = $min_max_data['min']['variation_id']; $min_variation_id = $min_max_data['min']['variation_id'];
$max_variation_id = $min_max_data['max']['variation_id']; $max_variation_id = $min_max_data['max']['variation_id'];
@@ -223,6 +223,8 @@ class WC_Product_Variable_Subscription_Legacy extends WC_Product_Variable_Subscr
$min_max_data = wcs_get_min_max_variation_data( $this, $child_variation_ids ); $min_max_data = wcs_get_min_max_variation_data( $this, $child_variation_ids );
$this->set_min_and_max_variation_data( $min_max_data, $child_variation_ids );
update_post_meta( $this->id, '_min_price_variation_id', $min_max_data['min']['variation_id'] ); update_post_meta( $this->id, '_min_price_variation_id', $min_max_data['min']['variation_id'] );
update_post_meta( $this->id, '_max_price_variation_id', $min_max_data['max']['variation_id'] ); update_post_meta( $this->id, '_max_price_variation_id', $min_max_data['max']['variation_id'] );
@@ -378,4 +380,56 @@ class WC_Product_Variable_Subscription_Legacy extends WC_Product_Variable_Subscr
public function get_default_attributes( $context = 'view' ) { public function get_default_attributes( $context = 'view' ) {
return $this->get_variation_default_attributes(); return $this->get_variation_default_attributes();
} }
/**
* Set the product's min and max variation data.
*
* @param array $min_and_max_data The min and max variation data returned by @see wcs_get_min_max_variation_data(). Optional.
* @param array $variation_ids The visible child variation IDs. Optional. By default this value be generated by @see WC_Product_Variable->get_children( true ).
* @since 2.3.0
*/
public function set_min_and_max_variation_data( $min_and_max_data = array(), $variation_ids = array() ) {
if ( empty( $variation_ids ) ) {
$variation_ids = $this->get_children( true );
}
if ( empty( $min_and_max_data ) ) {
$min_and_max_data = wcs_get_min_max_variation_data( $this, $variation_ids );
}
update_post_meta( $this->id, '_min_max_variation_data', $min_and_max_data, true );
update_post_meta( $this->id, '_min_max_variation_ids_hash', $this->get_variation_ids_hash( $variation_ids ), true );
}
/**
* Get the min and max variation data.
*
* This is a wrapper for @see wcs_get_min_max_variation_data() but to avoid calling
* that resource intensive function multiple times per request, check the value
* stored in meta or cached in memory before calling that function.
*
* @param array $variation_ids An array of variation IDs.
* @return array The variable product's min and max variation data.
* @since 2.3.0
*/
public function get_min_and_max_variation_data( $variation_ids ) {
$variation_ids_hash = $this->get_variation_ids_hash( $variation_ids );
// If this variable product has no min and max variation data, set it.
if ( ! metadata_exists( 'post', $this->id, '_min_max_variation_ids_hash' ) ) {
$this->set_min_and_max_variation_data();
}
if ( $variation_ids_hash === $this->get_meta( '_min_max_variation_ids_hash', true ) ) {
$min_and_max_variation_data = $this->get_meta( '_min_max_variation_data', true );
} elseif ( ! empty( $this->min_max_variation_data[ $variation_ids_hash ] ) ) {
$min_and_max_variation_data = $this->min_max_variation_data[ $variation_ids_hash ];
} else {
$min_and_max_variation_data = wcs_get_min_max_variation_data( $this, $variation_ids );
$this->min_max_variation_data[ $variation_ids_hash ] = $min_and_max_variation_data;
}
return $min_and_max_variation_data;
}
} }

View File

@@ -28,7 +28,7 @@ class WC_Subscription_Legacy extends WC_Subscription {
/** /**
* Initialize the subscription object. * Initialize the subscription object.
* *
* @param int|WC_Subscription $order * @param int|WC_Subscription $subscription
*/ */
public function __construct( $subscription ) { public function __construct( $subscription ) {
@@ -423,17 +423,25 @@ class WC_Subscription_Legacy extends WC_Subscription {
// Sign up is total amount paid for this item on original order when item has a free trial // Sign up is total amount paid for this item on original order when item has a free trial
$sign_up_fee = $original_order_item['line_total'] / $original_order_item['qty']; $sign_up_fee = $original_order_item['line_total'] / $original_order_item['qty'];
} elseif ( isset( $original_order_item['item_meta']['_synced_sign_up_fee'] ) ) {
$sign_up_fee = $original_order_item['item_meta']['_synced_sign_up_fee'] / $original_order_item['qty'];
} else { } else {
// Sign-up fee is any amount on top of recurring amount // Sign-up fee is any amount on top of recurring amount
$sign_up_fee = max( $original_order_item['line_total'] / $original_order_item['qty'] - $line_item['line_total'] / $line_item['qty'], 0 ); $sign_up_fee = max( $original_order_item['line_total'] / $original_order_item['qty'] - $line_item['line_total'] / $line_item['qty'], 0 );
} }
// If prices inc tax, ensure that the sign up fee amount includes the tax if ( ! empty( $original_order_item ) && ! empty( $sign_up_fee ) ) {
if ( 'inclusive_of_tax' === $tax_inclusive_or_exclusive && ! empty( $original_order_item ) && $this->get_prices_include_tax() ) { $sign_up_fee_proportion = $sign_up_fee / ( $original_order_item['line_total'] / $original_order_item['qty'] );
$proportion = $sign_up_fee / ( $original_order_item['line_total'] / $original_order_item['qty'] ); $sign_up_fee_tax = wc_round_tax_total( $original_order_item['line_tax'] * $sign_up_fee_proportion );
$sign_up_fee += round( $original_order_item['line_tax'] * $proportion, 2 );
// If prices don't inc tax, ensure that the sign up fee amount includes the tax.
if ( 'inclusive_of_tax' === $tax_inclusive_or_exclusive && ! $this->get_prices_include_tax() ) {
$sign_up_fee += $sign_up_fee_tax;
// If prices inc tax and the request is for prices exclusive of tax, remove the taxes.
} elseif ( 'inclusive_of_tax' !== $tax_inclusive_or_exclusive && $this->get_prices_include_tax() ) {
$sign_up_fee -= $sign_up_fee_tax;
}
} }
} }

View File

@@ -1,30 +1,47 @@
<?php <?php
/* /*
Plugin Name: Action Scheduler * Plugin Name: Action Scheduler
Plugin URI: https://github.com/prospress/action-scheduler * Plugin URI: https://github.com/prospress/action-scheduler
Description: A robust action scheduler for WordPress * Description: A robust scheduling library for use in WordPress plugins.
Author: Prospress * Author: Prospress
Author URI: http://prospress.com/ * Author URI: http://prospress.com/
Version: 1.5.3 * Version: 2.0.0
*/ * License: GPLv3
*
* Copyright 2018 Prospress, Inc. (email : freedoms@prospress.com)
*
* 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 <http://www.gnu.org/licenses/>.
*
*/
if ( ! function_exists( 'action_scheduler_register_1_dot_5_dot_3' ) ) { if ( ! function_exists( 'action_scheduler_register_2_dot_0_dot_0' ) ) {
if ( ! class_exists( 'ActionScheduler_Versions' ) ) { if ( ! class_exists( 'ActionScheduler_Versions' ) ) {
require_once( 'classes/ActionScheduler_Versions.php' ); require_once( 'classes/ActionScheduler_Versions.php' );
add_action( 'plugins_loaded', array( 'ActionScheduler_Versions', 'initialize_latest_version' ), 1, 0 ); add_action( 'plugins_loaded', array( 'ActionScheduler_Versions', 'initialize_latest_version' ), 1, 0 );
} }
add_action( 'plugins_loaded', 'action_scheduler_register_1_dot_5_dot_3', 0, 0 ); add_action( 'plugins_loaded', 'action_scheduler_register_2_dot_0_dot_0', 0, 0 );
function action_scheduler_register_1_dot_5_dot_3() { function action_scheduler_register_2_dot_0_dot_0() {
$versions = ActionScheduler_Versions::instance(); $versions = ActionScheduler_Versions::instance();
$versions->register( '1.5.3', 'action_scheduler_initialize_1_dot_5_dot_3' ); $versions->register( '2.0.0', 'action_scheduler_initialize_2_dot_0_dot_0' );
} }
function action_scheduler_initialize_1_dot_5_dot_3() { function action_scheduler_initialize_2_dot_0_dot_0() {
require_once( 'classes/ActionScheduler.php' ); require_once( 'classes/ActionScheduler.php' );
ActionScheduler::init( __FILE__ ); ActionScheduler::init( __FILE__ );
} }
} }

View File

@@ -78,7 +78,6 @@ abstract class ActionScheduler {
* *
* @static * @static
* @param string $plugin_file * @param string $plugin_file
* @return void
*/ */
public static function init( $plugin_file ) { public static function init( $plugin_file ) {
self::$plugin_file = $plugin_file; self::$plugin_file = $plugin_file;
@@ -97,6 +96,10 @@ abstract class ActionScheduler {
add_action( 'init', array( $admin_view, 'init' ), 0, 0 ); // run before $store::init() add_action( 'init', array( $admin_view, 'init' ), 0, 0 ); // run before $store::init()
require_once( self::plugin_path('functions.php') ); require_once( self::plugin_path('functions.php') );
if ( defined( 'WP_CLI' ) && WP_CLI ) {
WP_CLI::add_command( 'action-scheduler', 'ActionScheduler_WPCLI_Scheduler_command' );
}
} }
@@ -117,4 +120,3 @@ abstract class ActionScheduler {
return as_get_datetime_object( $when, $timezone ); return as_get_datetime_object( $when, $timezone );
} }
} }

View File

@@ -0,0 +1,656 @@
<?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 in translations
*/
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)
*/
protected function translate( $text, $context = '' ) {
return _x( $text, $context, $this->package );
}
/**
* 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 ] = $this->translate( $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" />' ),
array_map( array( $this, 'translate' ), $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 = wc_clean( $_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[] = '`' . $column . '` like "%' . $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( $this->translate( $label ) )
. '</option>';
}
echo '</select>';
}
submit_button( $this->translate( 'Filter' ), '', '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() ) {
echo '<span class="subtitle">' . esc_attr( $this->translate( sprintf( 'Search results for "%s"', $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>';
}
/**
* 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 $this->translate( 'Search' );
}
}

View File

@@ -0,0 +1,89 @@
<?php
/**
* Abstract class with common Queue Cleaner functionality.
*/
abstract class ActionScheduler_Abstract_QueueRunner {
/** @var ActionScheduler_QueueCleaner */
protected $cleaner;
/** @var ActionScheduler_FatalErrorMonitor */
protected $monitor;
/** @var ActionScheduler_Store */
protected $store;
/**
* 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->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.
*/
public function process_action( $action_id ) {
try {
do_action( 'action_scheduler_before_execute', $action_id );
$action = $this->store->fetch_action( $action_id );
$this->store->log_execution( $action_id );
$action->execute();
do_action( 'action_scheduler_after_execute', $action_id );
$this->store->mark_complete( $action_id );
} catch ( Exception $e ) {
$this->store->mark_failure( $action_id );
do_action( 'action_scheduler_failed_execution', $action_id, $e );
}
$this->schedule_next_instance( $action );
}
/**
* Schedule the next instance of the action if necessary.
*
* @param ActionScheduler_Action $action
*/
protected function schedule_next_instance( ActionScheduler_Action $action ) {
$schedule = $action->get_schedule();
$next = $schedule->next( as_get_datetime_object() );
if ( ! is_null( $next ) && $schedule->is_recurring() ) {
$this->store->save_action( $action, $next );
}
}
/**
* Run the queue cleaner.
*
* @author Jeremy Pry
*/
protected function run_cleanup() {
$this->cleaner->clean();
}
/**
* 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', 5 );
}
/**
* Process actions in the queue.
*
* @author Jeremy Pry
* @return int The number of actions processed.
*/
abstract public function run();
}

View File

@@ -24,7 +24,6 @@ class ActionScheduler_Action {
/** /**
* @param string $hook * @param string $hook
* @return void
*/ */
protected function set_hook( $hook ) { protected function set_hook( $hook ) {
$this->hook = $hook; $this->hook = $hook;
@@ -74,4 +73,3 @@ class ActionScheduler_Action {
return FALSE; return FALSE;
} }
} }

View File

@@ -4,6 +4,46 @@
* Class ActionScheduler_ActionFactory * Class ActionScheduler_ActionFactory
*/ */
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';
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 );
}
/** /**
* @param string $hook The hook to trigger when this action runs * @param string $hook The hook to trigger when this action runs
* @param array $args Args to pass when the hook is triggered * @param array $args Args to pass when the hook is triggered
@@ -12,7 +52,7 @@ class ActionScheduler_ActionFactory {
* *
* @return string The ID of the stored action * @return string The ID of the stored action
*/ */
public function single( $hook, $args = array(), $when = NULL, $group = '' ) { public function single( $hook, $args = array(), $when = null, $group = '' ) {
$date = as_get_datetime_object( $when ); $date = as_get_datetime_object( $when );
$schedule = new ActionScheduler_SimpleSchedule( $date ); $schedule = new ActionScheduler_SimpleSchedule( $date );
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group ); $action = new ActionScheduler_Action( $hook, $args, $schedule, $group );
@@ -28,7 +68,7 @@ class ActionScheduler_ActionFactory {
* *
* @return string The ID of the stored action * @return string The ID of the stored action
*/ */
public function recurring( $hook, $args = array(), $first = NULL, $interval = NULL, $group = '' ) { public function recurring( $hook, $args = array(), $first = null, $interval = null, $group = '' ) {
if ( empty($interval) ) { if ( empty($interval) ) {
return $this->single( $hook, $args, $first, $group ); return $this->single( $hook, $args, $first, $group );
} }
@@ -48,7 +88,7 @@ class ActionScheduler_ActionFactory {
* *
* @return string The ID of the stored action * @return string The ID of the stored action
*/ */
public function cron( $hook, $args = array(), $first = NULL, $schedule = NULL, $group = '' ) { public function cron( $hook, $args = array(), $first = null, $schedule = null, $group = '' ) {
if ( empty($schedule) ) { if ( empty($schedule) ) {
return $this->single( $hook, $args, $first, $group ); return $this->single( $hook, $args, $first, $group );
} }
@@ -69,4 +109,3 @@ class ActionScheduler_ActionFactory {
return $store->save_action( $action ); return $store->save_action( $action );
} }
} }

View File

@@ -4,12 +4,10 @@
* Class ActionScheduler_AdminView * Class ActionScheduler_AdminView
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
class ActionScheduler_AdminView { class ActionScheduler_AdminView extends ActionScheduler_AdminView_Deprecated {
private static $admin_view = NULL; private static $admin_view = NULL;
private static $admin_url;
/** /**
* @return ActionScheduler_QueueRunner * @return ActionScheduler_QueueRunner
* @codeCoverageIgnore * @codeCoverageIgnore
@@ -28,452 +26,53 @@ class ActionScheduler_AdminView {
* @codeCoverageIgnore * @codeCoverageIgnore
*/ */
public function init() { public function init() {
if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || false == DOING_AJAX ) ) { if ( is_admin() && ( ! defined( 'DOING_AJAX' ) || false == DOING_AJAX ) ) {
add_filter( 'action_scheduler_post_type_args', array( self::instance(), 'action_scheduler_post_type_args' ) );
}
self::$admin_url = admin_url( 'edit.php?post_type=' . ActionScheduler_wpPostStore::POST_TYPE ); if ( class_exists( 'WooCommerce' ) ) {
add_action( 'woocommerce_admin_status_content_action-scheduler', array( $this, 'render_admin_ui' ) );
add_filter( 'views_edit-' . ActionScheduler_wpPostStore::POST_TYPE, array( self::instance(), 'list_table_views' ) ); add_filter( 'woocommerce_admin_status_tabs', array( $this, 'register_system_status_tab' ) );
add_filter( 'bulk_actions-edit-' . ActionScheduler_wpPostStore::POST_TYPE, array( self::instance(), 'bulk_actions' ) );
add_filter( 'manage_' . ActionScheduler_wpPostStore::POST_TYPE . '_posts_columns', array( self::instance(), 'list_table_columns' ), 1 );
add_filter( 'manage_edit-' . ActionScheduler_wpPostStore::POST_TYPE . '_sortable_columns', array( self::instance(), 'list_table_sortable_columns' ) );
add_filter( 'manage_' . ActionScheduler_wpPostStore::POST_TYPE . '_posts_custom_column', array( self::instance(), 'list_table_column_content' ), 10, 2 );
add_filter( 'post_row_actions', array( self::instance(), 'row_actions' ), 10, 2 );
add_action( 'admin_init', array( self::instance(), 'maybe_execute_action' ), 20 );
add_action( 'admin_notices', array( self::instance(), 'admin_notices' ) );
add_filter( 'post_updated_messages', array( self::instance(), 'post_updated_messages' ) );
add_filter( 'posts_orderby', array( self::instance(), 'custom_orderby' ), 10, 2 );
add_filter( 'posts_search', array( self::instance(), 'search_post_password' ), 10, 2 );
}
public function action_scheduler_post_type_args( $args ) {
return array_merge( $args, array(
'show_ui' => true,
'show_in_menu' => 'tools.php',
'show_in_admin_bar' => false,
) );
}
/**
* Customise the post status related views displayed on the Scheduled Actions administration screen.
*
* @param array $views An associative array of views and view labels which can be used to filter the 'scheduled-action' posts displayed on the Scheduled Actions administration screen.
* @return array $views An associative array of views and view labels which can be used to filter the 'scheduled-action' posts displayed on the Scheduled Actions administration screen.
*/
public function list_table_views( $views ) {
foreach ( $views as $view_key => $view ) {
if ( 'publish' == $view_key ) {
$views[ $view_key ] = str_replace( __( 'Published', 'action-scheduler' ), __( 'Complete', 'action-scheduler' ), $view );
break;
} }
}
return $views; add_action( 'admin_menu', array( $this, 'register_menu' ) );
}
}
/**
* 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;
} }
/** /**
* Do not include the "Edit" action for the Scheduled Actions administration screen. * Include Action Scheduler's administration under the Tools menu.
* *
* Hooked to the 'bulk_actions-edit-action-scheduler' filter. * 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
* @param array $actions An associative array of actions which can be performed on the 'scheduled-action' post type. * System Status page, and for sites where WooCommerce isn't active.
* @return array $actions An associative array of actions which can be performed on the 'scheduled-action' post type.
*/ */
public function bulk_actions( $actions ) { public function register_menu() {
add_submenu_page(
if ( isset( $actions['edit'] ) ) { 'tools.php',
unset( $actions['edit'] ); __( 'Scheduled Actions', 'action-scheduler' ),
} __( 'Scheduled Actions', 'action-scheduler' ),
'manage_options',
return $actions; 'action-scheduler',
} array( $this, 'render_admin_ui' )
/**
* Completely customer the columns displayed on the Scheduled Actions administration screen.
*
* Because we can't filter the content of the default title and date columns, we need to recreate our own
* custom columns for displaying those post fields. For the column content, @see self::list_table_column_content().
*
* @param array $columns An associative array of columns that are use for the table on the Scheduled Actions administration screen.
* @return array $columns An associative array of columns that are use for the table on the Scheduled Actions administration screen.
*/
public function list_table_columns( $columns ) {
$custom_columns = array(
'cb' => $columns['cb'],
'hook' => __( 'Hook', 'action-scheduler' ), // because we want to customise the inline actions
'status' => __( 'Status', 'action-scheduler' ),
'args' => __( 'Arguments', 'action-scheduler' ),
'taxonomy-action-group' => __( 'Group', 'action-scheduler' ),
'recurrence' => __( 'Recurrence', 'action-scheduler' ),
'scheduled' => __( 'Scheduled Date', 'action-scheduler' ), // because we want to customise how the date is displayed
); );
if ( isset( $_REQUEST['post_status'] ) ) {
if ( in_array( $_REQUEST['post_status'], array( 'failed', 'in-progress' ) ) ) {
$custom_columns['modified'] = __( 'Started', 'action-scheduler' );
} elseif ( 'publish' == $_REQUEST['post_status'] ) {
$custom_columns['modified'] = __( 'Completed', 'action-scheduler' );
}
}
$custom_columns['claim'] = __( 'Claim ID', 'action-scheduler' );
$custom_columns['comments'] = __( 'Log', 'action-scheduler' );
return $custom_columns;
} }
/** /**
* Make our custom title & date columns use defaulting title & date sorting. * Renders the Admin UI
*
* @param array $columns An associative array of columns that can be used to sort the table on the Scheduled Actions administration screen.
* @return array $columns An associative array of columns that can be used to sort the table on the Scheduled Actions administration screen.
*/ */
public static function list_table_sortable_columns( $columns ) { public function render_admin_ui() {
$table = new ActionScheduler_ListTable( ActionScheduler::store(), ActionScheduler::logger(), ActionScheduler::runner() );
$columns['hook'] = 'title'; $table->display_page();
$columns['scheduled'] = array( 'date', true );
$columns['modified'] = 'modified';
$columns['claim'] = 'post_password';
return $columns;
} }
}
/**
* Print the content for our custom columns.
*
* @param string $column_name The key for the column for which we should output our content.
* @param int $post_id The ID of the 'scheduled-action' post for which this row relates.
* @return void
*/
public static function list_table_column_content( $column_name, $post_id ) {
global $post;
$action = ActionScheduler::store()->fetch_action( $post_id );
$action_title = ( 'trash' == $post->post_status ) ? $post->post_title : $action->get_hook();
$recurrence = ( 'trash' == $post->post_status ) ? 0 : $action->get_schedule();
$next_timestamp = as_get_datetime_object( $post->post_date_gmt )->format( 'U' );
$status = get_post_status( $post_id );
switch ( $column_name ) {
case 'hook':
echo $action_title;
break;
case 'status':
if ( 'publish' == $status ) {
_e( 'Complete', 'action-scheduler' );
} else {
echo ucfirst( $status );
}
break;
case 'args':
$action_args = ( 'trash' == $post->post_status ) ? $post->post_content : $action->get_args();
if ( is_array( $action_args ) ) {
foreach( $action_args as $key => $value ) {
printf( "<code>%s => %s</code><br/>", $key, $value );
}
}
break;
case 'recurrence':
if ( method_exists( $recurrence, 'interval_in_seconds' ) ) {
echo self::human_interval( $recurrence->interval_in_seconds() );
} else {
_e( 'Non-repeating', 'action-scheduler' );
}
break;
case 'scheduled':
echo get_date_from_gmt( gmdate( 'Y-m-d H:i:s', $next_timestamp ), 'Y-m-d H:i:s' );
if ( gmdate( 'U' ) > $next_timestamp ) {
printf( __( ' (%s ago)', 'action-scheduler' ), human_time_diff( gmdate( 'U' ), $next_timestamp ) );
} else {
echo ' (' . human_time_diff( gmdate( 'U' ), $next_timestamp ) . ')';
}
break;
case 'modified':
echo get_post_modified_time( 'Y-m-d H:i:s' );
$modified_timestamp = get_post_modified_time( 'U', true );
if ( gmdate( 'U' ) > $modified_timestamp ) {
printf( __( ' (%s ago)', 'action-scheduler' ), human_time_diff( gmdate( 'U' ), $modified_timestamp ) );
} else {
echo ' (' . human_time_diff( gmdate( 'U' ), $modified_timestamp ) . ')';
}
break;
case 'claim':
echo $post->post_password;
break;
}
}
/**
* Hide the inline "Edit" action for all 'scheduled-action' posts.
*
* Hooked to the 'post_row_actions' filter.
*
* @param array $actions An associative array of actions which can be performed on the 'scheduled-action' post type.
* @return array $actions An associative array of actions which can be performed on the 'scheduled-action' post type.
*/
public static function row_actions( $actions, $post ) {
if ( ActionScheduler_wpPostStore::POST_TYPE == $post->post_type ) {
if ( isset( $actions['edit'] ) ) {
unset( $actions['edit'] );
}
if ( isset( $actions['inline hide-if-no-js'] ) ) {
unset( $actions['inline hide-if-no-js'] );
}
if ( current_user_can( 'edit_post', $post->ID ) && ! in_array( $post->post_status, array( 'publish', 'in-progress', 'trash' ) ) ) {
$actions['process'] = "<a title='" . esc_attr( __( 'Process the action now as if it were run as part of a queue' ) ) . "' href='" . self::get_run_action_link( $post->ID, 'process' ) . "'>" . __( 'Run', 'action-scheduler' ) . "</a>";
}
ksort( $actions );
}
return $actions;
}
/**
* Retrieve a URI to execute a scheduled action.
*
* @param int $action_id The ID for a 'scheduled-action' post.
* @param string $operation To run the action (including trigger before/after hooks), log the execution and update the action's status, use 'process', to simply trigger the action, use 'execute'. Default 'execute'.
* @return string The URL for running the action.
*/
private static function get_run_action_link( $action_id, $operation = 'process' ) {
if ( !$post = get_post( $action_id ) )
return;
$post_type_object = get_post_type_object( $post->post_type );
if ( ! $post_type_object )
return;
if ( ! current_user_can( 'edit_post', $post->ID ) )
return;
$execute_link = add_query_arg( array( 'action' => $operation, 'post_id' => $post->ID ), self::$admin_url );
return wp_nonce_url( $execute_link, "{$operation}-action_{$post->ID}" );
}
/**
* Run an action when triggered from the Action Scheduler administration screen.
*
* @codeCoverageIgnore
*/
public static function maybe_execute_action() {
if ( ! isset( $_GET['action'] ) || 'process' != $_GET['action'] || ! isset( $_GET['post_id'] ) ){
return;
}
$action_id = absint( $_GET['post_id'] );
check_admin_referer( $_GET['action'] . '-action_' . $action_id );
try {
ActionScheduler::runner()->process_action( $action_id );
$success = 1;
} catch ( Exception $e ) {
$success = 0;
}
wp_redirect( add_query_arg( array( 'executed' => $success, 'ids' => $action_id ), self::$admin_url ) );
exit();
}
/**
* Convert an interval of seconds into a two part human friendly string.
*
* The WordPress human_time_diff() function only calculates the time difference to one degree, meaning
* even if an action is 1 day and 11 hours away, it will display "1 day". This funciton goes one step
* further to display two degrees of accuracy.
*
* Based on Crontrol::interval() funciton by Edward Dale: https://wordpress.org/plugins/wp-crontrol/
*
* @param int $interval A interval in seconds.
* @return string A human friendly string representation of the interval.
*/
public static function admin_notices() {
if ( self::is_admin_page() ) {
if ( ActionScheduler_Store::instance()->get_claim_count() >= apply_filters( 'action_scheduler_queue_runner_concurrent_batches', 5 ) ) : ?>
<div id="message" class="updated">
<p><?php printf( __( 'Maximum simulatenous batches already in progress (%s queues). No actions will be processed until the current batches are complete.', 'action-scheduler' ), ActionScheduler_Store::instance()->get_claim_count() ); ?></p>
</div>
<?php endif;
if ( isset( $_GET['executed'] ) && isset( $_GET['ids'] ) ) {
$action = ActionScheduler::store()->fetch_action( $_GET['ids'] );
$action_hook_html = '<strong>' . $action->get_hook() . '</strong>';
if ( 1 == $_GET['executed'] ) : ?>
<div id="message" class="updated">
<p><?php printf( __( 'Successfully executed the action: %s', 'action-scheduler' ), $action_hook_html ); ?></p>
</div>
<?php else : ?>
<div id="message" class="error">
<p><?php printf( __( 'Could not execute the action: %s', 'action-scheduler' ), $action_hook_html ); ?></p>
</div>
<?php endif;
}
}
}
/**
* Convert a interval of seconds into a two part human friendly string.
*
* The WordPress human_time_diff() function only calculates the time difference to one degree, meaning
* even if an action is 1 day and 11 hours away, it will display "1 day". This funciton goes one step
* further to display two degrees of accuracy.
*
* Based on Crontrol::interval() funciton by Edward Dale: https://wordpress.org/plugins/wp-crontrol/
*
* @param int $interval A interval in seconds.
* @return string A human friendly string representation of the interval.
*/
private static function human_interval( $interval ) {
// array of time period chunks
$chunks = array(
array( 60 * 60 * 24 * 365 , _n_noop( '%s year', '%s years', 'action-scheduler' ) ),
array( 60 * 60 * 24 * 30 , _n_noop( '%s month', '%s months', 'action-scheduler' ) ),
array( 60 * 60 * 24 * 7, _n_noop( '%s week', '%s weeks', 'action-scheduler' ) ),
array( 60 * 60 * 24 , _n_noop( '%s day', '%s days', 'action-scheduler' ) ),
array( 60 * 60 , _n_noop( '%s hour', '%s hours', 'action-scheduler' ) ),
array( 60 , _n_noop( '%s minute', '%s minutes', 'action-scheduler' ) ),
array( 1 , _n_noop( '%s second', '%s seconds', 'action-scheduler' ) ),
);
if ( $interval <= 0 ) {
return __( 'Now!', 'action-scheduler' );
}
// Step one: the first chunk
for ( $i = 0, $j = count( $chunks ); $i < $j; $i++ ) {
$seconds = $chunks[$i][0];
$name = $chunks[$i][1];
if ( ( $count = floor( $interval / $seconds ) ) != 0 ) {
break;
}
}
$output = sprintf( _n( $name[0], $name[1], $count, 'action-scheduler' ), $count );
if ( $i + 1 < $j ) {
$seconds2 = $chunks[$i + 1][0];
$name2 = $chunks[$i + 1][1];
if ( ( $count2 = floor( ( $interval - ( $seconds * $count ) ) / $seconds2 ) ) != 0 ) {
// add to output var
$output .= ' '.sprintf( _n( $name2[0], $name2[1], $count2, 'action-scheduler' ), $count2 );
}
}
return $output;
}
/**
* Filter search queries to allow searching by Claim ID (i.e. post_password).
*
* @param string $orderby MySQL orderby string.
* @param WP_Query $query Instance of a WP_Query object
* @return string MySQL orderby string.
*/
public function custom_orderby( $orderby, $query ){
global $wpdb;
if ( self::is_admin_page() && ! empty( $query->query['orderby'] ) && 'post_password' == $query->query['orderby'] ) {
$orderby = "$wpdb->posts.post_password " . $query->query['order'];
}
return $orderby;
}
/**
* Filter search queries to allow searching by Claim ID (i.e. post_password).
*
* @param string $search MySQL search string.
* @param WP_Query $query Instance of a WP_Query object
* @return string MySQL search string.
*/
public function search_post_password( $search, $query ) {
global $wpdb;
if ( self::is_admin_page() && ! empty( $search ) ) {
$search = '';
$searchand = '';
$n = ! empty( $query->query_vars['exact'] ) ? '' : '%';
foreach ( $query->query_vars['search_terms'] as $term ) {
$term = $wpdb->esc_like( esc_sql( $term ) );
$search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_password LIKE '{$n}{$term}{$n}'))";
$searchand = ' AND ';
}
if ( ! empty( $search ) ) {
$search = " AND ({$search}) ";
}
}
return $search;
}
/**
* Change messages when a scheduled action is updated.
*
* @param array $messages
* @return array
*/
public function post_updated_messages( $messages ) {
global $post, $post_ID;
$messages[ ActionScheduler_wpPostStore::POST_TYPE ] = array(
0 => '', // Unused. Messages start at index 1.
1 => __( 'Action updated.', 'action-scheduler' ),
2 => __( 'Custom field updated.', 'action-scheduler' ),
3 => __( 'Custom field deleted.', 'action-scheduler' ),
4 => __( 'Action updated.', 'action-scheduler' ),
5 => isset( $_GET['revision'] ) ? sprintf( __( 'Action restored to revision from %s', 'action-scheduler' ), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
6 => __( 'Action scheduled.', 'action-scheduler' ),
7 => __( 'Action saved.', 'action-scheduler' ),
8 => __( 'Action submitted.', 'action-scheduler' ),
9 => sprintf( __( 'Action scheduled for: <strong>%1$s</strong>', 'action-scheduler' ), date_i18n( __( 'M j, Y @ G:i', 'action-scheduler' ), strtotime( $post->post_date ) ) ),
10 => __( 'Action draft updated.', 'action-scheduler' ),
);
return $messages;
}
/**
* Check if the current request is for the Schedul Actions administration screen.
*
* @return bool
*/
private static function is_admin_page() {
if ( is_admin() && isset( $_GET['post_type'] ) && $_GET['post_type'] == ActionScheduler_wpPostStore::POST_TYPE ) {
return true;
} else {
return false;
}
}
}

View File

@@ -0,0 +1,147 @@
<?php
/**
* Class ActionScheduler_AdminView_Deprecated
*
* Store deprecated public functions previously found in the ActionScheduler_AdminView class.
* Keeps them out of the way of the main class.
*
* @codeCoverageIgnore
*/
class ActionScheduler_AdminView_Deprecated {
public function action_scheduler_post_type_args( $args ) {
_deprecated_function( __METHOD__, '2.0.0' );
return $args;
}
/**
* Customise the post status related views displayed on the Scheduled Actions administration screen.
*
* @param array $views An associative array of views and view labels which can be used to filter the 'scheduled-action' posts displayed on the Scheduled Actions administration screen.
* @return array $views An associative array of views and view labels which can be used to filter the 'scheduled-action' posts displayed on the Scheduled Actions administration screen.
*/
public function list_table_views( $views ) {
_deprecated_function( __METHOD__, '2.0.0' );
return $views;
}
/**
* Do not include the "Edit" action for the Scheduled Actions administration screen.
*
* Hooked to the 'bulk_actions-edit-action-scheduler' filter.
*
* @param array $actions An associative array of actions which can be performed on the 'scheduled-action' post type.
* @return array $actions An associative array of actions which can be performed on the 'scheduled-action' post type.
*/
public function bulk_actions( $actions ) {
_deprecated_function( __METHOD__, '2.0.0' );
return $actions;
}
/**
* Completely customer the columns displayed on the Scheduled Actions administration screen.
*
* Because we can't filter the content of the default title and date columns, we need to recreate our own
* custom columns for displaying those post fields. For the column content, @see self::list_table_column_content().
*
* @param array $columns An associative array of columns that are use for the table on the Scheduled Actions administration screen.
* @return array $columns An associative array of columns that are use for the table on the Scheduled Actions administration screen.
*/
public function list_table_columns( $columns ) {
_deprecated_function( __METHOD__, '2.0.0' );
return $columns;
}
/**
* Make our custom title & date columns use defaulting title & date sorting.
*
* @param array $columns An associative array of columns that can be used to sort the table on the Scheduled Actions administration screen.
* @return array $columns An associative array of columns that can be used to sort the table on the Scheduled Actions administration screen.
*/
public static function list_table_sortable_columns( $columns ) {
_deprecated_function( __METHOD__, '2.0.0' );
return $columns;
}
/**
* Print the content for our custom columns.
*
* @param string $column_name The key for the column for which we should output our content.
* @param int $post_id The ID of the 'scheduled-action' post for which this row relates.
*/
public static function list_table_column_content( $column_name, $post_id ) {
_deprecated_function( __METHOD__, '2.0.0' );
}
/**
* Hide the inline "Edit" action for all 'scheduled-action' posts.
*
* Hooked to the 'post_row_actions' filter.
*
* @param array $actions An associative array of actions which can be performed on the 'scheduled-action' post type.
* @return array $actions An associative array of actions which can be performed on the 'scheduled-action' post type.
*/
public static function row_actions( $actions, $post ) {
_deprecated_function( __METHOD__, '2.0.0' );
return $actions;
}
/**
* Run an action when triggered from the Action Scheduler administration screen.
*
* @codeCoverageIgnore
*/
public static function maybe_execute_action() {
_deprecated_function( __METHOD__, '2.0.0' );
}
/**
* Convert an interval of seconds into a two part human friendly string.
*
* The WordPress human_time_diff() function only calculates the time difference to one degree, meaning
* even if an action is 1 day and 11 hours away, it will display "1 day". This funciton goes one step
* further to display two degrees of accuracy.
*
* Based on Crontrol::interval() function by Edward Dale: https://wordpress.org/plugins/wp-crontrol/
*
* @param int $interval A interval in seconds.
* @return string A human friendly string representation of the interval.
*/
public static function admin_notices() {
_deprecated_function( __METHOD__, '2.0.0' );
}
/**
* Filter search queries to allow searching by Claim ID (i.e. post_password).
*
* @param string $orderby MySQL orderby string.
* @param WP_Query $query Instance of a WP_Query object
* @return string MySQL orderby string.
*/
public function custom_orderby( $orderby, $query ){
_deprecated_function( __METHOD__, '2.0.0' );
}
/**
* Filter search queries to allow searching by Claim ID (i.e. post_password).
*
* @param string $search MySQL search string.
* @param WP_Query $query Instance of a WP_Query object
* @return string MySQL search string.
*/
public function search_post_password( $search, $query ) {
_deprecated_function( __METHOD__, '2.0.0' );
}
/**
* Change messages when a scheduled action is updated.
*
* @param array $messages
* @return array
*/
public function post_updated_messages( $messages ) {
_deprecated_function( __METHOD__, '2.0.0' );
return $messages;
}
}

View File

@@ -0,0 +1,21 @@
<?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 );
$this->set_schedule( new ActionScheduler_NullSchedule() );
}
}

View File

@@ -36,7 +36,7 @@ class ActionScheduler_CronSchedule implements ActionScheduler_Schedule {
* @return array * @return array
*/ */
public function __sleep() { public function __sleep() {
$this->start_timestamp = $this->start->format('U'); $this->start_timestamp = $this->start->getTimestamp();
return array( return array(
'start_timestamp', 'start_timestamp',
'cron' 'cron'

View File

@@ -0,0 +1,20 @@
<?php
/**
* ActionScheduler DateTime class.
*
* This is a custom extension to DateTime that
*/
class ActionScheduler_DateTime extends DateTime {
/**
* 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' );
}
}

View File

@@ -49,7 +49,7 @@ class ActionScheduler_IntervalSchedule implements ActionScheduler_Schedule {
* @return array * @return array
*/ */
public function __sleep() { public function __sleep() {
$this->start_timestamp = $this->start->format('U'); $this->start_timestamp = $this->start->getTimestamp();
return array( return array(
'start_timestamp', 'start_timestamp',
'interval_in_seconds' 'interval_in_seconds'
@@ -60,4 +60,3 @@ class ActionScheduler_IntervalSchedule implements ActionScheduler_Schedule {
$this->start = as_get_datetime_object($this->start_timestamp); $this->start = as_get_datetime_object($this->start_timestamp);
} }
} }

View File

@@ -0,0 +1,526 @@
<?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,
'names' => _n_noop( '%s year', '%s years', 'action-scheduler' ),
),
array(
'seconds' => MONTH_IN_SECONDS,
'names' => _n_noop( '%s month', '%s months', 'action-scheduler' ),
),
array(
'seconds' => WEEK_IN_SECONDS,
'names' => _n_noop( '%s week', '%s weeks', 'action-scheduler' ),
),
array(
'seconds' => DAY_IN_SECONDS,
'names' => _n_noop( '%s day', '%s days', 'action-scheduler' ),
),
array(
'seconds' => HOUR_IN_SECONDS,
'names' => _n_noop( '%s hour', '%s hours', 'action-scheduler' ),
),
array(
'seconds' => MINUTE_IN_SECONDS,
'names' => _n_noop( '%s minute', '%s minutes', 'action-scheduler' ),
),
array(
'seconds' => 1,
'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 ) {
$recurrence = $action->get_schedule();
if ( method_exists( $recurrence, 'interval_in_seconds' ) ) {
return sprintf( __( 'Every %s', 'action-scheduler' ), self::human_interval( $recurrence->interval_in_seconds() ) );
}
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( $key ), esc_html( $value ) );
}
$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 e' ) ), 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->store->get_claim_count() >= $this->runner->get_allowed_concurrent_batches() ) {
$this->admin_notices[] = array(
'class' => 'updated',
'message' => sprintf( __( 'Maximum simultaneous batches already in progress (%s queues). No actions will be processed until the current batches are complete.', 'action-scheduler' ), $this->store->get_claim_count() ),
);
}
$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' :
$action_message_html = sprintf( __( 'Successfully executed action: %s', 'action-scheduler' ), $action_hook_html );
break;
case 'cancel' :
$action_message_html = sprintf( __( 'Successfully canceled action: %s', 'action-scheduler' ), $action_hook_html );
break;
default :
$action_message_html = sprintf( __( 'Successfully processed change for action: %s', 'action-scheduler' ), $action_hook_html );
break;
}
} else {
$class = 'error';
$action_message_html = sprintf( __( 'Could not process change for action: "%s" (ID: %d). Error: %s', 'action-scheduler' ), $action_hook_html, esc_html( $notification['action_id'] ), esc_html( $notification['error_message'] ) );
}
$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->next() ) {
return $schedule_display_string;
}
$next_timestamp = $schedule->next()->getTimestamp();
$schedule_display_string .= $schedule->next()->format( 'Y-m-d H:i:s e' );
$schedule_display_string .= '<br/>';
if ( gmdate( 'U' ) > $next_timestamp ) {
$schedule_display_string .= sprintf( __( ' (%s ago)', 'action-scheduler' ), self::human_interval( gmdate( 'U' ) - $next_timestamp ) );
} else {
$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 );
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->process_bulk_action();
$this->process_row_actions();
if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
// _wp_http_referer is used only on bulk actions, we remove it to keep the $_GET shorter
wp_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
exit;
}
$this->prepare_column_headers();
$per_page = $this->get_items_per_page( $this->package . '_items_per_page', $this->items_per_page );
$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

@@ -4,12 +4,56 @@
* Class ActionScheduler_LogEntry * Class ActionScheduler_LogEntry
*/ */
class ActionScheduler_LogEntry { class ActionScheduler_LogEntry {
protected $action_id = '';
protected $message = '';
public function __construct( $action_id, $message ) { /**
* @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->action_id = $action_id;
$this->message = $message; $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() { public function get_action_id() {
@@ -20,4 +64,4 @@ class ActionScheduler_LogEntry {
return $this->message; return $this->message;
} }
} }

View File

@@ -4,29 +4,76 @@
* Class ActionScheduler_QueueCleaner * Class ActionScheduler_QueueCleaner
*/ */
class ActionScheduler_QueueCleaner { class ActionScheduler_QueueCleaner {
/** @var ActionScheduler_Store */
private $store = NULL;
private $month_in_seconds = 2678400; // 31 days /** @var int */
protected $batch_size;
/** @var ActionScheduler_Store */
private $store = null;
/**
* 31 days in seconds.
*
* @var int
*/
private $month_in_seconds = 2678400;
/**
* Five minutes in seconds
*
* @var int
*/
private $five_minutes = 300; private $five_minutes = 300;
public function __construct( ActionScheduler_Store $store = NULL ) { /**
* 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->store = $store ? $store : ActionScheduler_Store::instance();
$this->batch_size = $batch_size;
} }
public function delete_old_actions() { public function delete_old_actions() {
$lifespan = apply_filters( 'action_scheduler_retention_period', $this->month_in_seconds ); $lifespan = apply_filters( 'action_scheduler_retention_period', $this->month_in_seconds );
$cutoff = as_get_datetime_object($lifespan.' seconds ago'); $cutoff = as_get_datetime_object($lifespan.' seconds ago');
$actions_to_delete = $this->store->query_actions( array( $statuses_to_purge = array(
'status' => ActionScheduler_Store::STATUS_COMPLETE, ActionScheduler_Store::STATUS_COMPLETE,
'modified' => $cutoff, ActionScheduler_Store::STATUS_CANCELED,
'modified_compare' => '<=', );
'per_page' => apply_filters( 'action_scheduler_cleanup_batch_size', 20 ),
) );
foreach ( $actions_to_delete as $action_id ) { foreach ( $statuses_to_purge as $status ) {
$this->store->delete_action( $action_id ); $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 ) );
}
}
} }
} }
@@ -37,11 +84,11 @@ class ActionScheduler_QueueCleaner {
} }
$cutoff = as_get_datetime_object($timeout.' seconds ago'); $cutoff = as_get_datetime_object($timeout.' seconds ago');
$actions_to_reset = $this->store->query_actions( array( $actions_to_reset = $this->store->query_actions( array(
'status' => ActionScheduler_Store::STATUS_PENDING, 'status' => ActionScheduler_Store::STATUS_PENDING,
'modified' => $cutoff, 'modified' => $cutoff,
'modified_compare' => '<=', 'modified_compare' => '<=',
'claimed' => TRUE, 'claimed' => true,
'per_page' => apply_filters( 'action_scheduler_cleanup_batch_size', 20 ), 'per_page' => $this->get_batch_size(),
) ); ) );
foreach ( $actions_to_reset as $action_id ) { foreach ( $actions_to_reset as $action_id ) {
@@ -57,10 +104,10 @@ class ActionScheduler_QueueCleaner {
} }
$cutoff = as_get_datetime_object($timeout.' seconds ago'); $cutoff = as_get_datetime_object($timeout.' seconds ago');
$actions_to_reset = $this->store->query_actions( array( $actions_to_reset = $this->store->query_actions( array(
'status' => ActionScheduler_Store::STATUS_RUNNING, 'status' => ActionScheduler_Store::STATUS_RUNNING,
'modified' => $cutoff, 'modified' => $cutoff,
'modified_compare' => '<=', 'modified_compare' => '<=',
'per_page' => apply_filters( 'action_scheduler_cleanup_batch_size', 20 ), 'per_page' => $this->get_batch_size(),
) ); ) );
foreach ( $actions_to_reset as $action_id ) { foreach ( $actions_to_reset as $action_id ) {
@@ -68,5 +115,30 @@ class ActionScheduler_QueueCleaner {
do_action( 'action_scheduler_failed_action', $action_id, $timeout ); do_action( 'action_scheduler_failed_action', $action_id, $timeout );
} }
} }
/**
* Do all of the cleaning actions.
*
* @author Jeremy Pry
*/
public function clean() {
$this->delete_old_actions();
$this->reset_timeouts();
$this->mark_failures();
}
/**
* 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

@@ -3,18 +3,23 @@
/** /**
* Class ActionScheduler_QueueRunner * Class ActionScheduler_QueueRunner
*/ */
class ActionScheduler_QueueRunner { class ActionScheduler_QueueRunner extends ActionScheduler_Abstract_QueueRunner {
const WP_CRON_HOOK = 'action_scheduler_run_queue'; const WP_CRON_HOOK = 'action_scheduler_run_queue';
const WP_CRON_SCHEDULE = 'every_minute'; const WP_CRON_SCHEDULE = 'every_minute';
/** @var ActionScheduler_QueueRunner */ /** @var ActionScheduler_QueueRunner */
private static $runner = NULL; private static $runner = null;
/** @var ActionScheduler_Store */
private $store = NULL;
/** @var ActionScheduler_FatalErrorMonitor */ /**
private $monitor = NULL; * 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;
/** /**
* @return ActionScheduler_QueueRunner * @return ActionScheduler_QueueRunner
@@ -28,8 +33,16 @@ class ActionScheduler_QueueRunner {
return self::$runner; return self::$runner;
} }
public function __construct( ActionScheduler_Store $store = NULL ) { /**
$this->store = $store ? $store : ActionScheduler_Store::instance(); * 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 ) {
parent::__construct( $store, $monitor, $cleaner );
$this->created_time = microtime( true );
} }
/** /**
@@ -53,29 +66,32 @@ class ActionScheduler_QueueRunner {
do_action( 'action_scheduler_before_process_queue' ); do_action( 'action_scheduler_before_process_queue' );
$this->run_cleanup(); $this->run_cleanup();
$count = 0; $count = 0;
if ( $this->store->get_claim_count() < apply_filters( 'action_scheduler_queue_runner_concurrent_batches', 5 ) ) { if ( $this->store->get_claim_count() < $this->get_allowed_concurrent_batches() ) {
$batch_size = apply_filters( 'action_scheduler_queue_runner_batch_size', 25 ); $batch_size = apply_filters( 'action_scheduler_queue_runner_batch_size', 25 );
$this->monitor = new ActionScheduler_FatalErrorMonitor( $this->store );
$count = $this->do_batch( $batch_size ); $count = $this->do_batch( $batch_size );
unset( $this->monitor );
} }
do_action( 'action_scheduler_after_process_queue' ); do_action( 'action_scheduler_after_process_queue' );
return $count; return $count;
} }
protected function run_cleanup() {
$cleaner = new ActionScheduler_QueueCleaner( $this->store );
$cleaner->delete_old_actions();
$cleaner->reset_timeouts();
$cleaner->mark_failures();
}
protected function do_batch( $size = 100 ) { protected function do_batch( $size = 100 ) {
$claim = $this->store->stake_claim($size); $claim = $this->store->stake_claim($size);
$this->monitor->attach($claim); $this->monitor->attach($claim);
$processed_actions = 0; $processed_actions = 0;
$maximum_execution_time = $this->get_maximum_execution_time();
foreach ( $claim->get_actions() as $action_id ) { foreach ( $claim->get_actions() as $action_id ) {
if ( 0 !== $processed_actions ) {
$time_elapsed = $this->get_execution_time();
$average_processing_time = $time_elapsed / $processed_actions;
// Bail early if the time it has taken to process this batch is approaching the maximum execution time.
if ( $time_elapsed + ( $average_processing_time * 2 ) > $maximum_execution_time ) {
break;
}
}
// bail if we lost the claim // bail if we lost the claim
if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $claim->get_id() ) ) ) { if ( ! in_array( $action_id, $this->store->find_actions_by_claim_id( $claim->get_id() ) ) ) {
break; break;
@@ -89,31 +105,6 @@ class ActionScheduler_QueueRunner {
return $processed_actions; return $processed_actions;
} }
public function process_action( $action_id ) {
try {
do_action( 'action_scheduler_before_execute', $action_id );
$action = $this->store->fetch_action( $action_id );
$this->store->log_execution( $action_id );
$action->execute();
do_action( 'action_scheduler_after_execute', $action_id );
$this->store->mark_complete( $action_id );
} catch ( Exception $e ) {
$this->store->mark_failure( $action_id );
do_action( 'action_scheduler_failed_execution', $action_id, $e );
}
$this->schedule_next_instance( $action );
}
protected function schedule_next_instance( ActionScheduler_Action $action ) {
$schedule = $action->get_schedule();
$next = $schedule->next( as_get_datetime_object() );
if ( ! is_null( $next ) && $schedule->is_recurring() ) {
$this->store->save_action( $action, $next );
}
}
/** /**
* Running large batches can eat up memory, as WP adds data to its object cache. * Running large batches can eat up memory, as WP adds data to its object cache.
* *
@@ -121,8 +112,6 @@ class ActionScheduler_QueueRunner {
* as well, so this is disabled by default. To enable: * as well, so this is disabled by default. To enable:
* *
* add_filter( 'action_scheduler_queue_runner_flush_cache', '__return_true' ); * add_filter( 'action_scheduler_queue_runner_flush_cache', '__return_true' );
*
* @return void
*/ */
protected function clear_caches() { protected function clear_caches() {
if ( ! wp_using_ext_object_cache() || apply_filters( 'action_scheduler_queue_runner_flush_cache', false ) ) { if ( ! wp_using_ext_object_cache() || apply_filters( 'action_scheduler_queue_runner_flush_cache', false ) ) {
@@ -138,5 +127,43 @@ class ActionScheduler_QueueRunner {
return $schedules; return $schedules;
} }
/**
* Get the maximum number of seconds a batch can run for.
*
* @return int The number of seconds.
*/
protected function get_maximum_execution_time() {
// There are known hosts with a strict 60 second execution time.
if ( defined( 'WPENGINE_ACCOUNT' ) || defined( 'PANTHEON_ENVIRONMENT' ) ) {
$maximum_execution_time = 60;
} elseif ( false !== strpos( getenv( 'HOSTNAME' ), '.siteground.' ) ) {
$maximum_execution_time = 120;
} else {
$maximum_execution_time = ini_get( 'max_execution_time' );
}
return absint( apply_filters( 'action_scheduler_maximum_execution_time', $maximum_execution_time ) );
}
/**
* Get the number of seconds a batch has run for.
*
* @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;
}
} }

View File

@@ -32,7 +32,7 @@ class ActionScheduler_SimpleSchedule implements ActionScheduler_Schedule {
* @return array * @return array
*/ */
public function __sleep() { public function __sleep() {
$this->timestamp = $this->date->format('U'); $this->timestamp = $this->date->getTimestamp();
return array( return array(
'timestamp', 'timestamp',
); );
@@ -42,4 +42,3 @@ class ActionScheduler_SimpleSchedule implements ActionScheduler_Schedule {
$this->date = as_get_datetime_object($this->timestamp); $this->date = as_get_datetime_object($this->timestamp);
} }
} }

View File

@@ -6,22 +6,23 @@
*/ */
abstract class ActionScheduler_Store { abstract class ActionScheduler_Store {
const STATUS_COMPLETE = 'complete'; const STATUS_COMPLETE = 'complete';
const STATUS_PENDING = 'pending'; const STATUS_PENDING = 'pending';
const STATUS_RUNNING = 'in-progress'; const STATUS_RUNNING = 'in-progress';
const STATUS_FAILED = 'failed'; const STATUS_FAILED = 'failed';
const STATUS_CANCELED = 'canceled';
/** @var ActionScheduler_Store */ /** @var ActionScheduler_Store */
private static $store = NULL; private static $store = NULL;
/** /**
* @param ActionScheduler_Action $action * @param ActionScheduler_Action $action
* @param DateTime $date Optional date of the first instance * @param DateTime $scheduled_date Optional Date of the first instance
* to store. Otherwise uses the first date of the action's * to store. Otherwise uses the first date of the action's
* schedule. * schedule.
* *
* @return string The action ID * @return string The action ID
*/ */
abstract public function save_action( ActionScheduler_Action $action, DateTime $date = NULL ); abstract public function save_action( ActionScheduler_Action $action, DateTime $scheduled_date = NULL );
/** /**
* @param string $action_id * @param string $action_id
@@ -44,16 +45,19 @@ abstract class ActionScheduler_Store {
abstract public function query_actions( $query = array() ); abstract public function query_actions( $query = array() );
/** /**
* @param string $action_id * Get a count of all actions in the store, grouped by status
* *
* @return void * @return array
*/
abstract public function action_counts();
/**
* @param string $action_id
*/ */
abstract public function cancel_action( $action_id ); abstract public function cancel_action( $action_id );
/** /**
* @param string $action_id * @param string $action_id
*
* @return void
*/ */
abstract public function delete_action( $action_id ); abstract public function delete_action( $action_id );
@@ -66,12 +70,14 @@ abstract class ActionScheduler_Store {
/** /**
* @param int $max_actions * @param int $max_actions
* @param DateTime $before_date Claim only actions schedule before the given date. Defaults to now. * @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 * @return ActionScheduler_ActionClaim
*/ */
abstract public function stake_claim( $max_actions = 10, DateTime $before_date = NULL ); abstract public function stake_claim( $max_actions = 10, DateTime $before_date = null, $hooks = array(), $group = '' );
/** /**
* @return int * @return int
@@ -80,38 +86,115 @@ abstract class ActionScheduler_Store {
/** /**
* @param ActionScheduler_ActionClaim $claim * @param ActionScheduler_ActionClaim $claim
*
* @return void
*/ */
abstract public function release_claim( ActionScheduler_ActionClaim $claim ); abstract public function release_claim( ActionScheduler_ActionClaim $claim );
/** /**
* @param string $action_id * @param string $action_id
*
* @return void
*/ */
abstract public function unclaim_action( $action_id ); abstract public function unclaim_action( $action_id );
/** /**
* @param string $action_id * @param string $action_id
*
* @return void
*/ */
abstract public function mark_failure( $action_id ); abstract public function mark_failure( $action_id );
/** /**
* @param string $action_id * @param string $action_id
* @return void
*/ */
abstract public function log_execution( $action_id ); abstract public function log_execution( $action_id );
/** /**
* @param string $action_id * @param string $action_id
*
* @return void
*/ */
abstract public function mark_complete( $action_id ); abstract public function mark_complete( $action_id );
/**
* @param string $action_id
*
* @return string
*/
abstract public function get_status( $action_id );
/**
* @param string $action_id
* @return mixed
*/
abstract public function get_claim_id( $action_id );
/**
* @param string $claim_id
* @return array
*/
abstract public function find_actions_by_claim_id( $claim_id );
/**
* @param string $comparison_operator
* @return string
*/
protected function validate_sql_comparator( $comparison_operator ) {
if ( in_array( $comparison_operator, array('!=', '>', '>=', '<', '<=', '=') ) ) {
return $comparison_operator;
}
return '=';
}
/**
* Get the time MySQL formated date/time string for an action's (next) scheduled date.
*
* @param ActionScheduler_Action $action
* @param DateTime $scheduled_date (optional)
* @return string
*/
protected function get_scheduled_date_string( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
$next = null === $scheduled_date ? $action->get_schedule()->next() : $scheduled_date;
if ( ! $next ) {
throw new InvalidArgumentException( __( 'Invalid schedule. Cannot save action.', 'action-scheduler' ) );
}
$next->setTimezone( new DateTimeZone( 'UTC' ) );
return $next->format( 'Y-m-d H:i:s' );
}
/**
* Get the time MySQL formated date/time string for an action's (next) scheduled date.
*
* @param ActionScheduler_Action $action
* @param DateTime $scheduled_date (optional)
* @return string
*/
protected function get_scheduled_date_string_local( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
$next = null === $scheduled_date ? $action->get_schedule()->next() : $scheduled_date;
if ( ! $next ) {
throw new InvalidArgumentException( __( 'Invalid schedule. Cannot save action.', 'action-scheduler' ) );
}
$next->setTimezone( $this->get_local_timezone() );
return $next->format( 'Y-m-d H:i:s' );
}
/**
* Get the site's local time. Wrapper for ActionScheduler_TimezoneHelper::get_local_timezone().
*
* @return DateTimeZone
*/
protected function get_local_timezone() {
return ActionScheduler_TimezoneHelper::get_local_timezone();
}
/**
* @return array
*/
public function get_status_labels() {
return array(
self::STATUS_COMPLETE => __( 'Complete', 'action-scheduler' ),
self::STATUS_PENDING => __( 'Pending', 'action-scheduler' ),
self::STATUS_RUNNING => __( 'In-progress', 'action-scheduler' ),
self::STATUS_FAILED => __( 'Failed', 'action-scheduler' ),
self::STATUS_CANCELED => __( 'Canceled', 'action-scheduler' ),
);
}
public function init() {} public function init() {}
/** /**
@@ -125,4 +208,3 @@ abstract class ActionScheduler_Store {
return self::$store; return self::$store;
} }
} }

View File

@@ -0,0 +1,204 @@
<?php
/**
* 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 ) ) {
throw new Exception( __( 'The ' . __CLASS__ . ' class can only be run within WP CLI.', 'action-scheduler' ) );
}
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.
$claim_count = $this->store->get_claim_count();
$too_many = $claim_count >= $this->get_allowed_concurrent_batches();
if ( $too_many ) {
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' ) );
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 = \WP_CLI\Utils\make_progress_bar(
sprintf( _n( 'Running %d action', 'Running %d actions', $count, 'action-scheduler' ), number_format_i18n( $count ) ),
$count
);
}
/**
* Process actions in the queue.
*
* @author Jeremy Pry
* @return int The number of actions processed.
*/
public function run() {
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 );
$this->progress_bar->tick();
// Free up memory after every 50 items
if ( 0 === $this->progress_bar->current() % 50 ) {
$this->stop_the_insanity();
}
}
$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 $action_id
*/
public function after_execute( $action_id ) {
/* translators: %s refers to the action ID */
WP_CLI::log( sprintf( __( 'Completed processing action %s', 'action-scheduler' ), $action_id ) );
}
/**
* 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$s refers to the action ID, %2$s refers to the 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
*/
protected function stop_the_insanity( $sleep_time = 0 ) {
if ( 0 < $sleep_time ) {
WP_CLI::warning( sprintf( 'Stopped the insanity for %d %s', $sleep_time, _n( 'second', 'seconds', $sleep_time ) ) );
sleep( $sleep_time );
}
WP_CLI::warning( __( 'Attempting to reduce used memory...', 'action-scheduler' ) );
/**
* @var $wpdb \wpdb
* @var $wp_object_cache \WP_Object_Cache
*/
global $wpdb, $wp_object_cache;
$wpdb->queries = array();
if ( ! is_object( $wp_object_cache ) ) {
return;
}
$wp_object_cache->group_ops = array();
$wp_object_cache->stats = array();
$wp_object_cache->memcache_debug = array();
$wp_object_cache->cache = array();
if ( is_callable( array( $wp_object_cache, '__remoteset' ) ) ) {
call_user_func( array( $wp_object_cache, '__remoteset' ) ); // important
}
}
}

View File

@@ -0,0 +1,145 @@
<?php
/**
* Commands for the Action Scheduler by Prospress.
*/
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.
*
* [--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.
*/
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', '' );
$force = \WP_CLI\Utils\get_flag_value( $assoc_args, 'force', false );
$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

@@ -49,7 +49,10 @@ class ActionScheduler_wpCommentLogger extends ActionScheduler_Logger {
if ( empty($comment) || $comment->comment_type != self::TYPE ) { if ( empty($comment) || $comment->comment_type != self::TYPE ) {
return new ActionScheduler_NullLogEntry(); return new ActionScheduler_NullLogEntry();
} }
return new ActionScheduler_LogEntry( $comment->comment_post_ID, $comment->comment_content, $comment->comment_type );
$date = as_get_datetime_object( $comment->comment_date_gmt );
$date->setTimezone( ActionScheduler_TimezoneHelper::get_local_timezone() );
return new ActionScheduler_LogEntry( $comment->comment_post_ID, $comment->comment_content, $date );
} }
/** /**
@@ -87,8 +90,6 @@ class ActionScheduler_wpCommentLogger extends ActionScheduler_Logger {
/** /**
* @param WP_Comment_Query $query * @param WP_Comment_Query $query
*
* @return void
*/ */
public function filter_comment_queries( $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 ) { foreach ( array('ID', 'parent', 'post_author', 'post_name', 'post_parent', 'type', 'post_type', 'post_id', 'post_ID') as $key ) {
@@ -205,8 +206,6 @@ class ActionScheduler_wpCommentLogger extends ActionScheduler_Logger {
/** /**
* Delete comment count cache whenever there is new comment or the status of a comment changes. Cache * 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. * will be regenerated next time ActionScheduler_wpCommentLogger::filter_comment_count() is called.
*
* @return void
*/ */
public function delete_comment_count_cache() { public function delete_comment_count_cache() {
delete_transient( 'as_comment_count' ); delete_transient( 'as_comment_count' );

View File

@@ -11,9 +11,9 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
/** @var DateTimeZone */ /** @var DateTimeZone */
protected $local_timezone = NULL; protected $local_timezone = NULL;
public function save_action( ActionScheduler_Action $action, DateTime $date = NULL ){ public function save_action( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ){
try { try {
$post_array = $this->create_post_array( $action, $date ); $post_array = $this->create_post_array( $action, $scheduled_date );
$post_id = $this->save_post_array( $post_array ); $post_id = $this->save_post_array( $post_array );
$this->save_post_schedule( $post_id, $action->get_schedule() ); $this->save_post_schedule( $post_id, $action->get_schedule() );
$this->save_action_group( $post_id, $action->get_group() ); $this->save_action_group( $post_id, $action->get_group() );
@@ -24,44 +24,22 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
} }
} }
protected function create_post_array( ActionScheduler_Action $action, DateTime $date = NULL ) { protected function create_post_array( ActionScheduler_Action $action, DateTime $scheduled_date = NULL ) {
$post = array( $post = array(
'post_type' => self::POST_TYPE, 'post_type' => self::POST_TYPE,
'post_title' => $action->get_hook(), 'post_title' => $action->get_hook(),
'post_content' => json_encode($action->get_args()), 'post_content' => json_encode($action->get_args()),
'post_status' => ( $action->is_finished() ? 'publish' : 'pending' ), 'post_status' => ( $action->is_finished() ? 'publish' : 'pending' ),
'post_date_gmt' => $this->get_timestamp($action, $date), 'post_date_gmt' => $this->get_scheduled_date_string( $action, $scheduled_date ),
'post_date' => $this->get_local_timestamp($action, $date), 'post_date' => $this->get_scheduled_date_string_local( $action, $scheduled_date ),
); );
return $post; return $post;
} }
protected function get_timestamp( ActionScheduler_Action $action, DateTime $date = NULL ) {
$next = is_null($date) ? $action->get_schedule()->next() : $date;
if ( !$next ) {
throw new InvalidArgumentException(__('Invalid schedule. Cannot save action.', 'action-scheduler'));
}
$next->setTimezone(new DateTimeZone('UTC'));
return $next->format('Y-m-d H:i:s');
}
protected function get_local_timestamp( ActionScheduler_Action $action, DateTime $date = NULL ) {
$next = is_null($date) ? $action->get_schedule()->next() : $date;
if ( !$next ) {
throw new InvalidArgumentException(__('Invalid schedule. Cannot save action.', 'action-scheduler'));
}
$next->setTimezone($this->get_local_timezone());
return $next->format('Y-m-d H:i:s');
}
protected function get_local_timezone() {
return ActionScheduler_TimezoneHelper::get_local_timezone();
}
protected function save_post_array( $post_array ) { protected function save_post_array( $post_array ) {
add_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 ); add_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 );
$post_id = wp_insert_post($post_array); $post_id = wp_insert_post($post_array);
remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 ); remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10 );
if ( is_wp_error($post_id) || empty($post_id) ) { if ( is_wp_error($post_id) || empty($post_id) ) {
throw new RuntimeException(__('Unable to save action.', 'action-scheduler')); throw new RuntimeException(__('Unable to save action.', 'action-scheduler'));
@@ -93,7 +71,7 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
public function fetch_action( $action_id ) { public function fetch_action( $action_id ) {
$post = $this->get_post( $action_id ); $post = $this->get_post( $action_id );
if ( empty($post) || $post->post_type != self::POST_TYPE || $post->post_status == 'trash' ) { if ( empty($post) || $post->post_type != self::POST_TYPE ) {
return $this->get_null_action(); return $this->get_null_action();
} }
return $this->make_action_from_post($post); return $this->make_action_from_post($post);
@@ -119,12 +97,59 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
} }
$group = wp_get_object_terms( $post->ID, self::GROUP_TAXONOMY, array('fields' => 'names') ); $group = wp_get_object_terms( $post->ID, self::GROUP_TAXONOMY, array('fields' => 'names') );
$group = empty( $group ) ? '' : reset($group); $group = empty( $group ) ? '' : reset($group);
if ( $post->post_status == 'pending' ) {
$action = new ActionScheduler_Action( $hook, $args, $schedule, $group ); return ActionScheduler::factory()->get_stored_action( $this->get_action_status_by_post_status( $post->post_status ), $hook, $args, $schedule, $group );
} else { }
$action = new ActionScheduler_FinishedAction( $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;
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;
} }
/** /**
@@ -157,23 +182,21 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
$query .= " AND p.post_content=%s"; $query .= " AND p.post_content=%s";
$args[] = json_encode($params['args']); $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'] ) { switch ( $params['status'] ) {
case self::STATUS_COMPLETE: case self::STATUS_COMPLETE:
$query .= " AND p.post_status='publish'"; case self::STATUS_RUNNING:
case self::STATUS_FAILED:
$order = 'DESC'; // Find the most recent action that matches $order = 'DESC'; // Find the most recent action that matches
break; break;
case self::STATUS_PENDING: case self::STATUS_PENDING:
$query .= " AND p.post_status='pending'";
$order = 'ASC'; // Find the next action that matches
break;
case self::STATUS_RUNNING:
case self::STATUS_FAILED:
$query .= " AND p.post_status=%s";
$args[] = $params['status'];
$order = 'DESC'; // Find the most recent action that matches
break;
default: default:
$order = 'ASC'; $order = 'ASC'; // Find the next action that matches
break; break;
} }
$query .= " ORDER BY post_date_gmt $order LIMIT 1"; $query .= " ORDER BY post_date_gmt $order LIMIT 1";
@@ -185,10 +208,19 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
} }
/** /**
* @param array $query * Returns the SQL statement to query (or count) actions.
* @return array The IDs of actions matching the query *
* @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.
*/ */
public function query_actions( $query = array() ) { 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( $query = wp_parse_args( $query, array(
'hook' => '', 'hook' => '',
'args' => NULL, 'args' => NULL,
@@ -203,17 +235,23 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
'offset' => 0, 'offset' => 0,
'orderby' => 'date', 'orderby' => 'date',
'order' => 'ASC', 'order' => 'ASC',
'search' => '',
) ); ) );
/** @var wpdb $wpdb */ /** @var wpdb $wpdb */
global $wpdb; global $wpdb;
$sql = "SELECT p.ID FROM {$wpdb->posts} p"; $sql = ( 'count' === $select_or_count ) ? 'SELECT count(p.ID)' : 'SELECT p.ID ';
$sql .= "FROM {$wpdb->posts} p";
$sql_params = array(); $sql_params = array();
if ( !empty($query['group']) ) { if ( ! empty( $query['group'] ) || 'group' === $query['orderby'] ) {
$sql .= " INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID"; $sql .= " INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id=p.ID";
$sql .= " INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id"; $sql .= " INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id=tt.term_taxonomy_id";
$sql .= " INNER JOIN {$wpdb->terms} t ON tt.term_id=t.term_id AND t.slug=%s"; $sql .= " INNER JOIN {$wpdb->terms} t ON tt.term_id=t.term_id";
$sql_params[] = $query['group'];
if ( ! empty( $query['group'] ) ) {
$sql .= " AND t.slug=%s";
$sql_params[] = $query['group'];
}
} }
$sql .= " WHERE post_type=%s"; $sql .= " WHERE post_type=%s";
$sql_params[] = self::POST_TYPE; $sql_params[] = self::POST_TYPE;
@@ -226,16 +264,9 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
$sql_params[] = json_encode($query['args']); $sql_params[] = json_encode($query['args']);
} }
switch ( $query['status'] ) { if ( ! empty( $query['status'] ) ) {
case self::STATUS_COMPLETE: $sql .= " AND p.post_status=%s";
$sql .= " AND p.post_status='publish'"; $sql_params[] = $this->get_post_status_by_action_status( $query['status'] );
break;
case self::STATUS_PENDING:
case self::STATUS_RUNNING:
case self::STATUS_FAILED:
$sql .= " AND p.post_status=%s";
$sql_params[] = $query['status'];
break;
} }
if ( $query['date'] instanceof DateTime ) { if ( $query['date'] instanceof DateTime ) {
@@ -265,51 +296,97 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
$sql_params[] = $query['claimed']; $sql_params[] = $query['claimed'];
} }
switch ( $query['orderby'] ) { if ( ! empty( $query['search'] ) ) {
case 'hook': $sql .= " AND (p.post_title LIKE %s OR p.post_content LIKE %s OR p.post_password LIKE %s)";
$orderby = 'p.title'; for( $i = 0; $i < 3; $i++ ) {
break; $sql_params[] = sprintf( '%%%s%%', $query['search'] );
case 'group': }
$orderby = 't.name';
break;
case 'modified':
$orderby = 'p.post_modified';
break;
case 'date':
default:
$orderby = 'p.post_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'];
} }
$sql = $wpdb->prepare( $sql, $sql_params ); 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'];
}
}
$id = $wpdb->get_col($sql); return $wpdb->prepare( $sql, $sql_params );
return $id;
} }
private function validate_sql_comparator( $comp ) { /**
if ( in_array($comp, array('!=', '>', '>=', '<', '<=', '=')) ) { * @param array $query
return $comp; * @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 '=';
return $action_counts_by_status;
} }
/** /**
* @param string $action_id * @param string $action_id
* *
* @throws InvalidArgumentException * @throws InvalidArgumentException
* @return void
*/ */
public function cancel_action( $action_id ) { public function cancel_action( $action_id ) {
$post = get_post($action_id); $post = get_post($action_id);
@@ -359,15 +436,20 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
} }
/** /**
* @param int $max_actions * @param int $max_actions
* @param DateTime $before_date Jobs must be schedule before this date. Defaults to now. * @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 * @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 ){ public function stake_claim( $max_actions = 10, DateTime $before_date = null, $hooks = array(), $group = '' ) {
$claim_id = $this->generate_claim_id(); $claim_id = $this->generate_claim_id();
$this->claim_actions( $claim_id, $max_actions, $before_date ); $this->claim_actions( $claim_id, $max_actions, $before_date, $hooks, $group );
$action_ids = $this->find_actions_by_claim_id( $claim_id ); $action_ids = $this->find_actions_by_claim_id( $claim_id );
return new ActionScheduler_ActionClaim( $claim_id, $action_ids ); return new ActionScheduler_ActionClaim( $claim_id, $action_ids );
} }
@@ -389,25 +471,134 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
} }
/** /**
* @param string $claim_id * @param string $claim_id
* @param int $limit * @param int $limit
* @param DateTime $before_date Should use UTC timezone. * @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 * @return int The number of actions that were claimed
* @throws RuntimeException * @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 ) { 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 */ /** @var wpdb $wpdb */
global $wpdb; global $wpdb;
$date = is_null($before_date) ? as_get_datetime_object() : clone $before_date; /*
// can't use $wpdb->update() because of the <= condition, using post_modified to take advantage of indexes * Build up custom query to update the affected posts. Parameters are built as a separate array
$sql = "UPDATE {$wpdb->posts} SET post_password = %s, post_modified_gmt = %s, post_modified = %s WHERE post_type = %s AND post_status = %s AND post_password = '' AND post_date_gmt <= %s ORDER BY menu_order ASC, post_date_gmt ASC LIMIT %d"; * to make it easier to identify where they are in the query.
$sql = $wpdb->prepare( $sql, array( $claim_id, current_time('mysql', true), current_time('mysql'), self::POST_TYPE, 'pending', $date->format('Y-m-d H:i:s'), $limit ) ); *
$rows_affected = $wpdb->query($sql); * We can't use $wpdb->update() here because of the "ID IN ..." clause.
if ( $rows_affected === false ) { */
throw new RuntimeException(__('Unable to claim actions. Database error.', 'action-scheduler')); $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 ) );
} }
return (int)$rows_affected;
/*
* 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',
array(
'compare' => '<=',
'year' => $date->format( 'Y' ),
'month' => $date->format( 'n' ),
'day' => $date->format( 'j' ),
'hour' => $date->format( 'G' ),
'minute' => $date->format( 'i' ),
'second' => $date->format( 's' ),
),
),
'tax_query' => array(
array(
'taxonomy' => self::GROUP_TAXONOMY,
'field' => 'slug',
'terms' => $group,
'include_children' => false,
),
),
);
return $query->query( $query_args );
} }
/** /**
@@ -441,8 +632,6 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
/** /**
* @param string $action_id * @param string $action_id
*
* @return void
*/ */
public function unclaim_action( $action_id ) { public function unclaim_action( $action_id ) {
/** @var wpdb $wpdb */ /** @var wpdb $wpdb */
@@ -467,9 +656,39 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
} }
/** /**
* @param string $action_id * Return an action's claim ID, as stored in the post password column
* *
* @return void * @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 ) { public function log_execution( $action_id ) {
/** @var wpdb $wpdb */ /** @var wpdb $wpdb */
@@ -491,7 +710,7 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
'ID' => $action_id, 'ID' => $action_id,
'post_status' => 'publish', 'post_status' => 'publish',
), TRUE); ), TRUE);
remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10, 1 ); remove_filter( 'wp_insert_post_data', array( $this, 'filter_insert_post_data' ), 10 );
if ( is_wp_error($result) ) { if ( is_wp_error($result) ) {
throw new RuntimeException($result->get_error_message()); throw new RuntimeException($result->get_error_message());
} }
@@ -511,4 +730,3 @@ class ActionScheduler_wpPostStore extends ActionScheduler_Store {
$taxonomy_registrar->register(); $taxonomy_registrar->register();
} }
} }

View File

@@ -1,9 +1,12 @@
{ {
"name": "prospress/action-scheduler", "name": "prospress/action-scheduler",
"version": "1.5.3", "version": "2.0.0",
"description": "Action Scheduler for WordPress and WooCommerce", "description": "Action Scheduler for WordPress and WooCommerce",
"type": "wordpress-plugin", "type": "wordpress-plugin",
"license": "GPL-3.0", "license": "GPL-3.0",
"minimum-stability": "dev", "minimum-stability": "dev",
"require": {} "require": {},
"require-dev": {
"wp-cli/wp-cli": "^1.3"
}
} }

2909
includes/libraries/action-scheduler/composer.lock generated Executable file

File diff suppressed because it is too large Load Diff

View File

@@ -64,8 +64,6 @@ function wc_schedule_cron_action( $timestamp, $schedule, $hook, $args = array(),
* @param string $hook The hook that the job will trigger * @param string $hook The hook that the job will trigger
* @param array $args Args that would have been passed to the job * @param array $args Args that would have been passed to the job
* @param string $group * @param string $group
*
* @return void
*/ */
function wc_unschedule_action( $hook, $args = array(), $group = '' ) { function wc_unschedule_action( $hook, $args = array(), $group = '' ) {
$params = array(); $params = array();
@@ -174,15 +172,15 @@ function wc_get_scheduled_actions( $args = array(), $return_format = OBJECT ) {
* @param mixed $date_string A date/time string. Valid formats are explained in http://php.net/manual/en/datetime.formats.php * @param mixed $date_string A date/time string. Valid formats are explained in http://php.net/manual/en/datetime.formats.php
* @param string $timezone A timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available http://php.net/manual/en/timezones.php * @param string $timezone A timezone identifier, like UTC or Europe/Lisbon. The list of valid identifiers is available http://php.net/manual/en/timezones.php
* *
* @return DateTime * @return ActionScheduler_DateTime
*/ */
function as_get_datetime_object( $date_string = null, $timezone = 'UTC' ) { function as_get_datetime_object( $date_string = null, $timezone = 'UTC' ) {
if ( is_object($date_string) && $date_string instanceof DateTime ) { if ( is_object( $date_string ) && $date_string instanceof DateTime ) {
$date = $date_string->setTimezone(new DateTimeZone( $timezone ) ); $date = new ActionScheduler_DateTime( $date_string->format( 'Y-m-d H:i:s' ), new DateTimeZone( $timezone ) );
} elseif ( is_numeric( $date_string ) ) { } elseif ( is_numeric( $date_string ) ) {
$date = new DateTime( '@'.$date_string, new DateTimeZone( $timezone ) ); $date = new ActionScheduler_DateTime( '@' . $date_string, new DateTimeZone( $timezone ) );
} else { } else {
$date = new DateTime( $date_string, new DateTimeZone( $timezone ) ); $date = new ActionScheduler_DateTime( $date_string, new DateTimeZone( $timezone ) );
} }
return $date; return $date;
} }

View File

@@ -240,10 +240,10 @@ class CronExpression
$currentTime = new DateTime($currentTime); $currentTime = new DateTime($currentTime);
$currentTime->setTime($currentTime->format('H'), $currentTime->format('i'), 0); $currentTime->setTime($currentTime->format('H'), $currentTime->format('i'), 0);
$currentDate = $currentTime->format('Y-m-d H:i'); $currentDate = $currentTime->format('Y-m-d H:i');
$currentTime = (int)($currentTime->format('U')); $currentTime = (int)($currentTime->getTimestamp());
} }
return $this->getNextRunDate($currentDate, 0, true)->format('U') == $currentTime; return $this->getNextRunDate($currentDate, 0, true)->getTimestamp() == $currentTime;
} }
/** /**

View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@@ -1,339 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@@ -1,25 +0,0 @@
<?php
class TLC_Transient_Update_Server {
public function __construct() {
add_action( 'init', array( $this, 'init' ), 9999 );
}
public function init() {
if ( isset( $_POST['_tlc_update'] )
&& ( 0 === strpos( $_POST['_tlc_update'], 'tlc_lock_' ) )
&& isset( $_POST['key'] )
) {
$update = get_transient( 'tlc_up__' . md5( $_POST['key'] ) );
if ( $update && $update[0] == $_POST['_tlc_update'] ) {
tlc_transient( $update[1] )
->expires_in( $update[2] )
->extend_on_fail( $update[5] )
->updates_with( $update[3], (array) $update[4] )
->set_lock( $update[0] )
->fetch_and_cache();
}
exit();
}
}
}

View File

@@ -1,146 +0,0 @@
<?php
class TLC_Transient {
public $key;
public $raw_key;
private $lock;
private $callback;
private $params;
private $expiration = 0;
private $extend_on_fail = 0;
private $force_background_updates = false;
public function __construct( $key ) {
$this->raw_key = $key;
$this->key = md5( $key );
}
public function get() {
$data = $this->raw_get();
if ( false === $data ) {
// Hard expiration
if ( $this->force_background_updates ) {
// In this mode, we never do a just-in-time update
// We return false, and schedule a fetch on shutdown
$this->schedule_background_fetch();
return false;
}
else {
// Bill O'Reilly mode: "We'll do it live!"
return $this->fetch_and_cache();
}
}
else {
// Soft expiration
if ( $data[0] !== 0 && $data[0] < time() )
$this->schedule_background_fetch();
return $data[1];
}
}
private function raw_get() {
return get_transient( 'tlc__' . $this->key );
}
private function schedule_background_fetch() {
if ( ! $this->has_update_lock() ) {
set_transient( 'tlc_up__' . $this->key, array( $this->new_update_lock(), $this->raw_key, $this->expiration, $this->callback, $this->params, $this->extend_on_fail ), 300 );
add_action( 'shutdown', array( $this, 'spawn_server' ) );
}
return $this;
}
private function has_update_lock() {
return (bool) $this->get_update_lock();
}
private function get_update_lock() {
$lock = get_transient( 'tlc_up__' . $this->key );
if ( $lock )
return $lock[0];
else
return false;
}
private function new_update_lock() {
$this->lock = uniqid( 'tlc_lock_', true );
return $this->lock;
}
public function fetch_and_cache() {
// If you don't supply a callback, we can't update it for you!
if ( empty( $this->callback ) )
return false;
if ( $this->has_update_lock() && ! $this->owns_update_lock() )
return; // Race... let the other process handle it
try {
$data = call_user_func_array( $this->callback, $this->params );
$this->set( $data );
} catch ( Exception $e ) {
if ( $this->extend_on_fail > 0 ) {
$data = $this->raw_get();
if ( $data ) {
$data = $data[1];
$old_expiration = $this->expiration;
$this->expiration = $this->extend_on_fail;
$this->set( $data );
$this->expiration = $old_expiration;
}
}
else {
$data = false;
}
}
$this->release_update_lock();
return $data;
}
private function owns_update_lock() {
return $this->lock == $this->get_update_lock();
}
public function set( $data ) {
// We set the timeout as part of the transient data.
// The actual transient has a far-future TTL. This allows for soft expiration.
$expiration = ( $this->expiration > 0 ) ? time() + $this->expiration : 0;
$transient_expiration = ( $this->expiration > 0 ) ? $this->expiration + 31536000 : 0; // 31536000 = 60*60*24*365 ~= one year
set_transient( 'tlc__' . $this->key, array( $expiration, $data ), $transient_expiration );
return $this;
}
private function release_update_lock() {
delete_transient( 'tlc_up__' . $this->key );
}
public function spawn_server() {
$server_url = home_url( '/?tlc_transients_request' );
wp_remote_post( $server_url, array( 'body' => array( '_tlc_update' => $this->lock, 'key' => $this->raw_key ), 'timeout' => 0.01, 'blocking' => false, 'sslverify' => apply_filters( 'https_local_ssl_verify', true ) ) );
}
public function updates_with( $callback, $params = array() ) {
$this->callback = $callback;
if ( is_array( $params ) )
$this->params = $params;
return $this;
}
public function expires_in( $seconds ) {
$this->expiration = (int) $seconds;
return $this;
}
public function extend_on_fail( $seconds ) {
$this->extend_on_fail = (int) $seconds;
return $this;
}
public function set_lock( $lock ) {
$this->lock = $lock;
return $this;
}
public function background_only() {
$this->force_background_updates = true;
return $this;
}
}

View File

@@ -1,21 +0,0 @@
{
"name" : "markjaquith/wp-tlc-transients",
"description": "A WP transients interface with support for soft-expiration, background updating of the transients.",
"keywords" : ["wordpress", "cache"],
"homepage" : "https://github.com/markjaquith/WP-TLC-Transients",
"license" : "GPL-2.0+",
"authors" : [
{
"name" : "Mark Jaquith",
"homepage": "http://markjaquith.com/"
}
],
"support" : {
"issues": "https://github.com/markjaquith/WP-TLC-Transients/issues",
"source": "https://github.com/markjaquith/WP-TLC-Transients"
},
"autoload" : {
"classmap": ["class-tlc-transient.php", "class-tlc-transient-update-server.php"],
"files" : ["functions.php"]
}
}

View File

@@ -1,9 +0,0 @@
<?php
// API so you don't have to use "new"
if ( !function_exists( 'tlc_transient' ) ) {
function tlc_transient( $key ) {
$transient = new TLC_Transient( $key );
return $transient;
}
}

View File

@@ -1,33 +0,0 @@
<?php
if ( ! class_exists( 'TLC_Transient_Update_Server' ) )
require_once dirname( __FILE__ ) . '/class-tlc-transient-update-server.php';
new TLC_Transient_Update_Server;
if ( ! class_exists( 'TLC_Transient' ) )
require_once dirname( __FILE__ ) . '/class-tlc-transient.php';
require_once dirname( __FILE__ ) . '/functions.php';
// Example:
/*
function sample_fetch_and_append( $url, $append ) {
$f = wp_remote_retrieve_body( wp_remote_get( $url, array( 'timeout' => 30 ) ) );
$f .= $append;
return $f;
}
function test_tlc_transient() {
$t = tlc_transient( 'foo' )
->expires_in( 30 )
->background_only()
->updates_with( 'sample_fetch_and_append', array( 'http://coveredwebservices.com/tools/long-running-request.php', ' appendfooparam ' ) )
->get();
var_dump( $t );
if ( !$t )
echo "The request is false, because it isn't yet in the cache. It'll be there in about 10 seconds. Keep refreshing!";
}
add_action( 'wp_footer', 'test_tlc_transient' );
*/

View File

@@ -30,6 +30,8 @@ class WCS_Retry_Admin {
// Display the number of retries in the Orders list table // Display the number of retries in the Orders list table
add_action( 'manage_shop_order_posts_custom_column', __CLASS__ . '::add_column_content', 20, 2 ); add_action( 'manage_shop_order_posts_custom_column', __CLASS__ . '::add_column_content', 20, 2 );
add_filter( 'wcs_system_status', array( $this, 'add_system_status_content' ) );
} }
} }
@@ -141,4 +143,51 @@ class WCS_Retry_Admin {
return $settings; return $settings;
} }
/**
* Add system status information about custom retry rules.
*
* @param array $data
* @return array
*/
public static function add_system_status_content( $data ) {
$has_custom_retry_rules = has_action( 'wcs_default_retry_rules' );
$has_custom_retry_rule_class = has_action( 'wcs_retry_rule_class' );
$has_custom_raw_retry_rule = has_action( 'wcs_get_retry_rule_raw' );
$has_custom_retry_rule = has_action( 'wcs_get_retry_rule' );
$data['wcs_retry_rules_overridden'] = array(
'name' => _x( 'Custom Retry Rules', 'label for the system status page', 'woocommerce-subscriptions' ),
'label' => 'Custom Retry Rules',
'mark_icon' => $has_custom_retry_rules ? 'warning' : 'yes',
'note' => $has_custom_retry_rules ? 'Yes' : 'No',
'success' => ! $has_custom_retry_rules,
);
$data['wcs_retry_rule_class_overridden'] = array(
'name' => _x( 'Custom Retry Rule Class', 'label for the system status page', 'woocommerce-subscriptions' ),
'label' => 'Custom Retry Rule Class',
'mark_icon' => $has_custom_retry_rule_class ? 'warning' : 'yes',
'note' => $has_custom_retry_rule_class ? 'Yes' : 'No',
'success' => ! $has_custom_retry_rule_class,
);
$data['wcs_raw_retry_rule_overridden'] = array(
'name' => _x( 'Custom Raw Retry Rule', 'label for the system status page', 'woocommerce-subscriptions' ),
'label' => 'Custom Raw Retry Rule',
'mark_icon' => $has_custom_raw_retry_rule ? 'warning' : 'yes',
'note' => $has_custom_raw_retry_rule ? 'Yes' : 'No',
'success' => ! $has_custom_raw_retry_rule,
);
$data['wcs_retry_rule_overridden'] = array(
'name' => _x( 'Custom Retry Rule', 'label for the system status page', 'woocommerce-subscriptions' ),
'label' => 'Custom Retry Rule',
'mark_icon' => $has_custom_retry_rule ? 'warning' : 'yes',
'note' => $has_custom_retry_rule ? 'Yes' : 'No',
'success' => ! $has_custom_retry_rule,
);
return $data;
}
} }

View File

@@ -30,6 +30,11 @@ class WC_Subscriptions_Upgrader {
public static $updated_to_wc_2_0; public static $updated_to_wc_2_0;
/**
* @var array An array of WCS_Background_Updater objects used to run upgrade scripts in the background.
*/
protected static $background_updaters = array();
/** /**
* Hooks upgrade function to init. * Hooks upgrade function to init.
* *
@@ -92,6 +97,13 @@ class WC_Subscriptions_Upgrader {
add_action( 'wcs_repair_end_of_prepaid_term_actions', __CLASS__ . '::repair_end_of_prepaid_term_actions' ); add_action( 'wcs_repair_end_of_prepaid_term_actions', __CLASS__ . '::repair_end_of_prepaid_term_actions' );
add_action( 'wcs_repair_subscriptions_containing_synced_variations', __CLASS__ . '::repair_subscription_contains_sync_meta' ); add_action( 'wcs_repair_subscriptions_containing_synced_variations', __CLASS__ . '::repair_subscription_contains_sync_meta' );
// When WC is updated from a version prior to 3.0 to a version after 3.0, add subscription address indexes. Must be hooked on before WC runs its updates, which occur on priority 5.
add_action( 'init', array( __CLASS__, 'maybe_add_subscription_address_indexes' ), 2 );
add_action( 'admin_notices', array( __CLASS__, 'maybe_add_downgrade_notice' ) );
add_action( 'init', array( __CLASS__, 'initialise_background_updaters' ), 0 );
} }
/** /**
@@ -200,6 +212,16 @@ class WC_Subscriptions_Upgrader {
WCS_Upgrade_2_2_9::schedule_repair(); WCS_Upgrade_2_2_9::schedule_repair();
} }
// Repair subscriptions suspended via PayPal.
if ( version_compare( self::$active_version, '2.1.4', '>=' ) && version_compare( self::$active_version, '2.3.0', '<' ) ) {
self::$background_updaters['2.3']['suspended_paypal_repair']->schedule_repair();
}
// If the store is running WC 3.0, repair subscriptions with missing address indexes.
if ( '0' !== self::$active_version && version_compare( self::$active_version, '2.3.0', '<' ) && version_compare( WC()->version, '3.0', '>=' ) ) {
self::$background_updaters['2.3']['address_indexes_repair']->schedule_repair();
}
self::upgrade_complete(); self::upgrade_complete();
} }
@@ -766,6 +788,65 @@ class WC_Subscriptions_Upgrader {
WCS_Upgrade_2_2_9::repair_subscriptions_containing_synced_variations(); WCS_Upgrade_2_2_9::repair_subscriptions_containing_synced_variations();
} }
/**
* Display an admin notice if the database version is greater than the active version of the plugin by at least one minor release (eg 1.1 and 1.0).
*
* @since 2.3.0
*/
public static function maybe_add_downgrade_notice() {
// If there's no downgrade, exit early. self::$active_version is a bit of a misnomer here but in an upgrade context it refers to the database version of the plugin.
if ( ! version_compare( wcs_get_minor_version_string( self::$active_version ), wcs_get_minor_version_string( WC_Subscriptions::$version ), '>' ) ) {
return;
}
$admin_notice = new WCS_Admin_Notice( 'error' );
$admin_notice->set_simple_content( sprintf( esc_html__( '%1$sWarning!%2$s It appears that you have downgraded %1$sWooCommerce Subscriptions%2$s from %3$s to %4$s. Downgrading the plugin in this way may cause issues. Please update to %3$s or higher, or %5$sopen a new support ticket%6$s for further assistance.', 'woocommerce-subscriptions' ),
'<strong>', '</strong>',
'<code>' . self::$active_version . '</code>',
'<code>' . WC_Subscriptions::$version . '</code>',
'<a href="https://woocommerce.com/my-account/marketplace-ticket-form/" target="_blank">', '</a>'
) );
$admin_notice->display();
}
/**
* When updating WC to a version after 3.0 from a version prior to 3.0, schedule the repair script to add address indexes.
*
* @since 2.3.0
*/
public static function maybe_add_subscription_address_indexes() {
$woocommerce_active_version = WC()->version;
$woocommerce_database_version = get_option( 'woocommerce_version' );
if ( $woocommerce_active_version !== $woocommerce_database_version && version_compare( $woocommerce_active_version, '3.0', '>=' ) && version_compare( $woocommerce_database_version, '3.0', '<' ) ) {
self::$background_updaters['2.3']['address_indexes_repair']->schedule_repair();
}
}
/**
* Load and initialise the background updaters.
*
* @since 2.3.0
*/
public static function initialise_background_updaters() {
$logger = new WC_logger();
include_once( dirname( __FILE__ ) . '/class-wcs-repair-suspended-paypal-subscriptions.php' );
include_once( dirname( __FILE__ ) . '/class-wcs-repair-subscription-address-indexes.php' );
self::$background_updaters['2.3']['suspended_paypal_repair'] = new WCS_Repair_Suspended_PayPal_Subscriptions( $logger );
self::$background_updaters['2.3']['address_indexes_repair'] = new WCS_Repair_Subscription_Address_Indexes( $logger );
// Init the updaters
foreach ( self::$background_updaters as $version => $updaters ) {
foreach ( $updaters as $updater ) {
$updater->init();
}
}
}
/** /**
* Used to check if a user ID is greater than the last user upgraded to version 1.4. * Used to check if a user ID is greater than the last user upgraded to version 1.4.
* *

View File

@@ -0,0 +1,75 @@
<?php
/**
* Repair subscriptions that have missing address indexes.
*
* Post WooCommerce Subscriptions 2.3 address indexes are used when searching via the admin subscriptions table.
* Subscriptions created prior to WC 3.0 won't have those meta keys set and so this repair script will generate them.
*
* @author Prospress
* @category Admin
* @package WooCommerce Subscriptions/Admin/Upgrades
* @version 2.3.0
*/
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class WCS_Repair_Subscription_Address_Indexes extends WCS_Background_Upgrader {
/**
* Constructor
*
* @param WC_Logger $logger The WC_Logger instance.
* @since 2.3.0
*/
public function __construct( WC_Logger $logger ) {
$this->scheduled_hook = 'wcs_add_missing_subscription_address_indexes';
$this->log_handle = 'wcs-add-subscription-address-indexes';
$this->logger = $logger;
}
/**
* Update a subscription, setting its address indexes.
*
* @since 2.3.0
*/
protected function update_item( $subscription_id ) {
try {
$subscription = wcs_get_subscription( $subscription_id );
if ( false === $subscription ) {
throw new Exception( 'Failed to instantiate subscription object' );
}
// Saving the subscription sets the address indexes if they don't exist.
$subscription->save();
$this->log( sprintf( 'Subscription ID %d address index(es) added.', $subscription_id ) );
} catch ( Exception $e ) {
$this->log( sprintf( '--- Exception caught repairing subscription %d - exception message: %s ---', $subscription_id, $e->getMessage() ) );
}
}
/**
* Get a batch of subscriptions which need address indexes.
*
* @since 2.3.0
* @return array A list of subscription ids which need address indexes.
*/
protected function get_items_to_update() {
return get_posts( array(
'post_type' => 'shop_subscription',
'posts_per_page' => 20,
'post_status' => 'any',
'fields' => 'ids',
'meta_query' => array(
array(
'key' => '_billing_address_index',
'compare' => 'NOT EXISTS',
),
),
) );
}
}

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