Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/wp-user-avatar/src/Admin/SettingsPages/Membership/views/orders/order-notes-sidebar.php
+++ b/wp-user-avatar/src/Admin/SettingsPages/Membership/views/orders/order-notes-sidebar.php
@@ -1,14 +1,17 @@
<?php /** @var array $order_notes */ ?>
<div class="ppress-order-notes-wrap">
<ul class="ppress-notes">
- <?php foreach ($order_notes as $order_note) : $explode = explode('|', $order_note['meta_value']); ?>
+ <?php foreach ($order_notes as $order_note) : $note_parts = explode('|', (string)$order_note['meta_value'], 2);
+ // notes are stored as "date|text". One without the separator is all text, with no date.
+ [$note_date, $note_text] = count($note_parts) === 2 ? $note_parts : ['', $note_parts[0]]; ?>
<li class="ppress-note ppress-note-system ">
<div class="ppress-note-content">
- <p><?= $explode[1] ?></p>
+ <?php // notes can carry links (e.g. an AffiliateWP referral) but also text from gateways and users. ?>
+ <p><?= wp_kses_post($note_text) ?></p>
</div>
<p class="ppress-note-meta">
- <abbr class="ppress-note-date"><?= $explode[0] ?></abbr>
- <a data-note-id="<?= $order_note['meta_id'] ?>" href="#" class="ppress-delete-note" role="button"><?php esc_html_e('Delete', 'wp-user-avatar') ?></a>
+ <abbr class="ppress-note-date"><?= esc_html($note_date) ?></abbr>
+ <a data-note-id="<?= absint($order_note['meta_id']) ?>" href="#" class="ppress-delete-note" role="button"><?php esc_html_e('Delete', 'wp-user-avatar') ?></a>
</p>
</li>
<?php endforeach; ?>
--- a/wp-user-avatar/src/Admin/SettingsPages/Membership/views/subscriptions/subscription-notes-sidebar.php
+++ b/wp-user-avatar/src/Admin/SettingsPages/Membership/views/subscriptions/subscription-notes-sidebar.php
@@ -1,13 +1,16 @@
<?php /** @var array $sub_notes */ ?>
<div class="ppress-subscription-notes-wrap">
<ul class="ppress-notes">
- <?php foreach ($sub_notes as $sub_note) : $explode = explode('|', $sub_note); ?>
+ <?php foreach ($sub_notes as $sub_note) : $note_parts = explode('|', (string)$sub_note, 2);
+ // notes are stored as "date|text". One without the separator is all text, with no date.
+ [$note_date, $note_text] = count($note_parts) === 2 ? $note_parts : ['', $note_parts[0]]; ?>
<li class="ppress-note ppress-note-system ">
<div class="ppress-note-content">
- <p><?= $explode[1] ?></p>
+ <?php // notes can carry links (e.g. an AffiliateWP referral) but also text from gateways and users. ?>
+ <p><?= wp_kses_post($note_text) ?></p>
</div>
<p class="ppress-note-meta">
- <abbr class="ppress-note-date"><?= $explode[0] ?></abbr>
+ <abbr class="ppress-note-date"><?= esc_html($note_date) ?></abbr>
</p>
</li>
<?php endforeach; ?>
--- a/wp-user-avatar/src/Classes/ExtensionManager.php
+++ b/wp-user-avatar/src/Classes/ExtensionManager.php
@@ -68,7 +68,7 @@
self::RECEIPT => 'ProfilePressLibsodiumReceiptInit',
self::BUDDYPRESS => 'ProfilePressLibsodiumBuddyPressInit',
self::MULTISITE => 'ProfilePressLibsodiumMultisiteIntegrationInit',
- self::WOOCOMMERCE => 'ProfilePressLibsodiumMultisiteIntegrationInit',
+ self::WOOCOMMERCE => 'ProfilePressLibsodiumWooCommerceIntegrationInit',
self::AKISMET => 'ProfilePressLibsodiumAkismetIntegration',
self::CAMPAIGN_MONITOR => 'ProfilePressLibsodiumEmailMarketingCampaignMonitorIntegrationInit',
self::MAILCHIMP => 'ProfilePressLibsodiumEmailMarketingMailchimpIntegrationInit',
--- a/wp-user-avatar/src/Classes/LoginNotificationEmail.php
+++ b/wp-user-avatar/src/Classes/LoginNotificationEmail.php
@@ -94,10 +94,7 @@
ppress_login_url()
], $wp_user);
- return ppress_custom_profile_field_search_replace(
- str_replace($search, $replace, $content),
- $wp_user
- );
+ return ppress_replace_placeholders($content, $search, $replace, $wp_user);
}
public static function get_instance()
--- a/wp-user-avatar/src/Classes/RegistrationAuth.php
+++ b/wp-user-avatar/src/Classes/RegistrationAuth.php
@@ -212,10 +212,13 @@
);
// acceptable defined roles in reg-select-role shortcode.
- if (!empty($role) && is_string($role) && $role != 'administrator' && in_array($role, (array)self::acceptable_defined_roles($form_id), true)) {
+ if (!empty($role) && is_string($role) && $role != 'administrator' && in_array($role, (array)self::acceptable_defined_roles($form_id, $is_melange), true)) {
$real_userdata['role'] = $role;
- } else {
+ } elseif ( ! $is_melange) {
// a missing or unaccepted selected role falls back to the role the form assigns.
+ // Melange forms have no User Role setting. Their IDs are a separate sequence from registration forms,
+ // so looking up the registration form with the same ID would hand out that (possibly unpublished)
+ // form's role. They get the default role from Settings > General instead.
$builder_role = FormRepository::get_form_meta($form_id, FormRepository::REGISTRATION_TYPE, FormRepository::REGISTRATION_USER_ROLE);
if (!empty($builder_role)) {
@@ -472,7 +475,7 @@
$default_success_message = '<div class="profilepress-reg-status success">' . esc_html__('Registration successful.', 'wp-user-avatar') . '</div>';
- if (FormRepository::is_drag_drop($form_id, FormRepository::REGISTRATION_TYPE)) {
+ if ( ! $is_melange && FormRepository::is_drag_drop($form_id, FormRepository::REGISTRATION_TYPE)) {
// Drag and drop signup pages do not allow the use of div wrapper. only the message to be shown is entered.
// so here, we are wrapping it in reg status div.
if (!empty($success_message)) {
@@ -499,20 +502,24 @@
/**
* Array list of acceptable defined roles.
*
- * @param int $form_id ID of registration form
+ * @param int $form_id ID of registration or melange form
+ * @param bool $is_melange whether $form_id is a melange form ID. Melange and registration IDs overlap, so the
+ * allow-list must come from the form of the right type.
*
* @return array
*/
- public static function acceptable_defined_roles($form_id)
+ public static function acceptable_defined_roles($form_id, $is_melange = false)
{
- if (FormRepository::is_drag_drop($form_id, FormRepository::REGISTRATION_TYPE)) {
- $settings = FormRepository::form_builder_fields_settings($form_id, FormRepository::REGISTRATION_TYPE);
+ $form_type = $is_melange ? FormRepository::MELANGE_TYPE : FormRepository::REGISTRATION_TYPE;
+
+ if (FormRepository::is_drag_drop($form_id, $form_type)) {
+ $settings = FormRepository::form_builder_fields_settings($form_id, $form_type);
$found_field = wp_list_filter($settings, ['fieldType' => 'reg-select-role']);
if (empty($found_field)) return [];
$reg_select_field_options = array_values(wp_list_pluck($found_field, 'options'));
$options = $reg_select_field_options[0] ?? [];
} else {
- $registration_structure = FormRepository::get_form_meta($form_id, FormRepository::REGISTRATION_TYPE, FormRepository::FORM_STRUCTURE);
+ $registration_structure = (string)FormRepository::get_form_meta($form_id, $form_type, FormRepository::FORM_STRUCTURE);
preg_match('/[reg-select-role.*]/', $registration_structure, $matches);
if (empty($matches[0])) return [];
$options = [];
@@ -525,6 +532,6 @@
$acceptable_user_role = empty($options) ? array_keys(ppress_get_editable_roles()) : array_map('trim', explode(',', $options));
- return apply_filters('ppress_acceptable_user_role', $acceptable_user_role, $form_id);
+ return apply_filters('ppress_acceptable_user_role', $acceptable_user_role, $form_id, $is_melange);
}
}
No newline at end of file
--- a/wp-user-avatar/src/Classes/SendEmail.php
+++ b/wp-user-avatar/src/Classes/SendEmail.php
@@ -80,7 +80,12 @@
$message = $this->message;
if ($this->email_content_type() == 'text/html') {
- $message = htmlspecialchars_decode(stripslashes($message));
+ // a template saved entity-encoded (no real tags, e.g. "<p>Hi") is decoded. A message that's HTML
+ // already is left as it is, so values escaped into it (e.g. profile fields) stay escaped.
+ if (false === strpos($message, '<') && preg_match('#</?[a-z!]#i', $message)) {
+ $message = htmlspecialchars_decode(stripslashes($message));
+ }
+
$email_template = ppress_get_setting('email_template_type', 'default', true);
if ($email_template == 'default') {
@@ -124,6 +129,9 @@
return false;
}
+ // subjects are plain text: placeholders filled in for HTML bodies may have left entities, e.g. &.
+ $this->subject = wp_specialchars_decode((string)$this->subject, ENT_QUOTES);
+
$this->message = $this->templatified_email();
$this->before_send();
--- a/wp-user-avatar/src/Classes/WelcomeEmailAfterSignup.php
+++ b/wp-user-avatar/src/Classes/WelcomeEmailAfterSignup.php
@@ -45,10 +45,7 @@
ppress_login_url()
]);
- return ppress_custom_profile_field_search_replace(
- str_replace($search, $replace, $content),
- $this->wp_user
- );
+ return ppress_replace_placeholders($content, $search, $replace, $this->wp_user);
}
public function send_welcome_mail()
--- a/wp-user-avatar/src/DBUpdates.php
+++ b/wp-user-avatar/src/DBUpdates.php
@@ -11,7 +11,7 @@
{
public static $instance;
- const DB_VER = 17;
+ const DB_VER = 18;
public function init_options()
{
@@ -250,6 +250,42 @@
add_action('init', 'flush_rewrite_rules', 99999);
}
+ /**
+ * Relinks orders that lost their subscription: ppress_subscribe_user_to_plan() (Orders → Add Order, the
+ * WooCommerce integration) saved them with subscription_id 0 since 4.18, until OrderEntity::save() stopped saving
+ * cached copies over them. Without the link, the subscription had no completed orders and couldn't change plans.
+ *
+ * Each such order is its subscription's parent order, for the same customer.
+ */
+ public function update_routine_18()
+ {
+ global $wpdb;
+
+ $orders = DBTables::orders_db_table();
+ $subscriptions = DBTables::subscriptions_db_table();
+
+ $pairs = $wpdb->get_results(
+ "SELECT o.id AS order_id, MIN(s.id) AS subscription_id
+ FROM $orders o
+ INNER JOIN $subscriptions s ON s.parent_order_id = o.id AND s.customer_id = o.customer_id
+ WHERE o.subscription_id = 0
+ GROUP BY o.id"
+ );
+
+ foreach ((array)$pairs as $pair) {
+ $wpdb->update(
+ $orders,
+ ['subscription_id' => (int)$pair->subscription_id],
+ ['id' => (int)$pair->order_id, 'subscription_id' => 0],
+ ['%d'],
+ ['%d', '%d']
+ );
+ }
+
+ // orders cached earlier in this request still have the old value.
+ ppress_cache_transform_flush('order_factory_');
+ }
+
public static function get_instance()
{
if ( ! isset(self::$instance)) {
--- a/wp-user-avatar/src/Functions/GlobalFunctions.php
+++ b/wp-user-avatar/src/Functions/GlobalFunctions.php
@@ -7,6 +7,7 @@
use ProfilePressCoreClassesPROFILEPRESS_sql;
use ProfilePressCoreClassesSendEmail;
use ProfilePressCoreMembershipCheckoutFields;
+use ProfilePressCoreMembershipModelsPlanPlanEntity;
use ProfilePressCoreShortcodeParserBuilderFrontendProfileBuilder;
/** Plugin DB settings data */
@@ -382,9 +383,17 @@
$username_or_id = ppress_get_username_by_id($username_or_id);
}
+ /**
+ * Filter the user identifier used in the frontend profile URL. Defaults to the username.
+ *
+ * @param string $slug
+ * @param string $username
+ */
+ $slug = apply_filters('ppress_frontend_profile_url_slug', $username_or_id, $username_or_id);
+
return apply_filters(
'ppress_frontend_profile_url',
- home_url(ppress_get_profile_slug() . '/' . rawurlencode($username_or_id)),
+ home_url(ppress_get_profile_slug() . '/' . rawurlencode($slug)),
$username_or_id
);
}
@@ -877,23 +886,20 @@
$user->last_name
);
- $message = htmlspecialchars_decode(
- apply_filters(
- 'ppress_signup_admin_email_message',
- str_replace($search, $replace, $message),
- $user
- )
+ // the new member chose their name and fields: their values are filled in once, never read as placeholders.
+ // The stored template is decoded before they go in, so their escaped values stay escaped.
+ $message = apply_filters(
+ 'ppress_signup_admin_email_message',
+ ppress_replace_placeholders(htmlspecialchars_decode($message), $search, $replace, $user),
+ $user
);
$title = apply_filters(
'ppress_signup_admin_email_subject',
- str_replace($search, $replace, $title),
+ ppress_replace_placeholders($title, $search, $replace, $user),
$user
);
- $title = ppress_custom_profile_field_search_replace($title, $user);
- $message = ppress_custom_profile_field_search_replace($message, $user);
-
$admin_email = apply_filters('ppress_signup_notification_admin_email', ppress_get_admin_notification_emails());
ppress_send_email($admin_email, $title, $message);
@@ -1852,6 +1858,68 @@
}
/**
+ * Lightweight, allowlist-only alternative to html_entity_decode() for user-supplied HTML.
+ *
+ * Only entity-encoded basic formatting tags without attributes (e.g. <strong>) are revived,
+ * plus <a href="..."> whose URL goes through esc_url(). Anything carrying other attributes
+ * (class, style, data-*, on*) stays inert text, so a stored value can never smuggle in markup
+ * that front-end scripts initialise on. Run it AFTER wp_kses_post(), never before.
+ *
+ * @param string $value
+ *
+ * @return string
+ */
+function ppress_decode_basic_html($value)
+{
+ if ( ! is_string($value) || $value === '') return $value;
+
+ $tags = 'b|strong|i|em|u|s|del|br|p|ul|ol|li|blockquote|code|pre|h[2-6]';
+ $lt = '(?:<|*60;|*3c;)';
+ $gt = '(?:>|*62;|*3e;)';
+ $q = '(?:"|*34;|*22;|"|*39;|*27;|')';
+
+ $value = preg_replace_callback("~$lt(/?)($tags)s*/?$gt~i", function ($m) {
+ $tag = strtolower($m[2]);
+
+ if ($tag === 'br') return '<br>';
+
+ return '<' . $m[1] . $tag . '>';
+ }, $value);
+
+ $value = preg_replace_callback("~{$lt}as+hrefs*=s*$q([^"'<>s]+?)$qs*$gt~i", function ($m) {
+ $url = esc_url(html_entity_decode($m[1], ENT_QUOTES, 'UTF-8'));
+
+ return empty($url) ? $m[0] : '<a href="' . $url . '" rel="nofollow ugc">';
+ }, $value);
+
+ $value = preg_replace("~$lt/as*$gt~i", '</a>', $value);
+
+ // stops an unclosed tag in the bio from bleeding into the rest of the page.
+ return force_balance_tags($value);
+}
+
+/**
+ * Build a social-login shortcode whose redirect cannot break out into another shortcode.
+ *
+ * esc_url_raw() keeps "[" and "]". Percent-encode them: HTML entities would be passed
+ * through to the redirect callback and corrupt the URL.
+ *
+ * @param mixed $type
+ * @param mixed $redirect
+ *
+ * @return string
+ */
+function ppress_social_login_shortcode($type, $redirect)
+{
+ $type = sanitize_key(is_scalar($type) ? (string)$type : '');
+ if ($type === '' || ! array_key_exists($type, ppress_social_login_networks())) return '';
+
+ $redirect = str_replace(['[', ']'], ['%5B', '%5D'], is_scalar($redirect) ? (string)$redirect : '');
+
+ return sprintf('[pp-social-login type="%s" redirect="%s"]', $type, $redirect);
+}
+
+/**
* Neutralize shortcodes in fully-assembled template buffers before outer do_shortcode() execution.
*
* Prevents split shortcode fragments from recombining across HTML element boundaries
@@ -2198,7 +2266,7 @@
/**
* Whether checkout should refuse a plan because the customer already has an active subscription to it.
*
- * @param ProfilePressCoreMembershipModelsPlanPlanEntity $plan
+ * @param PlanEntity $plan
* @param int $user_id
*
* @return bool
@@ -2237,19 +2305,38 @@
}
/**
- * @param $message
+ * Replaces {{field}} placeholders with the user's profile fields, user properties and user meta.
+ *
+ * Secrets are never filled in, whatever the template asks for: password hashes, password reset keys and login session
+ * tokens. Values that are lists are joined; lists of lists are left out.
+ *
+ * Values are what members typed, so they're escaped when emails are sent as HTML: markup in a member's field shows as
+ * text instead of becoming part of the email. Subjects are decoded again when sent (SendEmail), as they're plain text.
+ *
+ * @param string $message
* @param WP_User $user
+ * @param bool|null $escape whether to escape values for HTML. Default: when emails are sent as HTML.
*
- * @return array|mixed|string|string[]
+ * @return string
*/
-function ppress_custom_profile_field_search_replace($message, $user)
+function ppress_custom_profile_field_search_replace($message, $user, $escape = null)
{
+ if ( ! $user instanceof WP_User) return $message;
+
// handle support for custom fields placeholder.
- preg_match_all('#({{[a-z_-]+}})#', $message, $matches);
+ preg_match_all('#({{[a-z_-]+}})#', (string)$message, $matches);
if ( ! empty($matches[1])) {
- foreach ($matches[1] as $match) {
+ $secret = apply_filters('ppress_placeholder_secret_user_fields', ['user_pass', 'user_activation_key', 'session_tokens']);
+
+ if (is_null($escape)) {
+ $escape = ppress_get_setting('email_content_type', 'text/html', true) == 'text/html';
+ }
+
+ $escape = (bool)apply_filters('ppress_escape_placeholder_user_fields', $escape, $user);
+
+ foreach (array_unique($matches[1]) as $match) {
$key = str_replace(['{', '}'], '', $match);
@@ -2257,16 +2344,21 @@
$field_type = PROFILEPRESS_sql::get_field_type($key);
- if ($field_type == 'file') {
+ if (in_array($key, $secret, true)) {
+ $value = '';
+ } elseif ($field_type == 'file') {
$value = FrontendProfileBuilder::get_user_uploaded_file($user->ID, $key);
} elseif (isset($user->{$key})) {
$value = $user->{$key};
- if (is_array($value)) $value = implode(', ', $value);
+ if (is_array($value)) $value = implode(', ', array_filter($value, 'is_scalar'));
+
+ // uploaded files above are links ProfilePress builds; these are what the member typed.
+ if ($escape) $value = esc_html((string)$value);
}
- $message = str_replace($match, $value, $message);
+ $message = str_replace($match, (string)$value, $message);
}
}
@@ -2274,6 +2366,46 @@
}
/**
+ * Replaces an email's placeholders with their values, then {{field}} placeholders with the user's fields, in one pass:
+ * a value is never read again for placeholders. Values can come from members (a name, a billing field, a comment), so a
+ * member whose first name is "{{user_email}}" gets that text, not their email address.
+ *
+ * @param string $content
+ * @param string[] $search placeholders, e.g. {{first_name}}.
+ * @param string[] $replace their values, in the same order.
+ * @param WP_User|null $user for {{field}} placeholders. None without a user.
+ *
+ * @return string
+ */
+function ppress_replace_placeholders($content, $search, $replace, $user = null)
+{
+ $content = (string)$content;
+ $search = array_values((array)$search);
+ $replace = array_values((array)$replace);
+ $tokens = [];
+
+ // each placeholder becomes a token no placeholder or {{field}} can match, until the very end.
+ foreach ($search as $i => $placeholder) {
+
+ if ( ! is_string($placeholder) || '' === $placeholder || ! array_key_exists($i, $replace)) continue;
+
+ if (strpos($content, $placeholder) === false) continue;
+
+ $token = "x1A" . $i . "x1A";
+
+ $content = str_replace($placeholder, $token, $content);
+ $tokens[$token] = is_scalar($replace[$i]) || is_null($replace[$i]) ? (string)$replace[$i] : '';
+ }
+
+ if ($user instanceof WP_User) {
+ $content = ppress_custom_profile_field_search_replace($content, $user);
+ }
+
+ // strtr replaces in one pass, so a value is never searched again.
+ return strtr($content, $tokens);
+}
+
+/**
* IDs saved under a plan extras key (e.g. tutorlms_courses, learndash_groups) across the customer's
* active subscriptions other than the given one.
*
--- a/wp-user-avatar/src/Functions/MSFunctions.php
+++ b/wp-user-avatar/src/Functions/MSFunctions.php
@@ -996,4 +996,61 @@
function ppress_is_redirect_to_referrer_after_checkout()
{
return apply_filters('ppress_checkout_redirect_to_referrer_after_payment', false);
-}
No newline at end of file
+}
+/**
+ * Who or what is changing an order's or subscription's status, for its notes. Empty when it can't be told, e.g. a
+ * visitor's request that isn't from a payment gateway.
+ *
+ * @param string $payment_method_id the order's or subscription's payment method.
+ *
+ * @return string
+ */
+function ppress_status_change_actor($payment_method_id = '')
+{
+ if (is_user_logged_in()) {
+ $actor = wp_get_current_user()->user_login;
+ } elseif (doing_action('ppress_daily_recurring_job')) {
+ $actor = esc_html__('the daily subscription check', 'wp-user-avatar');
+ } elseif (wp_doing_cron()) {
+ $actor = esc_html__('a scheduled task', 'wp-user-avatar');
+ } elseif (defined('WP_CLI') && WP_CLI) {
+ $actor = 'WP-CLI';
+ } else {
+ // a gateway's webhook or payment confirmation. Store payments (free and manual orders) have no gateway.
+ $gateway = ! empty($payment_method_id) ? PaymentMethods::get_instance()->get_by_id($payment_method_id) : false;
+
+ $actor = $gateway instanceof AbstractPaymentMethod && $payment_method_id !== StoreGateway::get_instance()->get_id() ?
+ $gateway->get_method_title() : '';
+ }
+
+ return (string)apply_filters('ppress_status_change_actor', $actor, $payment_method_id);
+}
+
+/**
+ * The note added when an order's or subscription's status changes.
+ *
+ * @param string $type 'order' or 'subscription'.
+ * @param string $old_label the old status' label.
+ * @param string $new_label the new status' label.
+ * @param string $actor see ppress_status_change_actor().
+ *
+ * @return string
+ */
+function ppress_status_change_note($type, $old_label, $new_label, $actor)
+{
+ $is_order = 'order' === $type;
+
+ if ('' === (string)$old_label) {
+ return '' !== $actor ?
+ /* translators: 1: status, 2: user name, payment gateway or "a scheduled task" */
+ sprintf($is_order ? __('Order status set to %1$s by %2$s.', 'wp-user-avatar') : __('Subscription status set to %1$s by %2$s.', 'wp-user-avatar'), $new_label, $actor) :
+ /* translators: %s: status */
+ sprintf($is_order ? __('Order status set to %s.', 'wp-user-avatar') : __('Subscription status set to %s.', 'wp-user-avatar'), $new_label);
+ }
+
+ return '' !== $actor ?
+ /* translators: 1: old status, 2: new status, 3: user name, payment gateway or "a scheduled task" */
+ sprintf($is_order ? __('Order status changed from %1$s to %2$s by %3$s.', 'wp-user-avatar') : __('Subscription status changed from %1$s to %2$s by %3$s.', 'wp-user-avatar'), $old_label, $new_label, $actor) :
+ /* translators: 1: old status, 2: new status */
+ sprintf($is_order ? __('Order status changed from %1$s to %2$s.', 'wp-user-avatar') : __('Subscription status changed from %1$s to %2$s.', 'wp-user-avatar'), $old_label, $new_label);
+}
--- a/wp-user-avatar/src/Functions/custom-settings-api.php
+++ b/wp-user-avatar/src/Functions/custom-settings-api.php
@@ -532,7 +532,8 @@
$value = ! empty($value) ? $value : null;
?>
- <input type="text" placeholder="<?=$placeholder; ?>" id="<?=$id; ?>" name="<?=$name; ?>" class="<?=$class; ?>" value="<?=$value; ?>" <?=$data_key; ?>/>
+ <?php // saved values were escaped on save, which esc_attr() doesn't escape again; defaults weren't. ?>
+ <input type="text" placeholder="<?=esc_attr($placeholder); ?>" id="<?=$id; ?>" name="<?=$name; ?>" class="<?=$class; ?>" value="<?=esc_attr((string)$value); ?>" <?=$data_key; ?>/>
<?php
do_action('wp_cspa_field_before_text_field', $id);
}
@@ -679,7 +680,7 @@
<th scope="row"><label for="<?=$key; ?>"><?=$label; ?></label></th>
<td>
<?php do_action('wp_cspa_before_number_field', $db_options, $option_name, $key, $args); ?>
- <input type="number" id="<?=$key; ?>" name="<?=$option_name, '[', $key, ']'; ?>" class="regular-text" value="<?=$value; ?>" placeholder="<?=$placeholder?>"/>
+ <input type="number" id="<?=$key; ?>" name="<?=$option_name, '[', $key, ']'; ?>" class="regular-text" value="<?=esc_attr((string)$value); ?>" placeholder="<?=esc_attr($placeholder)?>"/>
<?php do_action('wp_cspa_after_number_field', $db_options, $option_name, $key, $args); ?>
<p class="description"><?=$description; ?></p>
@@ -714,7 +715,7 @@
<td>
<?php do_action('wp_cspa_before_password_field', $db_options, $option_name, $key, $args); ?>
<input type="password" id="<?=$key; ?>" name="<?=$option_name, '[', $key, ']'; ?>"
- class="regular-text" value="<?=$value; ?>" <?=$disabled; ?>/>
+ class="regular-text" value="<?=esc_attr((string)$value); ?>" <?=$disabled; ?>/>
<?php do_action('wp_cspa_after_password_field', $db_options, $option_name, $key, $args); ?>
<p class="description"><?=$description; ?></p>
@@ -750,7 +751,7 @@
<td>
<?php do_action('wp_cspa_before_hidden_field', $db_options, $option_name, $key, $args); ?>
<input type="hidden" id="<?=$key; ?>" name="<?=$option_name, '[', $key, ']'; ?>"
- class="regular-text" value="<?=$value; ?>"/>
+ class="regular-text" value="<?=esc_attr((string)$value); ?>"/>
<?php do_action('wp_cspa_after_hidden_field', $db_options, $option_name, $key, $args); ?>
<p class="description"><?=$description; ?></p>
</td>
@@ -1067,7 +1068,7 @@
<td>
<?php do_action('wp_cspa_before_checkbox_field', $db_options, $option_name, $key, $args); ?>
<input type="hidden" name="<?=$option_name, '[', $key, ']'; ?>" value="false">
- <input type="checkbox" id="<?=$key; ?>" name="<?=$option_name, '[', $key, ']'; ?>" value="<?=$value; ?>" <?php checked($default_value, $value); ?> />
+ <input type="checkbox" id="<?=$key; ?>" name="<?=$option_name, '[', $key, ']'; ?>" value="<?=esc_attr((string)$value); ?>" <?php checked($default_value, $value); ?> />
<strong><label for="<?=$key; ?>"><?=$checkbox_label; ?></label></strong>
<?php do_action('wp_cspa_after_checkbox_field', $db_options, $option_name, $key, $args); ?>
--- a/wp-user-avatar/src/LMS/Admin/IntroNotice.php
+++ b/wp-user-avatar/src/LMS/Admin/IntroNotice.php
@@ -29,6 +29,9 @@
{
if ( ! current_user_can('manage_options')) return false;
+ // fresh installs already have courses from day one; the announcement is for sites that upgraded.
+ if ('true' === get_option('ppress_skip_courses_intro_notice')) return false;
+
if (class_exists(PAnD::class) && ! PAnD::is_admin_notice_active(self::DISMISS_KEY)) return false;
$screen = function_exists('get_current_screen') ? get_current_screen() : null;
--- a/wp-user-avatar/src/Membership/Controllers/CheckoutController.php
+++ b/wp-user-avatar/src/Membership/Controllers/CheckoutController.php
@@ -19,6 +19,7 @@
use ProfilePressCoreMembershipServicesCouponService;
use ProfilePressCoreMembershipServicesEUVATCheckerEuVatApi;
use ProfilePressCoreMembershipServicesOrderService;
+use ProfilePressCoreMembershipServicesSubscriptionService;
use ProfilePressCoreMembershipServicesTaxService;
use ProfilePressLibsodiumLoginGuard;
@@ -297,6 +298,8 @@
{
$order_id = 0;
+ $plan_change_lock = false;
+
try {
$nonce_check = check_ajax_referer('ppress_process_checkout', 'ppress_checkout_nonce', false);
@@ -334,6 +337,14 @@
);
}
+ // the checkout page hides the form for a plan the member already has; refuse it here too, e.g. from another
+ // tab left open or a second click. ppress_checkout_allow_repurchase still allows it where wanted.
+ if (empty($change_plan_sub_id) && is_user_logged_in() && ppress_is_plan_repurchase_blocked(ppress_get_plan($plan_id), get_current_user_id())) {
+ throw new Exception(
+ esc_html__('You have an active subscription to this plan.', 'wp-user-avatar')
+ );
+ }
+
$checkout_errors = apply_filters('ppress_checkout_validation', new WP_Error(), $plan_id, $_POST);
if (is_wp_error($checkout_errors) && $checkout_errors->get_error_code() != '') {
@@ -367,6 +378,21 @@
if ( ! $changePlanSub->can_switch_to_plan($plan_id)) {
throw new Exception(esc_html__('You are not allowed to switch from this plan.', 'wp-user-avatar'));
}
+
+ // claim the source subscription until this checkout is done, so concurrent requests can't each
+ // switch away from it. Held through order completion, which cancels the source for free checkouts.
+ $plan_change_lock = SubscriptionService::init()->acquire_plan_change_lock($change_plan_sub_id);
+
+ if (false === $plan_change_lock) {
+ throw new Exception(esc_html__('A plan change for this subscription is already in progress. Please wait a moment and try again.', 'wp-user-avatar'));
+ }
+
+ // re-read it now that it's claimed: a request that held the claim may have switched it already.
+ $changePlanSub = SubscriptionFactory::fromId($change_plan_sub_id);
+
+ if ( ! $changePlanSub->can_switch_to_plan($plan_id)) {
+ throw new Exception(esc_html__('You are not allowed to switch from this plan.', 'wp-user-avatar'));
+ }
}
$coupon_code = CheckoutSessionData::get_coupon_code($plan_id);
@@ -513,6 +539,10 @@
}
}
+ if (false !== $plan_change_lock) {
+ SubscriptionService::init()->release_plan_change_lock($change_plan_sub_id, $plan_change_lock);
+ }
+
wp_send_json([
'success' => $process_payment->is_success,
'redirect_url' => $process_payment->redirect_url,
@@ -527,6 +557,10 @@
CouponService::init()->release_coupon_hold($order_id);
}
+ if (false !== $plan_change_lock) {
+ SubscriptionService::init()->release_plan_change_lock($change_plan_sub_id, $plan_change_lock);
+ }
+
$error_message = ppress_is_json($e->getMessage()) ? json_decode($e->getMessage(), true) : $e->getMessage();
ppress_log_error($error_message);
--- a/wp-user-avatar/src/Membership/Emails/AbstractMembershipEmail.php
+++ b/wp-user-avatar/src/Membership/Emails/AbstractMembershipEmail.php
@@ -102,10 +102,8 @@
$user = $order_or_sub->get_customer()->get_wp_user();
}
- return ppress_custom_profile_field_search_replace(
- str_replace(array_keys($placeholders), array_values($placeholders), $content),
- $user
- );
+ // values can come from members (names, billing fields), so they're filled in once and never read again.
+ return ppress_replace_placeholders($content, array_keys($placeholders), array_values($placeholders), $user);
}
/**
--- a/wp-user-avatar/src/Membership/Models/Coupon/CouponEntity.php
+++ b/wp-user-avatar/src/Membership/Models/Coupon/CouponEntity.php
@@ -65,7 +65,7 @@
$this->$key = $value;
if ($key == 'plan_ids') {
- $this->plan_ids = ! empty($value) && ppress_is_json($value) ? json_decode($value, true) : [];
+ $this->set_plan_ids($value);
}
}
}
@@ -145,14 +145,24 @@
return ! empty($this->amount) ? (float)$this->amount : '';
}
+ /**
+ * Kept as an array, whether given an array or the JSON stored in the database; the repository encodes it.
+ */
protected function set_plan_ids($value)
{
- $this->plan_ids = is_array($value) ? wp_json_encode($value) : $value;
+ if (is_string($value)) {
+ $value = '' !== $value && ppress_is_json($value) ? json_decode($value, true) : [];
+ }
+
+ $this->plan_ids = array_values(array_filter(array_map('absint', (array)$value)));
}
+ /**
+ * @return int[]
+ */
public function get_plan_ids()
{
- return $this->plan_ids;
+ return is_array($this->plan_ids) ? $this->plan_ids : [];
}
public function get_usage_limit()
--- a/wp-user-avatar/src/Membership/Models/Order/OrderEntity.php
+++ b/wp-user-avatar/src/Membership/Models/Order/OrderEntity.php
@@ -270,11 +270,12 @@
CouponService::init()->release_coupon_hold($this->id);
}
- $user = is_user_logged_in() ? wp_get_current_user()->user_login : esc_html__('payment method', 'wp-user-avatar');
-
- $this->add_note(
- sprintf(__('Order changed from %s to %s by %s', 'wp-user-avatar'), $old_status, $this->status, $user)
- );
+ $this->add_note(ppress_status_change_note(
+ 'order',
+ (string)$old_status !== '' ? (OrderStatus::get_label($old_status) ?: $old_status) : '',
+ OrderStatus::get_label($this->status) ?: $this->status,
+ ppress_status_change_actor($this->payment_method)
+ ));
do_action('ppress_order_status_updated', $order_status, $old_status, $this);
@@ -314,6 +315,8 @@
$result = OrderRepository::init()->update($this);
+ $this->forget_cached_copies();
+
do_action('ppress_order_updated', $result, $this);
return $result;
@@ -321,11 +324,28 @@
$result = OrderRepository::init()->add($this);
+ if ($result) $this->forget_cached_copies((int)$result);
+
do_action('ppress_order_added', $result, $this);
return $result;
}
+ /**
+ * OrderFactory keeps the orders it loads for the rest of the request. Once this order is saved, a copy loaded
+ * earlier is out of date, and saving that copy would undo this save. E.g. ppress_subscribe_user_to_plan() links
+ * the order to its subscription after course enrollment has loaded the order, and complete_order() then saved
+ * the earlier copy, unlinking them.
+ */
+ protected function forget_cached_copies($id = 0)
+ {
+ unset($GLOBALS['ppress_cache_transform']['order_factory_from_id_' . ($id ?: (int)$this->id)]);
+
+ if ( ! empty($this->order_key)) {
+ unset($GLOBALS['ppress_cache_transform']['order_factory_from_order_key_' . $this->order_key]);
+ }
+ }
+
public function get_customer_full_address()
{
$billing_address = $this->billing_address;
--- a/wp-user-avatar/src/Membership/Models/Subscription/SubscriptionEntity.php
+++ b/wp-user-avatar/src/Membership/Models/Subscription/SubscriptionEntity.php
@@ -472,11 +472,20 @@
public function add_note($note)
{
- $notes = $this->notes;
+ // append to the stored notes, not $this->notes: that's the list as of when this object was loaded, so
+ // writing it back dropped notes added since, including this object's own earlier ones (e.g. cancel() then
+ // expire() kept only the second status change note).
+ $notes = json_decode((string)SubscriptionRepository::init()->retrieveColumn($this->id, 'notes'), true);
+
+ if ( ! is_array($notes)) $notes = [];
$notes[] = ppress_format_date_time(time()) . '|' . $note;
- return SubscriptionRepository::init()->updateColumn($this->id, 'notes', json_encode($notes));
+ $result = SubscriptionRepository::init()->updateColumn($this->id, 'notes', json_encode($notes));
+
+ if (false !== $result) $this->notes = $notes;
+
+ return $result;
}
public function get_subscription_terms()
@@ -633,11 +642,12 @@
$response = $this->save();
- $user = is_user_logged_in() ? wp_get_current_user()->user_login : esc_html__('payment method', 'wp-user-avatar');
-
- $this->add_note(
- sprintf(__('Subscription changed from %s to %s by %s', 'wp-user-avatar'), $old_status, $this->status, $user)
- );
+ $this->add_note(ppress_status_change_note(
+ 'subscription',
+ (string)$old_status !== '' ? (SubscriptionStatus::get_label($old_status) ?: $old_status) : '',
+ SubscriptionStatus::get_label($this->status) ?: $this->status,
+ ppress_status_change_actor($this->get_payment_method())
+ ));
do_action('ppress_subscription_status_updated', $subscription_status, $old_status, $this);
--- a/wp-user-avatar/src/Membership/PaymentMethods/Stripe/PaymentHelpers.php
+++ b/wp-user-avatar/src/Membership/PaymentMethods/Stripe/PaymentHelpers.php
@@ -197,6 +197,62 @@
'caller' => __CLASS__ . '|' . __METHOD__ . '|' . __LINE__ . '|' . PPRESS_VERSION_NUMBER,
];
+ // New prices get a lookup key, so they are found again with one exact request however many prices the
+ // product has (e.g. one per donor's own amount).
+ $lookup_key = 'ppress_' . $stripe_price_id;
+
+ $existing = self::price_by_lookup_key($lookup_key);
+
+ if ( ! $existing) {
+ // prices created before lookup keys: look through the product's latest 100 (the most Stripe returns at once).
+ $existing = self::find_price_without_lookup_key($stripe_product_id, $stripe_price_id, $is_recurring, $period, $subscription, $plan);
+ }
+
+ if ($existing) {
+ return [
+ 'stripe_product_id' => $stripe_product_id,
+ 'stripe_price_id' => $existing
+ ];
+ }
+
+ $price_args['lookup_key'] = $lookup_key;
+
+ try {
+ $created_price = APIClass::stripeClient()->prices->create($price_args)->toArray();
+ } catch (Exception $e) {
+ throw new Exception($e->getMessage(), $e->getCode());
+ }
+
+ return [
+ 'stripe_product_id' => $stripe_product_id,
+ 'stripe_price_id' => $created_price['id']
+ ];
+ }
+
+ /**
+ * @param string $lookup_key
+ *
+ * @return string the active price's ID, or "".
+ */
+ protected static function price_by_lookup_key($lookup_key)
+ {
+ try {
+ $prices = APIClass::stripeClient()->prices->all(['lookup_keys' => [$lookup_key], 'active' => true, 'limit' => 1])->toArray();
+ } catch (Exception $e) {
+ return '';
+ }
+
+ return ! empty($prices['data'][0]['id']) ? (string)$prices['data'][0]['id'] : '';
+ }
+
+ /**
+ * Finds a price this site created before prices had lookup keys, in the product's latest 100 prices, and gives
+ * it its key so the next checkout finds it by key.
+ *
+ * @return string the price's ID, or "".
+ */
+ protected static function find_price_without_lookup_key($stripe_product_id, $stripe_price_id, $is_recurring, $period, $subscription, $plan)
+ {
$price_search_args = [
'product' => $stripe_product_id,
'type' => $is_recurring ? 'recurring' : 'one_time',
@@ -208,30 +264,26 @@
$price_search_args = apply_filters('ppress_stripe_price_search_args', $price_search_args, $subscription, $plan);
- $stripe_prices = APIClass::stripeClient()->prices->all($price_search_args)->toArray();
+ $stripe_prices = APIClass::stripeClient()->prices->all(array_merge(['active' => true, 'limit' => 100], $price_search_args))->toArray();
+
+ if (empty($stripe_prices['data']) || ! is_array($stripe_prices['data'])) return '';
+
+ foreach ($stripe_prices['data'] as $price) {
- if ( ! empty($stripe_prices['data']) && is_array($stripe_prices['data'])) {
+ if ( ! isset($price['metadata']['ppress_price_id']) || $price['metadata']['ppress_price_id'] != $stripe_price_id) continue;
- foreach ($stripe_prices['data'] as $price) {
- if (isset($price['metadata']['ppress_price_id']) && $price['metadata']['ppress_price_id'] == $stripe_price_id) {
- return [
- 'stripe_product_id' => $stripe_product_id,
- 'stripe_price_id' => $price['id']
- ];
+ if (empty($price['lookup_key'])) {
+ try {
+ APIClass::stripeClient()->prices->update($price['id'], ['lookup_key' => 'ppress_' . $stripe_price_id]);
+ } catch (Exception $e) {
+ // found by this search again next time.
}
}
- }
- try {
- $created_price = APIClass::stripeClient()->prices->create($price_args)->toArray();
- } catch (Exception $e) {
- throw new Exception($e->getMessage(), $e->getCode());
+ return (string)$price['id'];
}
- return [
- 'stripe_product_id' => $stripe_product_id,
- 'stripe_price_id' => $created_price['id']
- ];
+ return '';
}
/**
--- a/wp-user-avatar/src/Membership/PaymentMethods/Stripe/WebhookHandlers/CustomerSubscriptionUpdated.php
+++ b/wp-user-avatar/src/Membership/PaymentMethods/Stripe/WebhookHandlers/CustomerSubscriptionUpdated.php
@@ -23,8 +23,12 @@
$subscription = $subscription[0];
- if ($event_data['cancel_at_period_end'] === true) {
- // This is a subscription that has been cancelled but not deleted until period end
+ // cancelled in Stripe (dashboard or customer portal) to end at the period end. It stays cancelled here until then,
+ // which keeps access until it expires, as after cancelling in My Account. Stripe sends more updates while it
+ // waits; cancelling only once means those don't repeat the cancellation email, note and hooks.
+ $scheduled_cancellation = true === $event_data['cancel_at_period_end'];
+
+ if ($scheduled_cancellation && ! $subscription->is_cancelled()) {
$subscription->add_note(
sprintf(
esc_html__('Subscription is scheduled for cancellation on %s', 'wp-user-avatar'),
@@ -32,7 +36,6 @@
)
);
- // cancelling early so subscription can be set back to active down below if this isn't an immediate cancellation
$subscription->cancel();
}
@@ -43,7 +46,8 @@
case 'active':
if ( ! $subscription->is_active()) {
$subscription->activate_subscription($subscription_profile_id);
- } else {
+ } elseif ( ! $scheduled_cancellation) {
+ // e.g. the cancellation was undone in Stripe.
$subscription->status = SubscriptionStatus::ACTIVE;
}
// ensures expiration date is in sync with Stripe
@@ -52,7 +56,7 @@
case 'trialing':
if ( ! $subscription->is_active()) {
$subscription->enable_subscription_trial($subscription_profile_id);
- } else {
+ } elseif ( ! $scheduled_cancellation) {
$subscription->status = SubscriptionStatus::TRIALLING;
}
// ensures expiration date is in sync with Stripe
@@ -69,6 +73,17 @@
}
break;
case 'past_due':
+ // At a renewal or the end of a trial, Stripe starts the new period and reports the subscription as
+ // active before it charges the card, so the 'active' case above has already moved the expiration date
+ // to the end of the new, unpaid period. When the charge fails, move it back to the start of that period
+ // (the end of the last paid or trial period) so access ends after the usual grace period instead of
+ // lasting a full unpaid period. If a retry succeeds, the 'active' update moves it forward again.
+ if ( ! empty($event_data['current_period_start']) &&
+ apply_filters('ppress_stripe_past_due_end_access_at_period_start', true, $subscription, $event_data)
+ ) {
+ $subscription->expiration_date = CarbonImmutable::createFromTimestampUTC($event_data['current_period_start'])->toDateTimeString();
+ }
+
$subscription->add_note(
esc_html__('Stripe payment failed (payment is past due)', 'wp-user-avatar')
);
--- a/wp-user-avatar/src/Membership/PaymentMethods/Stripe/WebhookHandlers/InvoicePaymentSucceeded.php
+++ b/wp-user-avatar/src/Membership/PaymentMethods/Stripe/WebhookHandlers/InvoicePaymentSucceeded.php
@@ -42,14 +42,46 @@
]);
if ( ! empty($order_id)) {
- // we are not changing the expiration date because it is always in sync with stripe via
- // CustomerSubscriptionUpdated event.
- $subscription->renew(false);
+ // The expiration date is normally kept in sync with Stripe by the CustomerSubscriptionUpdated event.
+ // But when a retry pays a past-due invoice, the expiration date was moved back to the start of the
+ // unpaid period, so move it to the end of the period just paid for. Otherwise the subscription would
+ // be expired again before the 'active' update arrives.
+ $period_end = $this->get_subscription_period_end($event_data);
+
+ if ($period_end > ppress_strtotime_utc($subscription->expiration_date)) {
+ $subscription->renew(true, $period_end);
+ } else {
+ $subscription->renew(false);
+ }
}
}
}
/**
+ * The end of the subscription period an invoice paid for, from its subscription line items.
+ *
+ * @param array $event_data invoice object
+ *
+ * @return int timestamp in UTC, 0 if not found
+ */
+ public function get_subscription_period_end($event_data)
+ {
+ $period_end = 0;
+
+ $lines = $event_data['lines']['data'] ?? [];
+
+ if (is_array($lines)) {
+ foreach ($lines as $line) {
+ if (($line['type'] ?? '') == 'subscription' && ! empty($line['period']['end'])) {
+ $period_end = max($period_end, (int)$line['period']['end']);
+ }
+ }
+ }
+
+ return $period_end;
+ }
+
+ /**
* @param OrderEntity $order
* @param string $stripe_customer_id
*
--- a/wp-user-avatar/src/Membership/Repositories/CouponRepository.php
+++ b/wp-user-avatar/src/Membership/Repositories/CouponRepository.php
@@ -33,7 +33,7 @@
'is_onetime_use' => $data->is_onetime_use,
'amount' => $data->amount,
'unit' => $data->unit,
- 'plan_ids' => $data->plan_ids,
+ 'plan_ids' => wp_json_encode(array_values((array)$data->get_plan_ids())),
'usage_limit' => $data->usage_limit,
'status' => $data->status,
'start_date' => $data->start_date,
@@ -75,7 +75,7 @@
'is_onetime_use' => $data->is_onetime_use,
'amount' => $data->amount,
'unit' => $data->unit,
- 'plan_ids' => $data->plan_ids,
+ 'plan_ids' => wp_json_encode(array_values((array)$data->get_plan_ids())),
'usage_limit' => $data->usage_limit,
'status' => $data->status,
'start_date' => $data->start_date,
--- a/wp-user-avatar/src/Membership/Services/SubscriptionService.php
+++ b/wp-user-avatar/src/Membership/Services/SubscriptionService.php
@@ -10,12 +10,27 @@
use ProfilePressCoreMembershipModelsSubscriptionSubscriptionBillingFrequency;
use ProfilePressCoreMembershipModelsSubscriptionSubscriptionEntity;
use ProfilePressCoreMembershipModelsSubscriptionSubscriptionFactory;
+use ProfilePressCoreMembershipModelsSubscriptionSubscriptionStatus;
use ProfilePressCoreMembershipRepositoriesSubscriptionRepository;
use ProfilePressCoreShortcodeParserMyAccountMyAccountTag;
use ProfilePressVendorCarbonCarbonImmutable;
class SubscriptionService
{
+ /**
+ * Plan change claims this request holds, keyed by subscription ID, so it doesn't wait on its own claim.
+ *
+ * @var string[]
+ */
+ protected $held_plan_change_locks = [];
+
+ /**
+ * Duplicate plan change subscriptions to cancel at the end of the request, keyed by subscription ID.
+ *
+ * @var bool[]
+ */
+ protected $pending_conflict_cancellations = [];
+
public function __construct()
{
add_action('ppress_order_completed', [$this, 'process_plan_change_completion']);
@@ -213,28 +228,282 @@
return;
}
- $old_sub = SubscriptionFactory::fromId($old_sub_id);
+ // a request that is completing another switch from the same source (e.g. two gateway webhooks at once)
+ // must finish first, or both would see the source as not yet switched.
+ $lock = $this->wait_for_plan_change_lock($old_sub_id);
- if ( ! $old_sub->exists()) {
- return;
+ try {
+
+ if ($subscription->get_meta('_plan_change_processed') === 'true') {
+ return;
+ }
+
+ $old_sub = SubscriptionFactory::fromId($old_sub_id);
+
+ if ( ! $old_sub->exists()) {
+ return;
+ }
+
+ $switched_to_sub_id = absint($old_sub->get_meta('_upgraded_to_sub_id'));
+
+ if ($switched_to_sub_id > 0 && $switched_to_sub_id !== (int)$subscription->get_id()) {
+
+ $switched_to_sub = SubscriptionFactory::fromId($switched_to_sub_id);
+
+ if ($switched_to_sub->exists() && ! $switched_to_sub->is_pending()) {
+ $this->handle_plan_change_conflict($subscription, $old_sub, $switched_to_sub);
+
+ return;
+ }
+ }
+
+ $subscription->update_meta('_plan_change_processed', 'true');
+
+ // Do not send subscription cancelled or expired emails on plan changes
+ remove_action('ppress_subscription_cancelled', [SubscriptionCancelledNotification::init(), 'dispatch_email'], 10);
+ remove_action('ppress_subscription_expired', [SubscriptionExpiredNotification::init(), 'dispatch_email']);
+
+ $old_sub->cancel(true);
+ $old_sub->expire();
+
+ add_action('ppress_subscription_cancelled', [SubscriptionCancelledNotification::init(), 'dispatch_email'], 10, 2);
+ add_action('ppress_subscription_expired', [SubscriptionExpiredNotification::init(), 'dispatch_email']);
+
+ // Ensure customer has the new plan role even if old plan had the same role
+ $subscription->add_plan_role_to_customer();
+
+ $old_sub->update_meta('_upgraded_to_sub_id', $subscription->get_id());
+
+ } finally {
+ if (false !== $lock) {
+ $this->release_plan_change_lock($old_sub_id, $lock);
+ }
}
+ }
+
+ /**
+ * A plan change was paid for after its source subscription had already been switched to another plan.
+ *
+ * Each plan change checkout charges only the difference from the source, so a customer could start two (one
+ * after the other, with both payment pages left open), pay both, and end up with two subscriptions for the price
+ * of one. The checkout can't refuse the second one up front without breaking retries after an abandoned payment,
+ * so it's caught here: the duplicate subscription is not left active, and the order and subscription are noted
+ * for the admin to review and refund.
+ *
+ * Runs on every completion hook for the subscription, since gateways complete the order and activate the
+ * subscription in either order. The cancellation waits until the end of the request: these hooks get the
+ * caller's own subscription object, which it keeps using (and saving) afterwards, e.g.
+ * activate_subscription() then calls maybe_complete_subscription(). Changing the status mid-way wouldn't stick.
+ *
+ * @param SubscriptionEntity $subscription the duplicate.
+ * @param SubscriptionEntity $old_sub the source.
+ * @param SubscriptionEntity $switched_to_sub what the source was already switched to.
+ *
+ * @return void
+ */
+ protected function handle_plan_change_conflict($subscription, $old_sub, $switched_to_sub)
+ {
+ $subscription = SubscriptionFactory::fromId($subscription->get_id());
+
+ if (empty($subscription->get_meta('_plan_change_conflict'))) {
+
+ $subscription->update_meta('_plan_change_conflict', $switched_to_sub->get_id());
- $subscription->update_meta('_plan_change_processed', 'true');
+ $note = sprintf(
+ /* translators: 1: source subscription ID, 2: subscription it was switched to */
+ esc_html__('Plan change not applied: subscription #%1$d had already been changed to subscription #%2$d. This subscription was cancelled. Review the payment and refund it if needed.', 'wp-user-avatar'),
+ $old_sub->get_id(),
+ $switched_to_sub->get_id()
+ );
+
+ $subscription->add_note($note);
+
+ $parent_order_id = absint($subscription->get_parent_order_id());
+
+ if ($parent_order_id > 0) {
+ OrderService::init()->add_order_note($parent_order_id, $note);
+ }
+
+ ppress_log_error(sprintf(
+ 'Plan change conflict: subscription #%d was switched from #%d, which had already been switched to #%d.',
+ $subscription->get_id(),
+ $old_sub->get_id(),
+ $switched_to_sub->get_id()
+ ));
+
+ /**
+ * Fires when a paid plan change completes after its source subscription was already switched.
+ *
+ * @param SubscriptionEntity $subscription the duplicate subscription, which gets cancelled.
+ * @param SubscriptionEntity $old_sub the source subscription.
+ * @param SubscriptionEntity $switched_to_sub the subscription the source was already switched to.
+ */
+ do_action('ppress_plan_change_conflict', $subscription, $old_sub, $switched_to_sub);
+ }
+
+ $subscription_id = (int)$subscription->get_id();
+ $switched_to_sub_id = (int)$switched_to_sub->get_id();
+
+ if (isset($this->pending_conflict_cancellations[$subscription_id])) return;
+
+ $this->pending_conflict_cancellations[$subscription_id] = true;
+
+ add_action('shutdown', function () use ($subscription_id, $switched_to_sub_id) {
+ $this->cancel_conflicting_plan_change($subscription_id, $switched_to_sub_id);
+ });
+ }
+
+ /**
+ * Cancel the duplicate subscription found by handle_plan_change_conflict(), with its current state re-read.
+ *
+ * @param int $subscription_id
+ * @param int $switched_to_sub_id
+ *
+ * @return void
+ */
+ public function cancel_conflicting_plan_change($subscription_id, $switched_to_sub_id)
+ {
+ unset($this->pending_conflict_cancellations[$subscription_id]);
- // Do not send subscription cancelled or expired emails on plan changes
- remove_action('ppress_subscription_cancelled', [SubscriptionCancelledNotification::init(), 'dispatch_email'], 10);
+ $subscription = SubscriptionFactory::fromId($subscription_id);
+
+ if ( ! $subscription->exists()) return;
+
+ // the order completed but the subscription isn't activated yet. Its activation hook runs this again.
+ if ($subscription->is_pending()) return;
+
+ // already done on an earlier request.
+ if ($subscription->get_status() === SubscriptionStatus::EXPIRED || ($subscription->is_lifetime() && $subscription->is_cancelled())) {
+ return;
+ }
+
+ // the customer gets the cancellation email, not a second one for the expiry.
remove_action('ppress_subscription_expired', [SubscriptionExpiredNotification::init(), 'dispatch_email']);
- $old_sub->cancel(true);
- $old_sub->expire();
+ $subscription->cancel(true);
+ // cancel() keeps access until the end of the billing period, and expire() is a no-op for lifetime
+ // subscriptions, whose role cancel() already removed.
+ $subscription->expire();
- add_action('ppress_subscription_cancelled', [SubscriptionCancelledNotification::init(), 'dispatch_email'], 10, 2);
add_action('ppress_subscription_expired', [SubscriptionExpiredNotification::init(), 'dispatch_email']);
- // Ensure customer has the new plan role even if old plan had the same role
- $subscription->add_plan_role_to_custo