woocommerce-subscriptions/includes/class-wcs-cart-renewal.php

1212 lines
46 KiB
PHP

<?php
/**
* Implement renewing to a subscription via the cart.
*
* For manual renewals and the renewal of a subscription after a failed automatic payment, the customer must complete
* the renewal via checkout in order to pay for the renewal. This class handles that.
*
* @package WooCommerce Subscriptions
* @subpackage WCS_Cart_Renewal
* @category Class
* @author Prospress
* @since 2.0
*/
class WCS_Cart_Renewal {
/* The flag used to indicate if a cart item is a renewal */
public $cart_item_key = 'subscription_renewal';
/**
* Bootstraps the class and hooks required actions & filters.
*
* @since 2.0
*/
public function __construct() {
$this->setup_hooks();
// Attach hooks which depend on WooCommerce constants
add_action( 'woocommerce_loaded', array( &$this, 'attach_dependant_hooks' ), 10 );
// Set URL parameter for manual subscription renewals
add_filter( 'woocommerce_get_checkout_payment_url', array( &$this, 'get_checkout_payment_url' ), 10, 2 );
// Remove order action buttons from the My Account page
add_filter( 'woocommerce_my_account_my_orders_actions', array( &$this, 'filter_my_account_my_orders_actions' ), 10, 2 );
// When a failed renewal order is paid for via checkout, make sure WC_Checkout::create_order() preserves its "failed" status until it is paid
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
add_filter( 'woocommerce_create_order', array( &$this, 'set_renewal_order_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
add_filter( 'woocommerce_login_redirect', array( &$this, 'maybe_redirect_after_login' ), 10 , 1 );
// Once we have finished updating the renewal order on checkout, update the session cart so the cart changes are honoured.
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 );
}
/**
* Attach WooCommerce version dependent hooks
*
* @since 2.2.0
*/
public function attach_dependant_hooks() {
if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) {
// When a renewal order's line items are being updated, update the line item IDs stored in cart data.
add_action( 'woocommerce_add_order_item_meta', array( &$this, 'update_line_item_cart_data' ), 10, 3 );
add_filter( 'woocommerce_checkout_update_customer_data', array( &$this, 'maybe_update_subscription_customer_data' ), 10, 2 );
} else {
// For order items created as part of a renewal, keep a record of the cart item key so that we can match it later once the order item has been saved and has an ID
add_action( 'woocommerce_checkout_create_order_line_item', array( &$this, 'add_line_item_meta' ), 10, 3 );
// After order meta is saved, get the order line item ID for the renewal so we can update it later
add_action( 'woocommerce_checkout_update_order_meta', array( &$this, 'set_order_item_id' ), 10, 2 );
// Don't display cart item key meta stored above on the Edit Order screen
add_action( 'woocommerce_hidden_order_itemmeta', array( &$this, 'hidden_order_itemmeta' ), 10 );
// Update customer's address on the subscription if it is changed during renewal
add_filter( 'woocommerce_checkout_update_user_meta', array( &$this, 'maybe_update_subscription_address_data' ), 10, 2 );
}
}
/**
* Bootstraps the class and hooks required actions & filters.
*
* @since 2.0
*/
public function setup_hooks() {
// Make sure renewal meta data persists between sessions
add_filter( 'woocommerce_get_cart_item_from_session', array( &$this, 'get_cart_item_from_session' ), 10, 3 );
add_action( 'woocommerce_cart_loaded_from_session', array( &$this, 'cart_items_loaded_from_session' ), 10 );
// Make sure fees are added to the cart
add_action( 'woocommerce_cart_calculate_fees', array( &$this, 'maybe_add_fees' ), 10, 1 );
// Check if a user is requesting to create a renewal order for a subscription, needs to happen after $wp->query_vars are set
add_action( 'template_redirect', array( &$this, 'maybe_setup_cart' ), 100 );
// Apply renewal discounts as pseudo coupons
add_action( 'wcs_after_renewal_setup_cart_subscription', array( &$this, 'maybe_setup_discounts' ), 10, 1 );
add_filter( 'woocommerce_get_shop_coupon_data', array( &$this, 'renewal_coupon_data' ), 10, 2 );
add_action( 'wcs_before_renewal_setup_cart_subscriptions', array( &$this, 'clear_coupons' ), 10 );
add_action( 'woocommerce_remove_cart_item', array( &$this, 'maybe_remove_items' ), 10, 1 );
add_action( 'woocommerce_before_cart_item_quantity_zero', array( &$this, 'maybe_remove_items' ), 10, 1 );
add_action( 'woocommerce_cart_emptied', array( &$this, 'clear_coupons' ), 10 );
add_filter( 'woocommerce_cart_item_removed_title', array( &$this, 'items_removed_title' ), 10, 2 );
add_action( 'woocommerce_cart_item_restored', array( &$this, 'maybe_restore_items' ), 10, 1 );
// Use original order price when resubscribing to products with addons (to ensure the adds on prices are included)
add_filter( 'woocommerce_product_addons_adjust_price', array( &$this, 'product_addons_adjust_price' ), 10, 2 );
// When loading checkout address details, use the renewal order address details for renewals
add_filter( 'woocommerce_checkout_get_value', array( &$this, 'checkout_get_value' ), 10, 2 );
// If the shipping address on a renewal order differs to the order's billing address, check the "Ship to different address" automatically to make sure the renewal order's fields are used by default
add_filter( 'woocommerce_ship_to_different_address_checked', array( &$this, 'maybe_check_ship_to_different_address' ), 100, 1 );
}
/**
* Check if a payment is being made on a renewal order from 'My Account'. If so,
* redirect the order into a cart/checkout payment flow so that the customer can
* choose payment method, apply discounts set shipping and pay for the order.
*
* @since 2.0
*/
public function maybe_setup_cart() {
global $wp;
if ( isset( $_GET['pay_for_order'] ) && isset( $_GET['key'] ) && isset( $wp->query_vars['order-pay'] ) ) {
// Pay for existing order
$order_key = $_GET['key'];
$order_id = ( isset( $wp->query_vars['order-pay'] ) ) ? $wp->query_vars['order-pay'] : absint( $_GET['order_id'] );
$order = wc_get_order( $wp->query_vars['order-pay'] );
if ( wcs_get_objects_property( $order, 'order_key' ) == $order_key && $order->has_status( array( 'pending', 'failed' ) ) && wcs_order_contains_renewal( $order ) ) {
// If a user isn't logged in, allow them to login first and then redirect back
if ( ! is_user_logged_in() ) {
$redirect = add_query_arg( array(
'wcs_redirect' => 'pay_for_order',
'wcs_redirect_id' => $order_id,
), get_permalink( wc_get_page_id( 'myaccount' ) ) );
wp_safe_redirect( $redirect );
exit;
} elseif ( ! current_user_can( 'pay_for_order', $order_id ) ) {
wc_add_notice( __( 'That doesn\'t appear to be your order.', 'woocommerce-subscriptions' ), 'error' );
wp_safe_redirect( get_permalink( wc_get_page_id( 'myaccount' ) ) );
exit;
}
$subscriptions = wcs_get_subscriptions_for_renewal_order( $order );
do_action( 'wcs_before_renewal_setup_cart_subscriptions', $subscriptions, $order );
foreach ( $subscriptions as $subscription ) {
do_action( 'wcs_before_renewal_setup_cart_subscription', $subscription, $order );
// Add the existing subscription items to the cart
$this->setup_cart( $order, array(
'subscription_id' => $subscription->get_id(),
'renewal_order_id' => $order_id,
) );
do_action( 'wcs_after_renewal_setup_cart_subscription', $subscription, $order );
}
do_action( 'wcs_after_renewal_setup_cart_subscriptions', $subscriptions, $order );
if ( WC()->cart->cart_contents_count != 0 ) {
// Store renewal order's ID in session so it can be re-used after payment
WC()->session->set( 'order_awaiting_payment', $order_id );
wc_add_notice( __( 'Complete checkout to renew your subscription.', 'woocommerce-subscriptions' ), 'success' );
}
wp_safe_redirect( WC()->cart->get_checkout_url() );
exit;
}
}
}
/**
* Set up cart item meta data to complete a subscription renewal via the cart.
*
* @since 2.2.0
* @version 2.2.6
*/
protected function setup_cart( $subscription, $cart_item_data ) {
WC()->cart->empty_cart( true );
$success = true;
foreach ( $subscription->get_items() as $item_id => $line_item ) {
$variations = array();
$item_data = array();
// Load all product info including variation data
if ( WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) {
$product_id = (int) $line_item['product_id'];
$quantity = (int) $line_item['qty'];
$variation_id = (int) $line_item['variation_id'];
$item_name = $line_item['name'];
foreach ( $line_item['item_meta'] as $meta_name => $meta_value ) {
if ( taxonomy_is_product_attribute( $meta_name ) ) {
$variations[ $meta_name ] = $meta_value[0];
} elseif ( meta_is_product_attribute( $meta_name, $meta_value[0], $product_id ) ) {
$variations[ $meta_name ] = $meta_value[0];
}
}
} else {
$product_id = $line_item->get_product_id();
$quantity = $line_item->get_quantity();
$variation_id = $line_item->get_variation_id();
$item_name = $line_item->get_name();
foreach ( $line_item->get_meta_data() as $meta ) {
if ( taxonomy_is_product_attribute( $meta->key ) ) {
$variations[ $meta->key ] = $meta->value;
} elseif ( meta_is_product_attribute( $meta->key, $meta->value, $product_id ) ) {
$variations[ $meta->key ] = $meta->value;
}
}
}
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id', $product_id );
$product = wc_get_product( $product_id );
// The notice displayed when a subscription product has been deleted and the custoemr attempts to manually renew or make a renewal payment for a failed recurring payment for that product/subscription
// translators: placeholder is an item name
$product_deleted_error_message = apply_filters( 'woocommerce_subscriptions_renew_deleted_product_error_message', __( 'The %s product has been deleted and can no longer be renewed. Please choose a new product or contact us for assistance.', 'woocommerce-subscriptions' ) );
// Display error message for deleted products
if ( false === $product ) {
wc_add_notice( sprintf( $product_deleted_error_message, $item_name ), 'error' );
// Make sure we don't actually need the variation ID (if the product was a variation, it will have a variation ID; however, if the product has changed from a simple subscription to a variable subscription, there will be no variation_id)
} elseif ( $product->is_type( array( 'variable-subscription' ) ) && ! empty( $variation_id ) ) {
$variation = wc_get_product( $variation_id );
// Display error message for deleted product variations
if ( false === $variation ) {
wc_add_notice( sprintf( $product_deleted_error_message, $item_name ), 'error' );
}
}
$cart_item_data['line_item_id'] = $item_id;
$item_data = apply_filters( 'woocommerce_order_again_cart_item_data', array( $this->cart_item_key => $cart_item_data ), $line_item, $subscription );
if ( ! apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations, $item_data ) ) {
continue;
}
$cart_item_key = WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variations, $item_data );
$success = $success && (bool) $cart_item_key;
}
// If a product linked to a subscription failed to be added to the cart prevent partially paying for the order by removing all cart items.
if ( ! $success && wcs_is_subscription( $subscription ) ) {
// translators: %s is subscription's number
wc_add_notice( sprintf( esc_html__( 'Subscription #%s has not been added to the cart.', 'woocommerce-subscriptions' ), $subscription->get_order_number() ) , 'error' );
WC()->cart->empty_cart( true );
}
do_action( 'woocommerce_setup_cart_for_' . $this->cart_item_key, $subscription, $cart_item_data );
}
/**
* 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
* @since 2.0.10
*/
public function maybe_setup_discounts( $subscription ) {
if ( wcs_is_subscription( $subscription ) ) {
$used_coupons = $subscription->get_used_coupons();
$subscription_discount = wcs_get_objects_property( $subscription, 'cart_discount' );
// Add any used coupon discounts to the cart (as best we can) using our pseudo renewal coupons
if ( ! empty( $used_coupons ) ) {
$coupon_items = $subscription->get_items( 'coupon' );
foreach ( $coupon_items as $coupon_item ) {
$coupon = new WC_Coupon( $coupon_item['name'] );
$coupon_type = wcs_get_coupon_property( $coupon, 'discount_type' );
$coupon_code = '';
// If the coupon still exists we can use the existing/available coupon properties
if ( true === wcs_get_coupon_property( $coupon, 'exists' ) ) {
// But we only want to handle recurring coupons that have been applied to the subscription
if ( in_array( $coupon_type, array( 'recurring_percent', 'recurring_fee' ) ) ) {
// Set the coupon type to be a renewal equivalent for correct validation and calculations
if ( 'recurring_percent' == $coupon_type ) {
wcs_set_coupon_property( $coupon, 'discount_type', 'renewal_percent' );
} elseif ( 'recurring_fee' == $coupon_type ) {
wcs_set_coupon_property( $coupon, 'discount_type', 'renewal_fee' );
}
// Adjust coupon code to reflect that it is being applied to a renewal
$coupon_code = wcs_get_coupon_property( $coupon, 'code' );
}
} else {
// If the coupon doesn't exist we can only really apply the discount amount we know about - so we'll apply a cart style pseudo coupon and then set the amount
wcs_set_coupon_property( $coupon, 'discount_type', 'renewal_cart' );
wcs_set_coupon_property( $coupon, 'coupon_amount', $coupon_item['item_meta']['discount_amount']['0'] );
// Adjust coupon code to reflect that it is being applied to a renewal
$coupon_code = wcs_get_coupon_property( $coupon, 'code' );
}
// Now that we have a coupon we know we want to apply
if ( ! empty( $coupon_code ) ) {
// Set renewal order products as the product ids on the coupon
if ( ! WC_Subscriptions::is_woocommerce_pre( '2.5' ) ) {
wcs_set_coupon_property( $coupon, 'product_ids', $this->get_products( $subscription ) );
}
// Store the coupon info for later
$this->store_coupon( $subscription->get_id(), $coupon );
// Add the coupon to the cart - the actually coupon values / data are grabbed when needed later
if ( WC()->cart && ! WC()->cart->has_discount( $coupon_code ) ) {
WC()->cart->add_discount( $coupon_code );
}
}
}
// If there are no coupons but there is still a discount (i.e. it might have been manually added), we need to account for that as well
} elseif ( ! empty( $subscription_discount ) ) {
$coupon = new WC_Coupon( 'discount_renewal' );
// Apply our cart style pseudo coupon and the set the amount
wcs_set_coupon_property( $coupon, 'discount_type', 'renewal_cart' );
wcs_set_coupon_property( $coupon, 'coupon_amount', $subscription_discount );
// Set renewal order products as the product ids on the coupon
if ( ! WC_Subscriptions::is_woocommerce_pre( '2.5' ) ) {
wcs_set_coupon_property( $coupon, 'product_ids', $this->get_products( $subscription ) );
}
// Store the coupon info for later
$this->store_coupon( $subscription->get_id(), $coupon );
// Add the coupon to the cart
if ( WC()->cart && ! WC()->cart->has_discount( 'discount_renewal' ) ) {
WC()->cart->add_discount( 'discount_renewal' );
}
}
}
}
/**
* Does some housekeeping. Fires after the items have been passed through the get items from session filter. Because
* that filter is not good for removing cart items, we need to work around that by doing it later, in the cart
* loaded from session action.
*
* This checks cart items whether underlying subscriptions / renewal orders they depend exist. If not, they are
* removed from the cart.
*
* @param $cart WC_Cart the one we got from session
*/
public function cart_items_loaded_from_session( $cart ) {
$removed_count_subscription = $removed_count_order = 0;
foreach ( $cart->cart_contents as $key => $item ) {
if ( isset( $item[ $this->cart_item_key ]['subscription_id'] ) && ! wcs_is_subscription( $item[ $this->cart_item_key ]['subscription_id'] ) ) {
$cart->remove_cart_item( $key );
$removed_count_subscription++;
continue;
}
if ( isset( $item[ $this->cart_item_key ]['renewal_order_id'] ) && ! 'shop_order' == get_post_type( $item[ $this->cart_item_key ]['renewal_order_id'] ) ) {
$cart->remove_cart_item( $key );
$removed_count_order++;
continue;
}
}
if ( $removed_count_subscription ) {
$error_message = esc_html( _n( 'We couldn\'t find the original subscription for an item in your cart. The item was removed.', 'We couldn\'t find the original subscriptions for items in your cart. The items were removed.', $removed_count_subscription, 'woocommerce-subscriptions' ) );
if ( ! wc_has_notice( $error_message, 'notice' ) ) {
wc_add_notice( $error_message, 'notice' );
}
}
if ( $removed_count_order ) {
$error_message = esc_html( _n( 'We couldn\'t find the original renewal order for an item in your cart. The item was removed.', 'We couldn\'t find the original renewal orders for items in your cart. The items were removed.', $removed_count_order, 'woocommerce-subscriptions' ) );
if ( ! wc_has_notice( $error_message, 'notice' ) ) {
wc_add_notice( $error_message, 'notice' );
}
}
}
/**
* Restore renewal flag when cart is reset and modify Product object with renewal order related info
*
* @since 2.0
*/
public function get_cart_item_from_session( $cart_item_session_data, $cart_item, $key ) {
if ( isset( $cart_item[ $this->cart_item_key ]['subscription_id'] ) ) {
$cart_item_session_data[ $this->cart_item_key ] = $cart_item[ $this->cart_item_key ];
$_product = $cart_item_session_data['data'];
// Need to get the original subscription or order price, not the current price
$subscription = $this->get_order( $cart_item );
if ( $subscription ) {
$subscription_items = $subscription->get_items();
$item_to_renew = $subscription_items[ $cart_item_session_data[ $this->cart_item_key ]['line_item_id'] ];
$price = $item_to_renew['line_subtotal'];
if ( wc_prices_include_tax() ) {
if ( apply_filters( 'woocommerce_adjust_non_base_location_prices', true ) ) {
$base_tax_rates = WC_Tax::get_base_tax_rates( wcs_get_objects_property( $_product, 'tax_class' ) );
} else {
$base_tax_rates = WC_Tax::get_rates( wcs_get_objects_property( $_product, 'tax_class' ) );
}
$base_taxes_on_item = WC_Tax::calc_tax( $price, $base_tax_rates, false, false );
$price += array_sum( $base_taxes_on_item );
}
$_product->set_price( $price / $item_to_renew['qty'] );
// Don't carry over any sign up fee
wcs_set_objects_property( $_product, 'subscription_sign_up_fee', 0, 'set_prop_only' );
// Allow plugins to add additional strings to the product name for renewals
$line_item_name = is_callable( $item_to_renew, 'get_name' ) ? $item_to_renew->get_name() : $item_to_renew['name'];
wcs_set_objects_property( $_product, 'name', apply_filters( 'woocommerce_subscriptions_renewal_product_title', $line_item_name, $_product ), 'set_prop_only' );
// Make sure the same quantity is renewed
$cart_item_session_data['quantity'] = $item_to_renew['qty'];
}
}
return $cart_item_session_data;
}
/**
* Returns address details from the renewal order if the checkout is for a renewal.
*
* @param string $value Default checkout field value.
* @param string $key The checkout form field name/key
* @return string $value Checkout field value.
*/
public function checkout_get_value( $value, $key ) {
// Only hook in after WC()->checkout() has been initialised
if ( $this->cart_contains() && did_action( 'woocommerce_checkout_init' ) > 0 ) {
// Guard against the fake WC_Checkout singleton, see https://github.com/woocommerce/woocommerce-subscriptions/issues/427#issuecomment-260763250
remove_filter( 'woocommerce_checkout_get_value', array( &$this, 'checkout_get_value' ), 10, 2 );
if ( is_callable( array( WC()->checkout(), 'get_checkout_fields' ) ) ) { // WC 3.0+
$address_fields = array_merge( WC()->checkout()->get_checkout_fields( 'billing' ), WC()->checkout()->get_checkout_fields( 'shipping' ) );
} else {
$address_fields = array_merge( WC()->checkout()->checkout_fields['billing'], WC()->checkout()->checkout_fields['shipping'] );
}
add_filter( 'woocommerce_checkout_get_value', array( &$this, 'checkout_get_value' ), 10, 2 );
if ( array_key_exists( $key, $address_fields ) && false !== ( $item = $this->cart_contains() ) ) {
// Get the most specific order object, which will be the renewal order for renewals, initial order for initial payments, or a subscription for switches/resubscribes
$order = $this->get_order( $item );
if ( ( $order_value = wcs_get_objects_property( $order, $key ) ) ) {
$value = $order_value;
}
}
}
return $value;
}
/**
* If the cart contains a renewal order that needs to ship to an address that is different
* to the order's billing address, tell the checkout to toggle the ship to a different address
* checkbox and make sure the shipping fields are displayed by default.
*
* @param bool $ship_to_different_address Whether the order will ship to a different address
* @return bool $ship_to_different_address
*/
public function maybe_check_ship_to_different_address( $ship_to_different_address ) {
if ( ! $ship_to_different_address && false !== ( $item = $this->cart_contains() ) ) {
$order = $this->get_order( $item );
$renewal_shipping_address = $order->get_address( 'shipping' );
$renewal_billing_address = $order->get_address( 'billing' );
if ( isset( $renewal_billing_address['email'] ) ) {
unset( $renewal_billing_address['email'] );
}
if ( isset( $renewal_billing_address['phone'] ) ) {
unset( $renewal_billing_address['phone'] );
}
// If the order's addresses are different, we need to display the shipping fields otherwise the billing address will override it
if ( $renewal_shipping_address != $renewal_billing_address ) {
$ship_to_different_address = 1;
}
}
return $ship_to_different_address;
}
/**
* When completing checkout for a subscription renewal, update the address on the subscription to use
* the shipping/billing address entered in case it has changed since the subscription was first created.
*
* @since 2.0
*/
public function maybe_update_subscription_customer_data( $update_customer_data, $checkout_object ) {
$cart_renewal_item = $this->cart_contains();
if ( false !== $cart_renewal_item ) {
$subscription = wcs_get_subscription( $cart_renewal_item[ $this->cart_item_key ]['subscription_id'] );
$billing_address = array();
if ( $checkout_object->checkout_fields['billing'] ) {
foreach ( array_keys( $checkout_object->checkout_fields['billing'] ) as $field ) {
$field_name = str_replace( 'billing_', '', $field );
$billing_address[ $field_name ] = $checkout_object->get_posted_address_data( $field_name );
}
}
$shipping_address = array();
if ( $checkout_object->checkout_fields['shipping'] ) {
foreach ( array_keys( $checkout_object->checkout_fields['shipping'] ) as $field ) {
$field_name = str_replace( 'shipping_', '', $field );
$shipping_address[ $field_name ] = $checkout_object->get_posted_address_data( $field_name, 'shipping' );
}
}
$subscription->set_address( $billing_address, 'billing' );
$subscription->set_address( $shipping_address, 'shipping' );
}
return $update_customer_data;
}
/**
* If a product is being marked as not purchasable because it is limited and the customer has a subscription,
* but the current request is to resubscribe to the subscription, then mark it as purchasable.
*
* @since 2.0
* @return bool
*/
public function is_purchasable( $is_purchasable, $product ) {
_deprecated_function( __METHOD__, '2.1', 'WCS_Limiter::is_purchasable_renewal' );
return WCS_Limiter::is_purchasable_renewal( $is_purchasable, $product );
}
/**
* Flag payment of manual renewal orders via an extra URL param.
*
* This is particularly important to ensure renewals of limited subscriptions can be completed.
*
* @since 2.0
*/
public function get_checkout_payment_url( $pay_url, $order ) {
if ( wcs_order_contains_renewal( $order ) ) {
$pay_url = add_query_arg( array( $this->cart_item_key => 'true' ), $pay_url );
}
return $pay_url;
}
/**
* Customise which actions are shown against a subscription renewal order on the My Account page.
*
* @since 2.0
*/
public function filter_my_account_my_orders_actions( $actions, $order ) {
if ( wcs_order_contains_renewal( $order ) ) {
unset( $actions['cancel'] );
// If the subscription has been deleted or reactivated some other way, don't support payment on the order
$subscriptions = wcs_get_subscriptions_for_renewal_order( $order );
foreach ( $subscriptions as $subscription ) {
if ( empty( $subscription ) || ! $subscription->has_status( array( 'on-hold', 'pending' ) ) ) {
unset( $actions['pay'] );
break;
}
}
}
return $actions;
}
/**
* When a failed renewal order is being paid for via checkout, make sure WC_Checkout::create_order() preserves its
* status as 'failed' until it is paid. By default, it will always set it to 'pending', but we need it left as 'failed'
* so that we can correctly identify the status change in @see self::maybe_change_subscription_status().
*
* @param string Default order status for orders paid for via checkout. Default 'pending'
* @since 2.0
*/
public function maybe_preserve_order_status( $order_status ) {
if ( null !== WC()->session && 'failed' !== $order_status ) {
$order_id = absint( WC()->session->order_awaiting_payment );
// Guard against infinite loops in WC 3.0+ where default order staus is set in WC_Abstract_Order::__construct()
remove_filter( 'woocommerce_default_order_status', array( &$this, __FUNCTION__ ), 10 );
if ( $order_id > 0 && ( $order = wc_get_order( $order_id ) ) && wcs_order_contains_renewal( $order ) && $order->has_status( 'failed' ) ) {
$order_status = 'failed';
}
add_filter( 'woocommerce_default_order_status', array( &$this, __FUNCTION__ ) );
}
return $order_status;
}
/**
* Removes all the linked renewal/resubscribe items from the cart if a renewal/resubscribe item is removed.
*
* @param string $cart_item_key The cart item key of the item removed from the cart.
* @since 2.0
*/
public function maybe_remove_items( $cart_item_key ) {
if ( isset( WC()->cart->cart_contents[ $cart_item_key ][ $this->cart_item_key ]['subscription_id'] ) ) {
$removed_item_count = 0;
$subscription_id = WC()->cart->cart_contents[ $cart_item_key ][ $this->cart_item_key ]['subscription_id'];
foreach ( WC()->cart->cart_contents as $key => $cart_item ) {
if ( isset( $cart_item[ $this->cart_item_key ] ) && $subscription_id == $cart_item[ $this->cart_item_key ]['subscription_id'] ) {
WC()->cart->removed_cart_contents[ $key ] = WC()->cart->cart_contents[ $key ];
unset( WC()->cart->cart_contents[ $key ] );
$removed_item_count++;
}
}
//remove the renewal order flag
unset( WC()->session->order_awaiting_payment );
//clear renewal coupons
$this->clear_coupons();
if ( $removed_item_count > 1 && 'woocommerce_before_cart_item_quantity_zero' == current_filter() ) {
wc_add_notice( esc_html__( 'All linked subscription items have been removed from the cart.', 'woocommerce-subscriptions' ), 'notice' );
}
}
}
/**
* Checks the cart to see if it contains a subscription renewal item.
*
* @see wcs_cart_contains_renewal()
* @return bool | Array The cart item containing the renewal, else false.
* @since 2.0.10
*/
protected function cart_contains() {
return wcs_cart_contains_renewal();
}
/**
* Formats the title of the product removed from the cart. Because we have removed all
* linked renewal/resubscribe items from the cart we need a product title to reflect that.
*
* @param string $product_title
* @param $cart_item
* @return string $product_title
* @since 2.0
*/
public function items_removed_title( $product_title, $cart_item ) {
if ( isset( $cart_item[ $this->cart_item_key ]['subscription_id'] ) ) {
$subscription = $this->get_order( $cart_item );
$product_title = ( count( $subscription->get_items() ) > 1 ) ? esc_html_x( 'All linked subscription items were', 'Used in WooCommerce by removed item notification: "_All linked subscription items were_ removed. Undo?" Filter for item title.', 'woocommerce-subscriptions' ) : $product_title;
}
return $product_title;
}
/**
* Restores all linked renewal/resubscribe items to the cart if the customer has restored one.
*
* @param string $cart_item_key The cart item key of the item being restored to the cart.
* @since 2.0
*/
public function maybe_restore_items( $cart_item_key ) {
if ( isset( WC()->cart->cart_contents[ $cart_item_key ][ $this->cart_item_key ]['subscription_id'] ) ) {
$subscription_id = WC()->cart->cart_contents[ $cart_item_key ][ $this->cart_item_key ]['subscription_id'];
foreach ( WC()->cart->removed_cart_contents as $key => $cart_item ) {
if ( isset( $cart_item[ $this->cart_item_key ] ) && $key != $cart_item_key && $cart_item[ $this->cart_item_key ]['subscription_id'] == $subscription_id ) {
WC()->cart->cart_contents[ $key ] = WC()->cart->removed_cart_contents[ $key ];
unset( WC()->cart->removed_cart_contents[ $key ] );
}
}
//restore the renewal order flag
if ( isset( WC()->cart->cart_contents[ $cart_item_key ][ $this->cart_item_key ]['renewal_order_id'] ) ) {
WC()->session->set( 'order_awaiting_payment', WC()->cart->cart_contents[ $cart_item_key ][ $this->cart_item_key ]['renewal_order_id'] );
}
}
}
/**
* Return our custom pseudo coupon data for renewal coupons
*
* @param array $data the coupon data
* @param string $code the coupon code that data is being requested for
* @return array the custom coupon data
* @since 2.0.10
*/
public function renewal_coupon_data( $data, $code ) {
if ( ! is_object( WC()->session ) ) {
return $data;
}
$renewal_coupons = WC()->session->get( 'wcs_renewal_coupons' );
if ( empty( $renewal_coupons ) ) {
return $data;
}
foreach ( $renewal_coupons as $subscription_id => $coupons ) {
foreach ( $coupons as $coupon_code => $coupon_properties ) {
// Tweak the coupon data for renewal coupons
if ( $coupon_code == $code ) {
$expiry_date_property = WC_Subscriptions::is_woocommerce_pre( '3.0' ) ? 'expiry_date' : 'date_expires';
// Some coupon properties are overridden specifically for renewals
$renewal_coupon_overrides = array(
'id' => true,
'usage_limit' => '',
'usage_count' => '',
$expiry_date_property => '',
);
$data = array_merge( $coupon_properties, $renewal_coupon_overrides );
break 2;
}
}
}
return $data;
}
/**
* Get original products for a renewal order - so that we can ensure renewal coupons are only applied to those
*
* @param object $subscription subscription
* @return array $product_ids an array of product ids on a subscription renewal order
* @since 2.0.10
*/
protected function get_products( $subscription ) {
$product_ids = array();
if ( wcs_is_subscription( $subscription ) ) {
foreach ( $subscription->get_items() as $item ) {
$product_id = ( $item['variation_id'] ) ? $item['variation_id'] : $item['product_id'];
if ( ! empty( $product_id ) ) {
$product_ids[] = $product_id;
}
}
}
return $product_ids;
}
/**
* Store renewal coupon information in a session variable so we can access it later when coupon data is being retrieved
*
* @param int $subscription_id subscription id
* @param object $coupon coupon
* @since 2.0.10
*/
protected function store_coupon( $subscription_id, $coupon ) {
if ( ! empty( $subscription_id ) && ! empty( $coupon ) ) {
$renewal_coupons = WC()->session->get( 'wcs_renewal_coupons', array() );
$use_bools = WC_Subscriptions::is_woocommerce_pre( '3.0' ); // Some coupon properties have changed from accepting 'no' and 'yes' to true and false args.
$coupon_properties = array();
$property_defaults = array(
'discount_type' => '',
'amount' => 0,
'individual_use' => ( $use_bools ) ? false : 'no',
'product_ids' => array(),
'excluded_product_ids' => array(),
'free_shipping' => ( $use_bools ) ? false : 'no',
'product_categories' => array(),
'excluded_product_categories' => array(),
'exclude_sale_items' => ( $use_bools ) ? false : 'no',
'minimum_amount' => '',
'maximum_amount' => '',
'email_restrictions' => array(),
);
foreach ( $property_defaults as $property => $value ) {
$getter = 'get_' . $property;
if ( is_callable( array( $coupon, $getter ) ) ) {
$value = $coupon->$getter();
} else { // WC < 3.0
// Map the property to its version compatible name ( 3.0+ => WC < 3.0 )
$getter_to_property_map = array(
'amount' => 'coupon_amount',
'excluded_product_ids' => 'exclude_product_ids',
'date_expires' => 'expiry_date',
'excluded_product_categories' => 'exclude_product_categories',
'email_restrictions' => 'customer_email',
);
$property = array_key_exists( $property, $getter_to_property_map ) ? $getter_to_property_map[ $property ] : $property;
if ( property_exists( $coupon, $property ) ) {
$value = $coupon->$property;
}
}
$coupon_properties[ $property ] = $value;
}
// Subscriptions may have multiple coupons, store coupons in an array
if ( array_key_exists( $subscription_id, $renewal_coupons ) ) {
$renewal_coupons[ $subscription_id ][ wcs_get_coupon_property( $coupon, 'code' ) ] = $coupon_properties;
} else {
$renewal_coupons[ $subscription_id ] = array( wcs_get_coupon_property( $coupon, 'code' ) => $coupon_properties );
}
WC()->session->set( 'wcs_renewal_coupons', $renewal_coupons );
}
}
/**
* Clear renewal coupons - protects against confusing customer facing notices if customers add one renewal order to the cart with a set of coupons and then decide to add another renewal order with a different set of coupons
*
* @since 2.0.10
*/
public function clear_coupons() {
$renewal_coupons = WC()->session->get( 'wcs_renewal_coupons' );
// Remove the coupons from the cart
if ( ! empty( $renewal_coupons ) ) {
foreach ( $renewal_coupons as $subscription_id => $coupons ) {
foreach ( $coupons as $coupon_code => $coupon_properties ) {
WC()->cart->remove_coupons( $coupon_code );
}
}
}
// Clear the session information we have stored
WC()->session->set( 'wcs_renewal_coupons', array() );
}
/**
* Add order/subscription fee line items to the cart when a renewal order, initial order or resubscribe is in the cart.
*
* @param WC_Cart $cart
* @since 2.0.13
*/
public function maybe_add_fees( $cart ) {
if ( $cart_item = $this->cart_contains() ) {
$order = $this->get_order( $cart_item );
if ( $order instanceof WC_Order ) {
foreach ( $order->get_fees() as $fee ) {
$cart->add_fee( $fee['name'], $fee['line_total'], abs( $fee['line_tax'] ) > 0, $fee['tax_class'] );
}
}
}
}
/**
* When restoring the cart from the session, if the cart item contains addons, as well as
* a renewal or resubscribe, do not adjust the price because the original order's price will
* be used, and this includes the addons amounts.
*
* @since 2.0
*/
public function product_addons_adjust_price( $adjust_price, $cart_item ) {
if ( true === $adjust_price && isset( $cart_item[ $this->cart_item_key ] ) ) {
$adjust_price = false;
}
return $adjust_price;
}
/**
* Get the order object used to construct the renewal cart.
*
* @param Array The renewal cart item.
* @return WC_Order | The order object
* @since 2.0.13
*/
protected function get_order( $cart_item = '' ) {
$order = false;
if ( empty( $cart_item ) ) {
$cart_item = $this->cart_contains();
}
if ( false !== $cart_item && isset( $cart_item[ $this->cart_item_key ] ) ) {
$order = wc_get_order( $cart_item[ $this->cart_item_key ]['renewal_order_id'] );
}
return $order;
}
/**
* Before allowing payment on an order awaiting payment via checkout, WC >= 2.6 validates
* order items haven't changed by checking for a cart hash on the order, so we need to set
* that here. @see WC_Checkout::create_order()
*
* @since 2.0.14
*/
protected function set_cart_hash( $order_id ) {
$order = wc_get_order( $order_id );
wcs_set_objects_property( $order, 'cart_hash', md5( json_encode( wc_clean( WC()->cart->get_cart_for_session() ) ) . WC()->cart->total ) );
}
/**
* 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 ) {
if ( $item = wcs_cart_contains_renewal() ) {
$this->set_cart_hash( $item[ $this->cart_item_key ]['renewal_order_id'] );
}
return $order;
}
/**
* Redirect back to pay for an order after successfully logging in.
*
* @param string | redirect URL after successful login
* @return string
* @since 2.1.0
*/
function maybe_redirect_after_login( $redirect ) {
if ( isset( $_GET['wcs_redirect'], $_GET['wcs_redirect_id'] ) && 'pay_for_order' == $_GET['wcs_redirect'] ) {
$order = wc_get_order( $_GET['wcs_redirect_id'] );
if ( $order ) {
$redirect = $order->get_checkout_payment_url();
}
}
return $redirect;
}
/**
* Force an update to the session cart after updating renewal order line items.
*
* This is required so that changes made by @see WCS_Cart_Renewal->add_line_item_meta() (or @see
* WCS_Cart_Renewal->update_line_item_cart_data() for WC < 3.0), are also reflected
* in the session cart.
*
* @since 2.1.3
*/
public function update_session_cart_after_updating_renewal_order() {
if ( $this->cart_contains() ) {
// Update the cart stored in the session with the new data
WC()->session->cart = WC()->cart->get_cart_for_session();
}
}
/**
* Prevent compounding dynamic discounts on cart items.
* Dynamic discounts are copied from the subscription to the renewal order and so don't need to be applied again in the cart.
*
* @param bool Whether to apply the dynamic discount
* @param string The cart item key of the cart item the dynamic discount is being applied to.
* @return bool
* @since 2.1.4
*/
function prevent_compounding_dynamic_discounts( $adjust_price, $cart_item_key ) {
if ( $adjust_price && isset( WC()->cart->cart_contents[ $cart_item_key ][ $this->cart_item_key ] ) ) {
$adjust_price = false;
}
return $adjust_price;
}
/**
* For order items created as part of a renewal, keep a record of the cart item key so that we can match it
* later in @see this->set_order_item_id() once the order item has been saved and has an ID.
*
* Attached to WC 3.0+ hooks and uses WC 3.0 methods.
*
* @param WC_Order_Item_Product $order_item
* @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.2.0
*/
public function add_line_item_meta( $order_item, $cart_item_key, $cart_item ) {
if ( isset( $cart_item[ $this->cart_item_key ] ) ) {
// Store the cart item key on the line item so that we can link it later on to the order line item ID
$order_item->add_meta_data( '_cart_item_key_' . $this->cart_item_key, $cart_item_key );
}
}
/**
* After order meta is saved, get the order line item ID for this renewal and keep a record of it in
* the cart so we can update it later.
*
* @param int $order_id
* @param array $checkout_posted_data
* @since 2.2.1
*/
public function set_order_item_id( $order_id, $posted_checkout_data ) {
$order = wc_get_order( $order_id );
foreach ( $order->get_items( 'line_item' ) as $order_item_id => $order_item ) {
$cart_item_key = $order_item->get_meta( '_cart_item_key_' . $this->cart_item_key );
if ( ! empty( $cart_item_key ) ) {
// Update the line_item_id to the new corresponding item_id
$this->set_cart_item_order_item_id( $cart_item_key, $order_item_id );
}
}
}
/**
* After updating renewal order line items, update the values stored in cart item data
* which would now reference old line item IDs.
*
* Used when WC 3.0 or newer is active. When prior versions are active,
* @see WCS_Cart_Renewal->update_line_item_cart_data()
*
* @param string $cart_item_key
* @param int $order_item_id
* @since 2.2.1
*/
protected function set_cart_item_order_item_id( $cart_item_key, $order_item_id ) {
WC()->cart->cart_contents[ $cart_item_key ][ $this->cart_item_key ]['line_item_id'] = $order_item_id;
}
/**
* Do not display cart item key order item meta keys unless Subscriptions is in debug mode.
*
* @since 2.2.1
*/
public function hidden_order_itemmeta( $hidden_meta_keys ) {
if ( apply_filters( 'woocommerce_subscriptions_hide_itemmeta', ! defined( 'WCS_DEBUG' ) || true !== WCS_DEBUG ) ) {
$hidden_meta_keys[] = '_cart_item_key_' . $this->cart_item_key;
}
return $hidden_meta_keys;
}
/**
* When completing checkout for a subscription renewal, update the subscription's address to match
* the shipping/billing address entered on checkout.
*
* @param int $customer_id
* @param array $checkout_data the posted checkout data
* @since 2.2.7
*/
public function maybe_update_subscription_address_data( $customer_id, $checkout_data ) {
$cart_renewal_item = $this->cart_contains();
if ( false !== $cart_renewal_item ) {
$subscription = wcs_get_subscription( $cart_renewal_item[ $this->cart_item_key ]['subscription_id'] );
$billing_address = $shipping_address = array();
foreach ( array( 'billing', 'shipping' ) as $address_type ) {
$checkout_fields = WC()->checkout()->get_checkout_fields( $address_type );
if ( is_array( $checkout_fields ) ) {
foreach ( array_keys( $checkout_fields ) as $field ) {
if ( isset( $checkout_data[ $field ] ) ) {
$field_name = str_replace( $address_type. '_', '', $field );
${$address_type . '_address'}[ $field_name ] = $checkout_data[ $field ];
}
}
}
}
$subscription->set_address( $billing_address, 'billing' );
$subscription->set_address( $shipping_address, 'shipping' );
}
}
/* Deprecated */
/**
* For subscription renewal via cart, use original order discount
*
* @since 2.0
*/
public function set_renewal_discounts( $cart ) {
_deprecated_function( __METHOD__, '2.0.10', 'Applying original subscription discounts to renewals via cart are now handled within ' . __CLASS__ .'::maybe_setup_cart()' );
}
/**
* For subscription renewal via cart, previously adjust item price by original order discount
*
* No longer required as of 1.3.5 as totals are calculated correctly internally.
*
* @since 2.0
*/
public function get_discounted_price_for_renewal( $price, $cart_item, $cart ) {
_deprecated_function( __METHOD__, '2.0.10', 'No longer required as of 1.3.5 as totals are calculated correctly internally.' );
}
/**
* Add subscription fee line items to the cart when a renewal order or resubscribe is in the cart.
*
* @param WC_Cart $cart
* @since 2.0.10
*/
public function maybe_add_subscription_fees( $cart ) {
_deprecated_function( __METHOD__, '2.0.13', __CLASS__ .'::maybe_add_fees()' );
}
/**
* After updating renewal order line items, update the values stored in cart item data
* which would now reference old line item IDs.
*
* @since 2.1.3
*/
public function update_line_item_cart_data( $item_id, $cart_item_data, $cart_item_key ) {
if ( false === WC_Subscriptions::is_woocommerce_pre( '3.0' ) ) {
_deprecated_function( __METHOD__, '2.2.0 and WooCommerce 3.0', __CLASS__ . '::add_line_item_meta( $order_item, $cart_item_key, $cart_item )' );
}
if ( isset( $cart_item_data[ $this->cart_item_key ] ) ) {
// Update the line_item_id to the new corresponding item_id
WC()->cart->cart_contents[ $cart_item_key ][ $this->cart_item_key ]['line_item_id'] = $item_id;
}
}
/**
* After updating renewal order line items, update the values stored in cart item data
* which would now reference old line item IDs.
*
* Used when WC 3.0 or newer is active. When prior versions are active,
* @see WCS_Cart_Renewal->update_line_item_cart_data()
*
* @deprecated 2.2.1
* @since 2.2.0
*/
public function update_order_item_data_in_cart( $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 );
}
}
new WCS_Cart_Renewal();