From 504de013a7f797aa80e1527c4706d313d5a04483 Mon Sep 17 00:00:00 2001 From: David Stone Date: Wed, 4 Nov 2026 20:08:36 -0700 Subject: [PATCH 1/8] fix: make frontend customer account and site management work end to end --- DESIGN.md | 26 ++++ .../class-payment-edit-admin-page.php | 4 +- inc/class-current.php | 128 ++++++++++++++---- inc/gateways/class-base-stripe-gateway.php | 16 ++- inc/gateways/class-manual-gateway.php | 20 +-- inc/ui/class-account-summary-element.php | 31 ++++- inc/ui/class-current-site-element.php | 2 +- inc/ui/class-payment-methods-element.php | 2 +- inc/ui/class-site-actions-element.php | 47 +++++-- inc/ui/class-template-switching-element.php | 6 +- tests/WP_Ultimo/Current_Test.php | 77 +++++++++++ .../account-summary-empty.php | 33 +++++ views/dashboard-widgets/account-summary.php | 5 +- views/dashboard-widgets/current-site.php | 2 +- views/shortcodes/shortcodes.php | 20 +++ 15 files changed, 355 insertions(+), 64 deletions(-) create mode 100644 views/dashboard-widgets/account-summary-empty.php diff --git a/DESIGN.md b/DESIGN.md index 7104ee977..9aa510eac 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -52,3 +52,29 @@ Keep the existing stacked widget layout on desktop and mobile. List nameservers on separate lines and allow long hostnames to wrap without truncation. Hide the summary during loading or lookup errors; preserve the existing record table and provider-managed editing controls. + +## Frontend customer accounts + +Keep account-wide membership, billing and invoices separate from site-specific +summary and limits. Account Summary must offer a sign-in link when logged out, +an owner-scoped site chooser before site selection, and a neutral no-sites state +instead of silently rendering nothing. Do not silently select the first site: +customers may own several. Once a site is selected, omit self-referential +"See More" links and show remaining trial days from the actual membership date. +Use the existing stacked widget styles on desktop and mobile, with native links +and wrapping site names; do not add fixed-width panels or a second design system. +Frontend account pages belong on the main site; customer-site admin Account +screens remain an alternative interface to the same membership. + +On combined pages, Manage must visibly land on the selected site's controls, +using a keyboard-focusable native fragment target (Account Summary is the +fallback). Your Sites clears selected-site context and returns to the page +permalink. Successful frontend deletion returns to the account landing page, +unless an explicit destination is configured; never retain a deleted-site URL. +Sites without a template initialize the selector to numeric zero so their first +selection exposes the same destructive-action confirmation as template changes. + +Payment-method changes must return from Stripe Billing Portal to the originating +account page, using a validated local destination. Show the subscription's card +override when present; otherwise show the customer's default payment method, +including after the portal clears an override while replacing the default card. diff --git a/inc/admin-pages/class-payment-edit-admin-page.php b/inc/admin-pages/class-payment-edit-admin-page.php index 5f3a9b712..81857a697 100644 --- a/inc/admin-pages/class-payment-edit-admin-page.php +++ b/inc/admin-pages/class-payment-edit-admin-page.php @@ -1186,10 +1186,10 @@ public function register_widgets(): void { 'confirm_membership' => [ 'type' => 'toggle', 'title' => __('Activate Membership?', 'ultimate-multisite'), - 'desc' => __('This payment belongs to a pending membership. If you toggle this option, this change in status will also apply to the membership. If any sites are pending, they are also going to be published automatically.', 'ultimate-multisite'), + 'desc' => __('This payment belongs to a pending or on-hold membership. Enable this option to activate or renew the membership when confirming the payment. Any pending sites will also be published automatically.', 'ultimate-multisite'), 'value' => 0, 'wrapper_html_attr' => [ - 'v-if' => 'status !== original_status && status === "completed" && membership_status === "pending"', + 'v-if' => 'status !== original_status && status === "completed" && (membership_status === "pending" || membership_status === "on-hold")', 'v-cloak' => '1', ], ], diff --git a/inc/class-current.php b/inc/class-current.php index 1acaa2786..3d5e170e1 100644 --- a/inc/class-current.php +++ b/inc/class-current.php @@ -232,20 +232,37 @@ public static function get_manage_url($id, $type = 'site') { $site_hash = \WP_Ultimo\Helpers\Hash::encode($id, $type); if ( ! is_admin()) { - $current_url = rtrim((string) wu_get_current_url(), '/'); - $url_param = self::param_key($type); + $remove = 'site' === $type ? [$url_param, self::param_key('membership')] : [$url_param]; + $url = remove_query_arg($remove, (string) wu_get_current_url()); + $parts = wp_parse_url($url); + $suffix = empty($parts['query']) ? '' : '?' . $parts['query']; + $fragment = empty($parts['fragment']) ? '' : '#' . $parts['fragment']; + $post = get_post(); + + // On combined account pages, land on the controls that actually changed. + if ('site' === $type && $post) { + if (has_shortcode($post->post_content, 'wu_current_site') || has_block('wp-ultimo/current-site', $post)) { + $fragment = '#wu-site-' . $site_hash; + } elseif (has_shortcode($post->post_content, 'wu_account_summary') || has_block('wp-ultimo/account-summary', $post)) { + $fragment = '#wu-summary-' . $site_hash; + } + } /* - * Check if the current URL already has a site parameter and remove it. + * Replace the trailing context in the path, not inside the query string. + * Site selection also clears membership context so the site's own + * membership is selected, rather than one left over from another site. */ - if (str_contains($current_url, '/' . $url_param . '/')) { - $current_url = preg_replace('/\/' . $url_param . '\/(.+)/', '/', $current_url); - } + $current_url = preg_replace('/[?#].*$/', '', $url); + $current_url = preg_replace('/\/' . preg_quote($url_param, '/') . '\/[^\/]+\/?$/', '', $current_url); + $current_url = rtrim($current_url, '/'); - $pretty_url = $current_url . '/' . $url_param . '/' . $site_hash; + $pretty_url = $current_url . '/' . $url_param . '/' . $site_hash . $suffix . $fragment; - $manage_site_url = get_option('permalink_structure') ? $pretty_url : add_query_arg($url_param, $site_hash); + $plain_url = add_query_arg($url_param, $site_hash, preg_replace('/#.*$/', '', $url)) . $fragment; + + $manage_site_url = get_option('permalink_structure') ? $pretty_url : $plain_url; } else { $manage_site_url = get_admin_url($id); } @@ -280,6 +297,17 @@ public function load_currents(): void { return; } + // Never retain an earlier context when a later URL override is rejected. + $this->site = false; + $this->customer = false; + $this->membership = false; + $this->site_set_via_request = false; + $this->customer_set_via_request = false; + $this->membership_set_via_request = false; + $site_set_via_request = false; + $customer_set_via_request = false; + $membership_set_via_request = false; + /* * `get_query_var()` reads from the global `$wp_query`, which * WordPress only populates during `parse_query` (just before @@ -322,21 +350,23 @@ public function load_currents(): void { $site_hash = wu_request($site_url_param, $site_hash_default); - $site_from_url = wu_get_site_by_hash($site_hash); + if ($site_hash) { + if ( ! is_string($site_hash)) { + return; + } - if ($site_from_url) { - $this->site_set_via_request = true; + $site = wu_get_site_by_hash($site_hash); - $site = $site_from_url; + if ( ! $this->can_access_context($site)) { + return; + } + + $site_set_via_request = true; } } else { $site = wu_get_current_site(); } - if ($site) { - $this->set_site($site); - } - $customer = wu_get_current_customer(); /** @@ -348,17 +378,23 @@ public function load_currents(): void { */ $customer_url_param = self::param_key('customer'); - $customer_from_url = wu_get_customer(wu_request($customer_url_param, 0)); + $customer_id = wu_request($customer_url_param, 0); + + if ($customer_id) { + if ( ! is_scalar($customer_id) || ! ctype_digit((string) $customer_id)) { + return; + } - if ($customer_from_url) { - $this->customer_set_via_request = true; + $customer = wu_get_customer($customer_id); - $customer = $customer_from_url; + if ( ! $this->can_access_context($customer)) { + return; + } + + $customer_set_via_request = true; } } - $this->set_customer($customer); - $membership = false; /* @@ -371,9 +407,17 @@ public function load_currents(): void { $membership_hash = wu_request($membership_url_param, $membership_hash_default); if ($membership_hash) { - $this->membership_set_via_request = true; + if ( ! is_string($membership_hash)) { + return; + } $membership = wu_get_membership_by_hash($membership_hash); + + if ( ! $this->can_access_context($membership)) { + return; + } + + $membership_set_via_request = true; } elseif ($site) { $membership = $site->get_membership(); } @@ -384,9 +428,47 @@ public function load_currents(): void { $membership = wu_get_isset($memberships, 0, false); } + if ($membership && ! $this->can_access_context($membership)) { + return; + } + + $this->site_set_via_request = $site_set_via_request; + $this->customer_set_via_request = $customer_set_via_request; + $this->membership_set_via_request = $membership_set_via_request; + + $this->set_site($site); + $this->set_customer($customer); $this->set_membership($membership); } + /** + * Authorizes account context against the authenticated user, never URL state. + * + * Hashes select objects; they are not access credentials. Pass an explicit + * customer ID to the model checks to avoid resolving this singleton again. + * + * @param \WP_Ultimo\Models\Customer|\WP_Ultimo\Models\Site|\WP_Ultimo\Models\Membership|false $context Requested object. + * @return bool + */ + private function can_access_context($context): bool { + + if ( ! $context || ! is_user_logged_in()) { + return false; + } + + if (current_user_can('manage_network')) { + return true; + } + + if ($context instanceof \WP_Ultimo\Models\Customer) { + return (int) $context->get_user_id() === get_current_user_id(); + } + + $customer = wu_get_current_customer(); + + return $customer && $context->is_customer_allowed($customer->get_id()); + } + /** * Get the current site instance. * diff --git a/inc/gateways/class-base-stripe-gateway.php b/inc/gateways/class-base-stripe-gateway.php index 95d6a627c..42249136c 100644 --- a/inc/gateways/class-base-stripe-gateway.php +++ b/inc/gateways/class-base-stripe-gateway.php @@ -824,6 +824,7 @@ public function get_change_payment_method_url($membership) { [ 'wu-stripe-portal' => true, 'membership' => $membership->get_hash(), + 'redirect_url' => wu_request('redirect_url', wu_get_current_url()), ], home_url('/') ); @@ -848,11 +849,16 @@ public function get_payment_method_display($membership) { $subscription = $this->get_stripe_client()->subscriptions->retrieve( $sub_id, - ['expand' => ['default_payment_method']] + ['expand' => ['default_payment_method', 'customer.invoice_settings.default_payment_method']] ); $pm = $subscription->default_payment_method; + // Portal updates may clear the subscription override to use the customer default. + if ( ! $pm) { + $pm = $subscription->customer->invoice_settings->default_payment_method ?? null; + } + if ( ! $pm || ! $pm->card) { return null; } @@ -906,12 +912,14 @@ public function maybe_redirect_to_portal(): void { $s_customer_id = $membership->get_gateway_customer_id(); $stored_redirect = get_user_meta(get_current_user_id(), '_wu_change_payment_redirect', true); + $redirect_url = wu_request('redirect_url', $stored_redirect); + $fallback_url = remove_query_arg(['wu-stripe-portal', 'redirect_url'], wu_get_current_url()); - if ($stored_redirect) { + if ($redirect_url && is_string($redirect_url)) { delete_user_meta(get_current_user_id(), '_wu_change_payment_redirect'); - $return_url = add_query_arg('updated', 'payment_method', $stored_redirect); + $return_url = add_query_arg('updated', 'payment_method', wp_validate_redirect($redirect_url, $fallback_url)); } else { - $return_url = remove_query_arg('wu-stripe-portal', wu_get_current_url()); + $return_url = $fallback_url; } try { diff --git a/inc/gateways/class-manual-gateway.php b/inc/gateways/class-manual-gateway.php index 623ef28bb..235fe4e37 100644 --- a/inc/gateways/class-manual-gateway.php +++ b/inc/gateways/class-manual-gateway.php @@ -215,13 +215,7 @@ public function process_checkout($payment, $membership, $customer, $cart, $type) * simply throw a exception and Ultimate Multisite will * catch it and rollback any changes. */ - if ('new' === $type) { - - // Your logic here. - } elseif ('renewal' === $type) { - - // Your logic here. - } elseif ('downgrade' === $type) { + if ('downgrade' === $type) { /* * When downgrading, we need to schedule a swap for the end of the * current expiration date. @@ -238,7 +232,7 @@ public function process_checkout($payment, $membership, $customer, $cart, $type) * Saves the membership with the changes. */ $status = $membership->save(); - } elseif ('upgrade' === $type || 'addon' === $type) { + } elseif (in_array($type, ['upgrade', 'addon', 'reactivation'], true)) { /* * After everything is said and done, * we need to swap the membership to the new products @@ -254,7 +248,12 @@ public function process_checkout($payment, $membership, $customer, $cart, $type) * It doesn't save the membership, though, so * you'll have to do that manually (example below). */ - $membership->swap($cart); + if ('reactivation' !== $type) { + $membership->swap($cart); + } + + $membership->set_gateway($this->get_id()); + $membership->set_auto_renew(false); /* * Mark the membership as pending, as we need to @@ -333,7 +332,8 @@ public function process_cancellation($membership, $customer) {} * @param \WP_Ultimo\Models\Payment $payment The payment associated with the checkout. * @param \WP_Ultimo\Models\Membership $membership The membership. * @param \WP_Ultimo\Models\Customer $customer The customer checking out. - * @return void|bool + * @throws \Exception When the refund fails. + * @return void */ public function process_refund($amount, $payment, $membership, $customer): void { diff --git a/inc/ui/class-account-summary-element.php b/inc/ui/class-account-summary-element.php index b7dc1a034..09d2c8828 100644 --- a/inc/ui/class-account-summary-element.php +++ b/inc/ui/class-account-summary-element.php @@ -121,7 +121,7 @@ public function get_title() { */ public function get_description() { - return __('Displays a summary of the customer\'s account including membership and site overview.', 'ultimate-multisite'); + return __('Displays the selected site\'s plan, trial time and disk usage. On the main-site frontend, customers can select a site to view its summary.', 'ultimate-multisite'); } /** @@ -220,7 +220,11 @@ public function setup() { $this->site = WP_Ultimo()->currents->get_site(); - if ( ! $this->site || ! $this->site->is_customer_allowed()) { + if ( ! $this->site) { + return; + } + + if ( ! $this->site->is_customer_allowed()) { $this->set_display(false); return; @@ -240,8 +244,18 @@ public function setup() { is_multisite() && restore_current_blog(); + $trial_days = 0; + + if ($this->membership && 'trialing' === $this->membership->get_status()) { + $trial_end = strtotime($this->membership->get_date_trial_end() . ' UTC'); + + if ($trial_end) { + $trial_days = max(0, (int) ceil(($trial_end - time()) / DAY_IN_SECONDS)); + } + } + $this->atts = [ - 'site_trial' => 0, // @todo: fix this + 'site_trial' => $trial_days, 'space_used' => $space_used, 'space_allowed' => $space_allowed, 'percentage' => $percentage, @@ -298,8 +312,15 @@ public function output($atts, $content = null) { $this->ensure_setup(); - // Return empty if no site available (e.g., during SEO processing) if ( ! $this->site) { + if ( ! is_admin()) { + $customer = WP_Ultimo()->currents->get_customer(); + + $atts['sites'] = $customer ? $customer->get_sites() : []; + + wu_get_template('dashboard-widgets/account-summary-empty', $atts); + } + return; } @@ -311,6 +332,8 @@ public function output($atts, $content = null) { $atts['product'] = $this->product; + $atts['hide_manage_link'] = WP_Ultimo()->currents->is_site_set_via_request(); + wu_get_template('dashboard-widgets/account-summary', $atts); } diff --git a/inc/ui/class-current-site-element.php b/inc/ui/class-current-site-element.php index d38bfc3e0..ca0849a21 100644 --- a/inc/ui/class-current-site-element.php +++ b/inc/ui/class-current-site-element.php @@ -384,7 +384,7 @@ public function output($atts, $content = null) { $my_sites_id = $atts['breadcrumbs_my_sites_page']; - $my_sites_url = empty($my_sites_id) ? remove_query_arg('site') : get_page_link($my_sites_id); + $my_sites_url = empty($my_sites_id) ? get_permalink() : get_page_link($my_sites_id); $atts['my_sites_url'] = is_admin() ? admin_url('admin.php?page=sites') : $my_sites_url; diff --git a/inc/ui/class-payment-methods-element.php b/inc/ui/class-payment-methods-element.php index 651d0b387..47e3aec6f 100644 --- a/inc/ui/class-payment-methods-element.php +++ b/inc/ui/class-payment-methods-element.php @@ -194,7 +194,7 @@ public function output($atts, $content = null) { $gateway_display = ''; if ($gateway) { - $gateway_display = $gateway->get_title(); + $gateway_display = $gateway->get_public_title(); $payment_info = $gateway->get_payment_method_display($this->membership); $change_url = $gateway->get_change_payment_method_url($this->membership); } diff --git a/inc/ui/class-site-actions-element.php b/inc/ui/class-site-actions-element.php index 13cc498ee..5921ffbd2 100644 --- a/inc/ui/class-site-actions-element.php +++ b/inc/ui/class-site-actions-element.php @@ -476,7 +476,7 @@ public function get_danger_zone_actions($atts) { 'delete_site', [ 'site' => $this->site->get_hash(), - 'redirect_url' => ! $atts['redirect_after_delete'] ? false : get_page_link($atts['redirect_after_delete']), + 'redirect_url' => $atts['redirect_after_delete'] ? get_page_link($atts['redirect_after_delete']) : (is_admin() ? user_admin_url() : get_permalink()), ] ), ], @@ -917,13 +917,7 @@ public function handle_change_email(): void { wp_send_json_error($user_id); } - // Update customer email if exists. - $customer = wu_get_current_customer(); - - if ($customer) { - $customer->set_email_address($new_email); - $customer->save(); - } + // Customer::get_email_address() reads the linked WordPress user's email. $referer = isset($_SERVER['HTTP_REFERER']) ? sanitize_url(wp_unslash($_SERVER['HTTP_REFERER'])) : ''; @@ -1006,6 +1000,12 @@ public function handle_change_default_site(): void { $new_primary_site = wu_request('new_primary_site'); + if ( ! is_scalar($new_primary_site) || ! ctype_digit((string) $new_primary_site) || ! isset(get_blogs_of_user(get_current_user_id())[ (int) $new_primary_site ])) { + wp_send_json_error(new \WP_Error('invalid-site', __('Please select a site from your account.', 'ultimate-multisite'))); + + return; + } + if ($new_primary_site) { update_user_meta(get_current_user_id(), 'primary_blog', $new_primary_site); $referer = isset($_SERVER['HTTP_REFERER']) ? sanitize_url(wp_unslash($_SERVER['HTTP_REFERER'])) : ''; @@ -1317,7 +1317,21 @@ public function handle_cancel_membership(): void { 'other' => wu_request('cancellation_explanation'), ]; - $reason = wu_get_isset($cancellation_options, wu_request('cancellation_reason'), ''); + if (__('CANCEL', 'ultimate-multisite') !== wu_request('confirm')) { + wp_send_json_error(new \WP_Error('not-confirmed', __('Please type CANCEL to confirm the membership cancellation.', 'ultimate-multisite'))); + + return; + } + + $reason_key = wu_request('cancellation_reason', ''); + + if ( ! is_string($reason_key) || ! array_key_exists($reason_key, $cancellation_options)) { + wp_send_json_error(new \WP_Error('invalid-reason', __('Please select a cancellation reason.', 'ultimate-multisite'))); + + return; + } + + $reason = $cancellation_options[ $reason_key ]; try { /* * Cancel the subscription on the payment gateway before @@ -1493,14 +1507,21 @@ public function handle_resubscribe_membership(): void { } /* - * Build the checkout URL pre-filled with the customer's previous plan. - * The products[] query parameter pre-selects the plan on the checkout form. + * Reuse the existing membership, rather than starting a new site signup. + * Reactivation carts restore the original products themselves. Passing + * product slugs in GET conflicts with the form's product IDs in POST. */ - $checkout_url = wu_get_registration_url(); + $checkout_url = wu_get_membership_update_url($membership); + + // Preselect the required product field without conflicting GET products. + $session = wu_get_session('signup'); + $signup = (array) $session->get('signup'); + $signup['products'] = [$plan->get_id()]; + $session->set('signup', $signup); + $session->commit(); $checkout_url = add_query_arg( [ - 'products[]' => $plan->get_slug(), 'wu_resubscribe' => $membership->get_hash(), ], $checkout_url diff --git a/inc/ui/class-template-switching-element.php b/inc/ui/class-template-switching-element.php index ea1bd2afd..71a4cd1e3 100644 --- a/inc/ui/class-template-switching-element.php +++ b/inc/ui/class-template-switching-element.php @@ -721,13 +721,13 @@ public function output($atts, $content = null) { * giving Vue a chance to bind it before the `template_id` * watcher runs. The watcher itself also defends against the * inverse ordering (see template-switching.js: it bails out - * early when original_template_id <= 0). + * early when original_template_id < 0). */ $checkout_fields['template_id'] = [ 'type' => 'hidden', 'html_attr' => [ - 'v-init:original_template_id' => $this->site->get_template_id(), - 'v-init:template_id' => $this->site->get_template_id(), + 'v-init:original_template_id' => $current_template_id, + 'v-init:template_id' => $current_template_id, 'v-model' => 'template_id', ], ]; diff --git a/tests/WP_Ultimo/Current_Test.php b/tests/WP_Ultimo/Current_Test.php index 279695fa5..5d687a611 100644 --- a/tests/WP_Ultimo/Current_Test.php +++ b/tests/WP_Ultimo/Current_Test.php @@ -440,4 +440,81 @@ public function test_load_currents_skips_rerun_during_ajax(): void { remove_filter('wp_doing_ajax', '__return_true'); } + + /** URL-selected account objects require the real owner's authentication. */ + public function test_request_context_requires_ownership(): void { + + $owner_id = self::factory()->user->create(['role' => 'subscriber']); + $stranger_id = self::factory()->user->create(['role' => 'subscriber']); + $admin_id = self::factory()->user->create(['role' => 'administrator']); + $customer = wu_create_customer(['user_id' => $owner_id]); + $stranger = wu_create_customer(['user_id' => $stranger_id]); + $this->assertNotWPError($customer); + $this->assertNotWPError($stranger); + + $membership = wu_create_membership( + [ + 'customer_id' => $customer->get_id(), + 'status' => 'active', + 'skip_validation' => true, + ] + ); + $this->assertNotWPError($membership); + + $site = wu_get_site(self::factory()->blog->create(['user_id' => $owner_id])); + $site->set_type('customer_owned'); + $site->set_customer_id($customer->get_id()); + $site->set_membership_id($membership->get_id()); + $this->assertNotWPError($site->save()); + + $this->go_to(home_url('/')); + set_current_screen('front'); + grant_super_admin($admin_id); + + try { + foreach ([$owner_id, $stranger_id, 0, $admin_id] as $viewer_id) { + wp_set_current_user($viewer_id); + + foreach (['membership', 'site', 'pretty_site', 'customer', 'spoofed_customer'] as $context_type) { + $_GET = []; + $_REQUEST = []; + set_query_var('site_hash', ''); + + if ('pretty_site' === $context_type) { + set_query_var('site_hash', $site->get_hash()); + } elseif ('spoofed_customer' === $context_type) { + $_GET = [ + 'customer' => $customer->get_id(), + 'membership' => $membership->get_hash(), + ]; + } else { + $values = [ + 'membership' => $membership->get_hash(), + 'site' => $site->get_hash(), + 'customer' => $customer->get_id(), + ]; + $_GET = [$context_type => $values[$context_type]]; + } + + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Synthetic request selection; ownership is the boundary under test. + $_REQUEST = $_GET; + $this->current->load_currents(); + + if (in_array($viewer_id, [$owner_id, $admin_id], true)) { + $this->assertSame($membership->get_id(), $this->current->get_membership()->get_id(), $context_type); + } else { + $this->assertFalse($this->current->get_membership(), $context_type); + $this->assertFalse($this->current->get_customer(), $context_type); + $this->assertFalse($this->current->get_site(), $context_type); + $this->assertFalse($this->current->is_site_set_via_request()); + $this->assertFalse($this->current->is_membership_set_via_request()); + } + } + } + } finally { + revoke_super_admin($admin_id); + set_query_var('site_hash', ''); + wp_set_current_user(0); + } + } } diff --git a/views/dashboard-widgets/account-summary-empty.php b/views/dashboard-widgets/account-summary-empty.php new file mode 100644 index 000000000..5ab0adaf1 --- /dev/null +++ b/views/dashboard-widgets/account-summary-empty.php @@ -0,0 +1,33 @@ + +
+
+ +

+ + +

+ + +

+ + +
+
diff --git a/views/dashboard-widgets/account-summary.php b/views/dashboard-widgets/account-summary.php index bf6a38b6c..d3d625224 100644 --- a/views/dashboard-widgets/account-summary.php +++ b/views/dashboard-widgets/account-summary.php @@ -6,8 +6,9 @@ */ defined('ABSPATH') || exit; +// phpcs:disable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase -- className is the shared block/template attribute. ?> -
+
@@ -24,7 +25,7 @@ - +
diff --git a/views/dashboard-widgets/current-site.php b/views/dashboard-widgets/current-site.php index 152332c34..c8ee236a4 100644 --- a/views/dashboard-widgets/current-site.php +++ b/views/dashboard-widgets/current-site.php @@ -7,7 +7,7 @@ defined('ABSPATH') || exit; ?> -
+
diff --git a/views/shortcodes/shortcodes.php b/views/shortcodes/shortcodes.php index 8f38792db..2d9d1302e 100644 --- a/views/shortcodes/shortcodes.php +++ b/views/shortcodes/shortcodes.php @@ -15,6 +15,26 @@
+
+
+

+

+
[wu_account_summary]
+[wu_current_membership]
+[wu_billing_info]
+[wu_payment_methods]
+[wu_invoices]
+[wu_current_site]
+[wu_limits]
+[wu_site_actions]
+

+

Memberships > Default Membership Update Page.', 'ultimate-multisite'); ?>

+

[wu_checkout slug="wu-checkout"]

+

+

+
+
+
From 8d6823d539e59d8b39a5db2f984ffa9a2a58793f Mon Sep 17 00:00:00 2001 From: David Stone Date: Wed, 4 Nov 2026 20:23:12 -0700 Subject: [PATCH 2/8] test: restore account singleton state after ownership regression checks --- tests/WP_Ultimo/Current_Test.php | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/tests/WP_Ultimo/Current_Test.php b/tests/WP_Ultimo/Current_Test.php index 5d687a611..5bbd88d16 100644 --- a/tests/WP_Ultimo/Current_Test.php +++ b/tests/WP_Ultimo/Current_Test.php @@ -444,6 +444,9 @@ public function test_load_currents_skips_rerun_during_ajax(): void { /** URL-selected account objects require the real owner's authentication. */ public function test_request_context_requires_ownership(): void { + $saved_current = clone $this->current; + $saved_user_id = get_current_user_id(); + $owner_id = self::factory()->user->create(['role' => 'subscriber']); $stranger_id = self::factory()->user->create(['role' => 'subscriber']); $admin_id = self::factory()->user->create(['role' => 'administrator']); @@ -514,7 +517,15 @@ public function test_request_context_requires_ownership(): void { } finally { revoke_super_admin($admin_id); set_query_var('site_hash', ''); - wp_set_current_user(0); + wp_set_current_user($saved_user_id); + + // Do not leave the final synthetic membership in the shared singleton. + foreach ((new \ReflectionClass(Current::class))->getProperties() as $property) { + if ( ! $property->isStatic()) { + $property->setAccessible(true); + $property->setValue($this->current, $property->getValue($saved_current)); + } + } } } } From 46031b735b50e31ad83435ca90baffd25644ef0d Mon Sep 17 00:00:00 2001 From: David Stone Date: Thu, 5 Nov 2026 15:23:59 -0700 Subject: [PATCH 3/8] fix: preserve account block settings and style editor previews --- DESIGN.md | 7 +++++++ inc/builders/block-editor/assets/js/blocks.js | 3 ++- inc/builders/block-editor/assets/js/blocks.min.js | 2 +- .../class-block-editor-widget-manager.php | 15 ++++++++++++++- inc/ui/class-base-element.php | 7 ++++++- 5 files changed, 30 insertions(+), 4 deletions(-) diff --git a/DESIGN.md b/DESIGN.md index 9aa510eac..68fb6b7d2 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -78,3 +78,10 @@ Payment-method changes must return from Stripe Billing Portal to the originating account page, using a validated local destination. Show the subscription's card override when present; otherwise show the customer's default payment method, including after the portal clears an override while replacing the default card. + +Native account blocks share shortcode renderers, settings and ownership checks. +Load widget preview styles inside the block editor canvas, including iframe +editors. Numeric controls save integers and toggle defaults use booleans. Group +and Columns layouts must preserve nested element attributes during early setup, +especially the Checkout form slug. Editor previews use sample data; verify real +customer actions on the published page rather than treating a preview as proof. diff --git a/inc/builders/block-editor/assets/js/blocks.js b/inc/builders/block-editor/assets/js/blocks.js index 92be99e0e..96b762590 100644 --- a/inc/builders/block-editor/assets/js/blocks.js +++ b/inc/builders/block-editor/assets/js/blocks.js @@ -109,7 +109,8 @@ const obj = {}; - obj[ field_slug ] = value; + // NumberControl emits strings; the block REST schema requires integers. + obj[ field_slug ] = field.type === 'number' ? Math.trunc(Number(value)) : value; props.setAttributes(obj); diff --git a/inc/builders/block-editor/assets/js/blocks.min.js b/inc/builders/block-editor/assets/js/blocks.min.js index 3b527ef3a..096a41135 100644 --- a/inc/builders/block-editor/assets/js/blocks.min.js +++ b/inc/builders/block-editor/assets/js/blocks.min.js @@ -1 +1 @@ -((e,p,c,d)=>{let h=p.createElement,l=e.registerBlockType,o=wp.serverSideRender,g=wp.components.PanelBody,m=wp.components.TextControl,w=wp.components.__experimentalNumberControl,b=wp.components.RangeControl,v=wp.components.ToggleControl,f=wp.components.TextareaControl,y=wp.components.Notice,k=wp.components.SelectControl,C=wp.blockEditor.InspectorControls,_=wp.compose.useDebounce||(e=>e);function x(t){let[e,n]=p.useState("");return h(m,{label:t.label,value:e,onChange(e){n(e),t.onSearch(e)}})}function R(t){var[e,n]=p.useState(""),n=_(n,300),l=String(t.value||0);let s=Number(l)||0,r=e.trim();e=wp.data.useSelect(function(e){var t=e("core"),e=e("core/editor"),e=e&&e.getCurrentPostId?Number(e.getCurrentPostId()):0,n={status:"publish",per_page:20,_fields:"id,title",search:r,search_columns:"post_title"},l=["postType","page",s,{_fields:"id,title,status"}],o=["postType","page",n],i=2<=r.length,n=(0{let i=[],a=[],s=null,r=null,u=!1,p=!0;return d.each(e,function(e,n){"group"===e.type&&(t=e.fields,(e=d.first(d.values(t))).desc="",n=d.first(d.keys(t)));var t=e.page_search?R:((e,t)=>{let n=m;switch(e){case"toggle":n=v;break;case"number":n=t.max&&t.min?b:w;break;case"textarea":n=f;break;case"select":n=k;break;case"note":n=y;break;default:n=m}return n})(e.type,e);d.isObject(e.required)||(e.required={});let l=!0;d.each(e.required,function(e,t){l=o.attributes[t]==e}),l&&a.push(h(t,{key:n,label:e.title,help:e.desc,value:o.attributes[n],checked:o.attributes[n],options:(e=>{let n=[];return d.each(e,function(e,t){n.push({label:e,value:t})}),n})(e.options),placeholder:e.placeholder,min:e.min,max:e.max,onChange(e){var t={};t[n]=e,o.setAttributes(t)}})),"header"===e.type&&(a.pop(),(u=null!==s?!0:u)&&(i.push(h(g,{key:r,title:s.title,description:s.desc,initialOpen:p},a)),p=!1),s=e,r=n,a=[])}),i.push(h(g,{key:r,title:s.title,help:s.desc,initialOpen:p},a)),h(C,{key:"wp-ultimo"},i)})(t.fields,e)]},save(){return null}})})})(window.wp.blocks,window.wp.element,window.wp.components,window._); \ No newline at end of file +((e,p,c,d)=>{let h=p.createElement,l=e.registerBlockType,o=wp.serverSideRender,m=wp.components.PanelBody,g=wp.components.TextControl,w=wp.components.__experimentalNumberControl,b=wp.components.RangeControl,v=wp.components.ToggleControl,f=wp.components.TextareaControl,y=wp.components.Notice,k=wp.components.SelectControl,C=wp.blockEditor.InspectorControls,_=wp.compose.useDebounce||(e=>e);function x(t){let[e,n]=p.useState("");return h(g,{label:t.label,value:e,onChange(e){n(e),t.onSearch(e)}})}function R(t){var[e,n]=p.useState(""),n=_(n,300),l=String(t.value||0);let s=Number(l)||0,r=e.trim();e=wp.data.useSelect(function(e){var t=e("core"),e=e("core/editor"),e=e&&e.getCurrentPostId?Number(e.getCurrentPostId()):0,n={status:"publish",per_page:20,_fields:"id,title",search:r,search_columns:"post_title"},l=["postType","page",s,{_fields:"id,title,status"}],o=["postType","page",n],i=2<=r.length,n=(0{let t=[],a=[],s=null,r=null,u=!1,p=!0;return d.each(e,function(n,l){"group"===n.type&&(e=n.fields,(n=d.first(d.values(e))).desc="",l=d.first(d.keys(e)));var e=n.page_search?R:((e,t)=>{let n=g;switch(e){case"toggle":n=v;break;case"number":n=t.max&&t.min?b:w;break;case"textarea":n=f;break;case"select":n=k;break;case"note":n=y;break;default:n=g}return n})(n.type,n);d.isObject(n.required)||(n.required={});let o=!0;d.each(n.required,function(e,t){o=i.attributes[t]==e}),o&&a.push(h(e,{key:l,label:n.title,help:n.desc,value:i.attributes[l],checked:i.attributes[l],options:(e=>{let n=[];return d.each(e,function(e,t){n.push({label:e,value:t})}),n})(n.options),placeholder:n.placeholder,min:n.min,max:n.max,onChange(e){var t={};t[l]="number"===n.type?Math.trunc(Number(e)):e,i.setAttributes(t)}})),"header"===n.type&&(a.pop(),(u=null!==s?!0:u)&&(t.push(h(m,{key:r,title:s.title,description:s.desc,initialOpen:p},a)),p=!1),s=n,r=l,a=[])}),t.push(h(m,{key:r,title:s.title,help:s.desc,initialOpen:p},a)),h(C,{key:"wp-ultimo"},t)})(t.fields,e)]},save(){return null}})})})(window.wp.blocks,window.wp.element,window.wp.components,window._); \ No newline at end of file diff --git a/inc/builders/block-editor/class-block-editor-widget-manager.php b/inc/builders/block-editor/class-block-editor-widget-manager.php index 1a5e89ec0..1a312da59 100644 --- a/inc/builders/block-editor/class-block-editor-widget-manager.php +++ b/inc/builders/block-editor/class-block-editor-widget-manager.php @@ -125,6 +125,7 @@ public function register_block($element): void { [ 'attributes' => $attributes, 'editor_script' => 'wu-blocks', + 'editor_style' => 'wu-admin', 'render_callback' => \Closure::fromCallable([$element, 'get_content']), ] ); @@ -236,9 +237,21 @@ public function get_attributes_from_fields($element) { } $default_value = wu_get_isset($defaults, $field_id, ''); + $value = wu_get_isset($field, 'value', $default_value); + + // Block defaults must have the same types as their REST schema. + if ( ! is_callable($value)) { + if ('boolean' === $type) { + $value = (bool) $value; + } elseif ('integer' === $type) { + $value = (int) $value; + } else { + $value = (string) $value; + } + } $_fields[ $field_id ] = [ - 'default' => wu_get_isset($field, 'value', $default_value), + 'default' => $value, 'type' => $type, ]; } diff --git a/inc/ui/class-base-element.php b/inc/ui/class-base-element.php index 1edd6024b..0196601a3 100644 --- a/inc/ui/class-base-element.php +++ b/inc/ui/class-base-element.php @@ -573,10 +573,15 @@ protected function maybe_extract_arguments($content, $type = 'shortcode') { */ $block_content = parse_blocks($content); - foreach ($block_content as $block) { + while ($block_content) { + $block = array_shift($block_content); + if ($this->get_id() === $block['blockName']) { return $block['attrs']; } + + // Groups and Columns are normal account-page layout containers. + $block_content = array_merge($block['innerBlocks'] ?? [], $block_content); } return false; From 0de65df0956706613369affd7f5f452c0d40e1ad Mon Sep 17 00:00:00 2001 From: David Stone Date: Thu, 5 Nov 2026 22:30:10 -0700 Subject: [PATCH 4/8] test: protect account context cleanup during fixture setup --- tests/WP_Ultimo/Current_Test.php | 63 +++++++++++++++++--------------- 1 file changed, 34 insertions(+), 29 deletions(-) diff --git a/tests/WP_Ultimo/Current_Test.php b/tests/WP_Ultimo/Current_Test.php index 5bbd88d16..d105b1f6d 100644 --- a/tests/WP_Ultimo/Current_Test.php +++ b/tests/WP_Ultimo/Current_Test.php @@ -446,35 +446,37 @@ public function test_request_context_requires_ownership(): void { $saved_current = clone $this->current; $saved_user_id = get_current_user_id(); - - $owner_id = self::factory()->user->create(['role' => 'subscriber']); - $stranger_id = self::factory()->user->create(['role' => 'subscriber']); - $admin_id = self::factory()->user->create(['role' => 'administrator']); - $customer = wu_create_customer(['user_id' => $owner_id]); - $stranger = wu_create_customer(['user_id' => $stranger_id]); - $this->assertNotWPError($customer); - $this->assertNotWPError($stranger); - - $membership = wu_create_membership( - [ - 'customer_id' => $customer->get_id(), - 'status' => 'active', - 'skip_validation' => true, - ] - ); - $this->assertNotWPError($membership); - - $site = wu_get_site(self::factory()->blog->create(['user_id' => $owner_id])); - $site->set_type('customer_owned'); - $site->set_customer_id($customer->get_id()); - $site->set_membership_id($membership->get_id()); - $this->assertNotWPError($site->save()); - - $this->go_to(home_url('/')); - set_current_screen('front'); - grant_super_admin($admin_id); + $saved_hash = get_query_var('site_hash', ''); + $admin_id = 0; try { + $owner_id = self::factory()->user->create(['role' => 'subscriber']); + $stranger_id = self::factory()->user->create(['role' => 'subscriber']); + $admin_id = self::factory()->user->create(['role' => 'administrator']); + $customer = wu_create_customer(['user_id' => $owner_id]); + $stranger = wu_create_customer(['user_id' => $stranger_id]); + $this->assertNotWPError($customer); + $this->assertNotWPError($stranger); + + $membership = wu_create_membership( + [ + 'customer_id' => $customer->get_id(), + 'status' => 'active', + 'skip_validation' => true, + ] + ); + $this->assertNotWPError($membership); + + $site = wu_get_site(self::factory()->blog->create(['user_id' => $owner_id])); + $site->set_type('customer_owned'); + $site->set_customer_id($customer->get_id()); + $site->set_membership_id($membership->get_id()); + $this->assertNotWPError($site->save()); + + $this->go_to(home_url('/')); + set_current_screen('front'); + grant_super_admin($admin_id); + foreach ([$owner_id, $stranger_id, 0, $admin_id] as $viewer_id) { wp_set_current_user($viewer_id); @@ -515,8 +517,11 @@ public function test_request_context_requires_ownership(): void { } } } finally { - revoke_super_admin($admin_id); - set_query_var('site_hash', ''); + if ($admin_id) { + revoke_super_admin($admin_id); + } + + set_query_var('site_hash', $saved_hash); wp_set_current_user($saved_user_id); // Do not leave the final synthetic membership in the shared singleton. From 9eb96d9fcc55de1495e8b86fb8dc0c9ab11fc221 Mon Sep 17 00:00:00 2001 From: David Stone Date: Sat, 21 Nov 2026 09:59:13 -0700 Subject: [PATCH 5/8] fix: address review findings in the account re-land Manual gateway / payment confirmation - A reactivation checkout no longer moves a cancelled or expired membership to on-hold. On-hold counts as active, so access was restored before the manual payment was confirmed. The membership now stays inactive until an administrator confirms the payment, which calls reactivate() like the Stripe and PayPal gateways (clears the cancellation date, fires the reactivation hooks, records the gateway). - Add-on payments keep the existing recurring gateway and renewal setting; only an upgrade moves a membership to the Manual gateway. Switching an add-on would cancel a Stripe subscription. - The "Activate Membership?" toggle only shows when handle_save() can act on it: a pending payment being completed on a membership that is not running. Stripe Billing Portal - Encode the nested return URL so its query string cannot leak into the portal link, and read it back without sanitize_text_field(), which strips percent-encoded octets (non-ASCII slugs). - Do not show the customer default card when the subscription has a legacy default_source, which Stripe charges first. Block editor - A cleared or non-numeric number control keeps the last valid integer instead of saving 0 or NaN. Tests: reactivation stays inactive, add-on keeps its gateway, upgrade moves to Manual, and a cancelled membership is reactivated on confirmation. --- .../class-payment-edit-admin-page.php | 17 ++- inc/builders/block-editor/assets/js/blocks.js | 21 ++- .../block-editor/assets/js/blocks.min.js | 2 +- inc/gateways/class-base-stripe-gateway.php | 36 ++++- inc/gateways/class-manual-gateway.php | 24 +++- .../Payment_Edit_Admin_Page_Test.php | 17 ++- .../Manual_Gateway_Checkout_Process_Test.php | 129 ++++++++++++++++++ 7 files changed, 228 insertions(+), 18 deletions(-) diff --git a/inc/admin-pages/class-payment-edit-admin-page.php b/inc/admin-pages/class-payment-edit-admin-page.php index 6ace77d1b..47ff1cbec 100644 --- a/inc/admin-pages/class-payment-edit-admin-page.php +++ b/inc/admin-pages/class-payment-edit-admin-page.php @@ -1186,10 +1186,11 @@ public function register_widgets(): void { 'confirm_membership' => [ 'type' => 'toggle', 'title' => __('Activate Membership?', 'ultimate-multisite'), - 'desc' => __('This payment belongs to a pending or on-hold membership. Enable this option to activate or renew the membership when confirming the payment. Any pending sites will also be published automatically.', 'ultimate-multisite'), + 'desc' => __('This payment belongs to a membership that is not active yet. Enable this option to activate, renew or reactivate it when confirming the payment. Any pending sites will also be published automatically.', 'ultimate-multisite'), 'value' => 0, 'wrapper_html_attr' => [ - 'v-if' => 'status !== original_status && status === "completed" && (membership_status === "pending" || membership_status === "on-hold")', + // Mirrors handle_save(): only a pending payment being completed can confirm a membership. + 'v-if' => 'original_status === "pending" && status === "completed" && membership_status !== "active" && membership_status !== "trialing"', 'v-cloak' => '1', ], ], @@ -1487,6 +1488,18 @@ public function handle_save(): bool { if ($is_initial_payment) { $membership->set_status(Membership_Status::ACTIVE); $membership_saved = $membership->save(); + } elseif (in_array($membership->get_status(), [Membership_Status::CANCELLED, Membership_Status::EXPIRED], true)) { + /* + * A paid reactivation. Like the Stripe and PayPal gateways, use + * reactivate() so the cancellation date clears and the reactivation + * hooks fire. Cancelling clears the gateway: record how this + * membership was paid so the account page shows it. + */ + if ( ! $membership->get_gateway() && $payment->get_gateway()) { + $membership->set_gateway($payment->get_gateway()); + } + + $membership_saved = $membership->reactivate(false); } else { $membership_saved = $membership->renew(false, Membership_Status::ACTIVE); } diff --git a/inc/builders/block-editor/assets/js/blocks.js b/inc/builders/block-editor/assets/js/blocks.js index 96b762590..6a3985ddd 100644 --- a/inc/builders/block-editor/assets/js/blocks.js +++ b/inc/builders/block-editor/assets/js/blocks.js @@ -109,8 +109,25 @@ const obj = {}; - // NumberControl emits strings; the block REST schema requires integers. - obj[ field_slug ] = field.type === 'number' ? Math.trunc(Number(value)) : value; + if (field.type === 'number') { + + // NumberControl emits strings, and '' while cleared; the block schema requires integers. + const number = parseInt(value, 10); + + // Keep the last valid number rather than saving an invalid one mid-edit. + if (Number.isNaN(number)) { + + return; + + } + + obj[ field_slug ] = number; + + } else { + + obj[ field_slug ] = value; + + } props.setAttributes(obj); diff --git a/inc/builders/block-editor/assets/js/blocks.min.js b/inc/builders/block-editor/assets/js/blocks.min.js index 096a41135..918c39a19 100644 --- a/inc/builders/block-editor/assets/js/blocks.min.js +++ b/inc/builders/block-editor/assets/js/blocks.min.js @@ -1 +1 @@ -((e,p,c,d)=>{let h=p.createElement,l=e.registerBlockType,o=wp.serverSideRender,m=wp.components.PanelBody,g=wp.components.TextControl,w=wp.components.__experimentalNumberControl,b=wp.components.RangeControl,v=wp.components.ToggleControl,f=wp.components.TextareaControl,y=wp.components.Notice,k=wp.components.SelectControl,C=wp.blockEditor.InspectorControls,_=wp.compose.useDebounce||(e=>e);function x(t){let[e,n]=p.useState("");return h(g,{label:t.label,value:e,onChange(e){n(e),t.onSearch(e)}})}function R(t){var[e,n]=p.useState(""),n=_(n,300),l=String(t.value||0);let s=Number(l)||0,r=e.trim();e=wp.data.useSelect(function(e){var t=e("core"),e=e("core/editor"),e=e&&e.getCurrentPostId?Number(e.getCurrentPostId()):0,n={status:"publish",per_page:20,_fields:"id,title",search:r,search_columns:"post_title"},l=["postType","page",s,{_fields:"id,title,status"}],o=["postType","page",n],i=2<=r.length,n=(0{let t=[],a=[],s=null,r=null,u=!1,p=!0;return d.each(e,function(n,l){"group"===n.type&&(e=n.fields,(n=d.first(d.values(e))).desc="",l=d.first(d.keys(e)));var e=n.page_search?R:((e,t)=>{let n=g;switch(e){case"toggle":n=v;break;case"number":n=t.max&&t.min?b:w;break;case"textarea":n=f;break;case"select":n=k;break;case"note":n=y;break;default:n=g}return n})(n.type,n);d.isObject(n.required)||(n.required={});let o=!0;d.each(n.required,function(e,t){o=i.attributes[t]==e}),o&&a.push(h(e,{key:l,label:n.title,help:n.desc,value:i.attributes[l],checked:i.attributes[l],options:(e=>{let n=[];return d.each(e,function(e,t){n.push({label:e,value:t})}),n})(n.options),placeholder:n.placeholder,min:n.min,max:n.max,onChange(e){var t={};t[l]="number"===n.type?Math.trunc(Number(e)):e,i.setAttributes(t)}})),"header"===n.type&&(a.pop(),(u=null!==s?!0:u)&&(t.push(h(m,{key:r,title:s.title,description:s.desc,initialOpen:p},a)),p=!1),s=n,r=l,a=[])}),t.push(h(m,{key:r,title:s.title,help:s.desc,initialOpen:p},a)),h(C,{key:"wp-ultimo"},t)})(t.fields,e)]},save(){return null}})})})(window.wp.blocks,window.wp.element,window.wp.components,window._); \ No newline at end of file +((e,p,c,d)=>{let h=p.createElement,l=e.registerBlockType,i=wp.serverSideRender,m=wp.components.PanelBody,g=wp.components.TextControl,w=wp.components.__experimentalNumberControl,b=wp.components.RangeControl,v=wp.components.ToggleControl,f=wp.components.TextareaControl,y=wp.components.Notice,k=wp.components.SelectControl,C=wp.blockEditor.InspectorControls,_=wp.compose.useDebounce||(e=>e);function x(t){let[e,n]=p.useState("");return h(g,{label:t.label,value:e,onChange(e){n(e),t.onSearch(e)}})}function R(t){var[e,n]=p.useState(""),n=_(n,300),l=String(t.value||0);let s=Number(l)||0,r=e.trim();e=wp.data.useSelect(function(e){var t=e("core"),e=e("core/editor"),e=e&&e.getCurrentPostId?Number(e.getCurrentPostId()):0,n={status:"publish",per_page:20,_fields:"id,title",search:r,search_columns:"post_title"},l=["postType","page",s,{_fields:"id,title,status"}],i=["postType","page",n],o=2<=r.length,n=(0{let t=[],a=[],s=null,r=null,u=!1,p=!0;return d.each(e,function(l,i){"group"===l.type&&(e=l.fields,(l=d.first(d.values(e))).desc="",i=d.first(d.keys(e)));var e=l.page_search?R:((e,t)=>{let n=g;switch(e){case"toggle":n=v;break;case"number":n=t.max&&t.min?b:w;break;case"textarea":n=f;break;case"select":n=k;break;case"note":n=y;break;default:n=g}return n})(l.type,l);d.isObject(l.required)||(l.required={});let n=!0;d.each(l.required,function(e,t){n=o.attributes[t]==e}),n&&a.push(h(e,{key:i,label:l.title,help:l.desc,value:o.attributes[i],checked:o.attributes[i],options:(e=>{let n=[];return d.each(e,function(e,t){n.push({label:e,value:t})}),n})(l.options),placeholder:l.placeholder,min:l.min,max:l.max,onChange(e){var t={};if("number"===l.type){var n=parseInt(e,10);if(Number.isNaN(n))return;t[i]=n}else t[i]=e;o.setAttributes(t)}})),"header"===l.type&&(a.pop(),(u=null!==s?!0:u)&&(t.push(h(m,{key:r,title:s.title,description:s.desc,initialOpen:p},a)),p=!1),s=l,r=i,a=[])}),t.push(h(m,{key:r,title:s.title,help:s.desc,initialOpen:p},a)),h(C,{key:"wp-ultimo"},t)})(t.fields,e)]},save(){return null}})})})(window.wp.blocks,window.wp.element,window.wp.components,window._); \ No newline at end of file diff --git a/inc/gateways/class-base-stripe-gateway.php b/inc/gateways/class-base-stripe-gateway.php index 42249136c..7bdd7cd90 100644 --- a/inc/gateways/class-base-stripe-gateway.php +++ b/inc/gateways/class-base-stripe-gateway.php @@ -820,16 +820,40 @@ public function get_change_payment_method_url($membership) { return null; } + $current_url = wu_get_current_url(); + return add_query_arg( [ 'wu-stripe-portal' => true, 'membership' => $membership->get_hash(), - 'redirect_url' => wu_request('redirect_url', wu_get_current_url()), + // Encoded: the page has its own query string, which must not leak into this link. + 'redirect_url' => rawurlencode(wp_validate_redirect($this->get_requested_return_url(), $current_url)), ], home_url('/') ); } + /** + * Reads the page to return to after the Billing Portal from the request. + * + * Not wu_request(): it sanitizes with sanitize_text_field(), which strips + * percent-encoded octets such as those in non-ASCII slugs. esc_url_raw() + * keeps them. Callers must still validate the result with wp_validate_redirect(). + * + * @since n.e.x.t + * @return string The requested URL, or an empty string. + */ + private function get_requested_return_url(): string { + + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigation target only; validated by the caller. + if ( ! isset($_REQUEST['redirect_url']) || ! is_string($_REQUEST['redirect_url'])) { + return ''; + } + + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigation target only; validated by the caller. + return esc_url_raw(wp_unslash($_REQUEST['redirect_url'])); + } + /** * Returns payment method display info from the Stripe subscription. * @@ -854,8 +878,12 @@ public function get_payment_method_display($membership) { $pm = $subscription->default_payment_method; - // Portal updates may clear the subscription override to use the customer default. - if ( ! $pm) { + /* + * Portal updates may clear the subscription override to use the customer + * default. A legacy default_source takes precedence over that default + * when Stripe charges, so show no card rather than a different one. + */ + if ( ! $pm && empty($subscription->default_source)) { $pm = $subscription->customer->invoice_settings->default_payment_method ?? null; } @@ -912,7 +940,7 @@ public function maybe_redirect_to_portal(): void { $s_customer_id = $membership->get_gateway_customer_id(); $stored_redirect = get_user_meta(get_current_user_id(), '_wu_change_payment_redirect', true); - $redirect_url = wu_request('redirect_url', $stored_redirect); + $redirect_url = $this->get_requested_return_url() ?: $stored_redirect; $fallback_url = remove_query_arg(['wu-stripe-portal', 'redirect_url'], wu_get_current_url()); if ($redirect_url && is_string($redirect_url)) { diff --git a/inc/gateways/class-manual-gateway.php b/inc/gateways/class-manual-gateway.php index 235fe4e37..ce34cf573 100644 --- a/inc/gateways/class-manual-gateway.php +++ b/inc/gateways/class-manual-gateway.php @@ -160,7 +160,7 @@ public function get_amount_update_message($to_customer = false) { * @param \WP_Ultimo\Models\Membership $membership The membership. * @param \WP_Ultimo\Models\Customer $customer The customer checking out. * @param \WP_Ultimo\Checkout\Cart $cart The cart object. - * @param string $type The checkout type. Can be 'new', 'retry', 'upgrade', 'downgrade', 'addon'. + * @param string $type The checkout type. Can be 'new', 'retry', 'upgrade', 'downgrade', 'addon', 'reactivation'. * * @throws \Exception When saving a membership fails. */ @@ -190,6 +190,10 @@ public function process_checkout($payment, $membership, $customer, $cart, $type) * - downgrade: @see upgrade. * - retry: This cart is created when a customer tries to settle a pending or failed payment. * - addon: Contains only services or packages that should be added to the membership in question. + * - reactivation: A cancelled or expired membership being paid for again. Nothing changes + * here on purpose: on-hold counts as active, so moving the membership there + * would restore access before the payment is confirmed. The administrator's + * confirmation reactivates it (Payment_Edit_Admin_Page::handle_save()). */ $status = true; @@ -232,7 +236,7 @@ public function process_checkout($payment, $membership, $customer, $cart, $type) * Saves the membership with the changes. */ $status = $membership->save(); - } elseif (in_array($type, ['upgrade', 'addon', 'reactivation'], true)) { + } elseif ('upgrade' === $type || 'addon' === $type) { /* * After everything is said and done, * we need to swap the membership to the new products @@ -248,12 +252,18 @@ public function process_checkout($payment, $membership, $customer, $cart, $type) * It doesn't save the membership, though, so * you'll have to do that manually (example below). */ - if ('reactivation' !== $type) { - $membership->swap($cart); - } + $membership->swap($cart); - $membership->set_gateway($this->get_id()); - $membership->set_auto_renew(false); + /* + * A manually paid plan change is invoiced manually from now on, so the + * membership must use this gateway and stop auto-renewing elsewhere. + * Add-ons are extra items on the existing subscription: they keep its + * recurring gateway and renewal setting. + */ + if ('upgrade' === $type) { + $membership->set_gateway($this->get_id()); + $membership->set_auto_renew(false); + } /* * Mark the membership as pending, as we need to diff --git a/tests/WP_Ultimo/Admin_Pages/Payment_Edit_Admin_Page_Test.php b/tests/WP_Ultimo/Admin_Pages/Payment_Edit_Admin_Page_Test.php index 2a8cf5fb2..37b5635a4 100644 --- a/tests/WP_Ultimo/Admin_Pages/Payment_Edit_Admin_Page_Test.php +++ b/tests/WP_Ultimo/Admin_Pages/Payment_Edit_Admin_Page_Test.php @@ -764,7 +764,7 @@ public function test_manual_confirmation_period(string $status, int $times_bille $this->assertNotWPError($product); // Keep the day low so adding one month cannot overflow a short month. $expiration = gmdate('Y-m-09 23:59:59', strtotime('+1 year')); - $membership = wu_create_membership([ + $membership_args = [ 'customer_id' => $customer->get_id(), 'plan_id' => $product->get_id(), 'status' => $status, @@ -774,7 +774,11 @@ public function test_manual_confirmation_period(string $status, int $times_bille 'duration_unit' => 'month', 'times_billed' => $times_billed, 'date_expiration' => $expiration, - ]); + ]; + if ('cancelled' === $status) { + $membership_args['date_cancellation'] = gmdate('Y-m-d H:i:s', strtotime('-1 week')); + } + $membership = wu_create_membership($membership_args); $this->assertNotWPError($membership); $payment = wu_create_payment([ 'customer_id' => $customer->get_id(), @@ -822,9 +826,17 @@ public function test_manual_confirmation_period(string $status, int $times_bille $this->page->object = wu_get_payment($payment->get_id()); } + $reactivated_before = did_action('wu_membership_post_reactivate'); + $this->assertTrue($this->page->handle_save()); $membership = wu_get_membership($membership->get_id()); $this->assertSame('active', $membership->get_status()); + if ('cancelled' === $status) { + // A paid reactivation clears the cancellation, records how it was paid and fires the hooks once. + $this->assertEmpty($membership->get_date_cancellation()); + $this->assertSame('manual', $membership->get_gateway()); + $this->assertSame($reactivated_before + 1, did_action('wu_membership_post_reactivate')); + } $this->assertSame($expected_expiration, $membership->get_date_expiration()); $this->assertSame($times_billed + 1, $membership->get_times_billed()); $this->assertSame(Payment_Status::COMPLETED, wu_get_payment($payment->get_id())->get_status()); @@ -851,6 +863,7 @@ public function manual_confirmation_periods(): array { 'active renewal' => ['active', 1, true], 'pending billed renewal' => ['pending', 1, true], 'expired renewal' => ['expired', 1, true], + 'cancelled reactivation' => ['cancelled', 1, true], 'initial save retry' => ['pending', 0, false, true], 'renewal save retry' => ['active', 1, true, true], ]; diff --git a/tests/WP_Ultimo/Gateways/Manual_Gateway_Checkout_Process_Test.php b/tests/WP_Ultimo/Gateways/Manual_Gateway_Checkout_Process_Test.php index a43402439..da5d7a9e4 100644 --- a/tests/WP_Ultimo/Gateways/Manual_Gateway_Checkout_Process_Test.php +++ b/tests/WP_Ultimo/Gateways/Manual_Gateway_Checkout_Process_Test.php @@ -206,6 +206,135 @@ public function test_process_checkout(string $type, bool $recurring, bool $trial $second_product->delete(); } + /** + * Builds a membership, a pending manual payment and a cart for one scenario. + * + * @param string $slug Unique plan slug. + * @param string $cart_type Cart type to build. + * @param array $membership_args Membership attributes. + * @return array{0: \WP_Ultimo\Models\Membership, 1: \WP_Ultimo\Models\Payment, 2: \WP_Ultimo\Checkout\Cart} + */ + private function build_checkout(string $slug, string $cart_type, array $membership_args): array { + + $customer = self::$customer; + + wp_set_current_user($customer->get_user_id(), $customer->get_username()); + + $product = wu_create_product( + [ + 'name' => $slug, + 'slug' => $slug, + 'amount' => 50.00, + 'recurring' => true, + 'duration' => 1, + 'duration_unit' => 'month', + 'type' => 'plan', + 'pricing_type' => 'paid', + 'active' => true, + ] + ); + + $membership = wu_create_membership( + array_merge( + [ + 'customer_id' => $customer->get_id(), + 'plan_id' => $product->get_id(), + 'recurring' => true, + ], + $membership_args + ) + ); + + $this->assertNotWPError($membership); + + $cart = new \WP_Ultimo\Checkout\Cart( + [ + 'cart_type' => $cart_type, + 'products' => [$product->get_id()], + 'duration' => 1, + 'duration_unit' => 'month', + 'membership_id' => $membership->get_id(), + 'currency' => 'USD', + 'country' => 'US', + ] + ); + + $payment = wu_create_payment( + [ + 'customer_id' => $customer->get_id(), + 'membership_id' => $membership->get_id(), + 'gateway' => 'manual', + 'status' => Payment_Status::PENDING, + 'total' => 50.00, + ] + ); + + return [$membership, $payment, $cart]; + } + + /** + * On-hold counts as active, so a reactivation must not restore access + * before an administrator confirms the payment. + */ + public function test_reactivation_keeps_the_membership_inactive_until_payment_is_confirmed(): void { + + [$membership, $payment, $cart] = $this->build_checkout( + 'manual-reactivation-plan', + 'upgrade', + ['status' => Membership_Status::CANCELLED] + ); + + $this->gateway->process_checkout($payment, $membership, self::$customer, $cart, 'reactivation'); + + $reloaded = wu_get_membership($membership->get_id()); + + $this->assertSame(Membership_Status::CANCELLED, $reloaded->get_status()); + $this->assertFalse($reloaded->is_active(), 'Access must wait for the payment confirmation.'); + $this->assertSame(Payment_Status::PENDING, $payment->get_status()); + } + + /** + * An add-on is an extra item on the existing subscription: paying for it + * manually must not move the membership off its recurring gateway. + */ + public function test_addon_keeps_the_existing_recurring_gateway(): void { + + [$membership, $payment, $cart] = $this->build_checkout( + 'manual-addon-plan', + 'addon', + [ + 'status' => Membership_Status::ACTIVE, + 'gateway' => 'free', + ] + ); + + $this->gateway->process_checkout($payment, $membership, self::$customer, $cart, 'addon'); + + $this->assertSame('free', wu_get_membership($membership->get_id())->get_gateway()); + } + + /** + * A manually paid plan change is invoiced manually from now on. + */ + public function test_upgrade_moves_the_membership_to_the_manual_gateway(): void { + + [$membership, $payment, $cart] = $this->build_checkout( + 'manual-upgrade-plan', + 'upgrade', + [ + 'status' => Membership_Status::ACTIVE, + 'gateway' => 'free', + ] + ); + + $this->gateway->process_checkout($payment, $membership, self::$customer, $cart, 'upgrade'); + + $reloaded = wu_get_membership($membership->get_id()); + + $this->assertSame('manual', $reloaded->get_gateway()); + $this->assertFalse($reloaded->should_auto_renew()); + } + public function tearDown(): void { parent::tearDown(); From 4014c9e7690579fc2ce8929aa0b9a5422bc3d04d Mon Sep 17 00:00:00 2001 From: David Stone Date: Sat, 21 Nov 2026 10:18:15 -0700 Subject: [PATCH 6/8] fix: enforce ownership on account form renders and stop modal crashes Found while re-verifying the account area as a second, unprivileged customer. Both problems exist on main; none of these lines were part of the original account branch. Disclosure - update_billing_address and edit_site render callbacks resolved a record from a request-supplied hash and pre-filled the form without checking the current customer owns it. Any logged-in user could read another customer's billing address (company, street, email, city) or site title and description by reusing their own form nonce, which is per form, not per record. Their save handlers already checked is_customer_allowed(); the render callbacks now apply the same check. Missing and foreign records return the same empty response, so a hash cannot be probed. Crash - render_delete_site, render_cancel_membership and render_resubscribe_membership compared the owner before knowing the record existed, so a stale or mistyped hash called a method on false and returned HTTP 500 "critical error". They now show the existing "not selected" message, as render_change_payment_method already did. Verified on the dev site with real nonces as a free-plan customer: foreign billing/edit-site forms leaked before and are empty after; the nonexistent-record modals returned 500 before and 200 with a message after; owners still get every form. Six foreign-record handler requests (cancel, resubscribe, delete site, change primary site, billing, edit site) were all refused and left the data unchanged. --- inc/ui/class-billing-info-element.php | 7 ++++++- inc/ui/class-current-site-element.php | 7 ++++++- inc/ui/class-site-actions-element.php | 9 ++++++--- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/inc/ui/class-billing-info-element.php b/inc/ui/class-billing-info-element.php index fea1724b4..8f97a166d 100644 --- a/inc/ui/class-billing-info-element.php +++ b/inc/ui/class-billing-info-element.php @@ -323,7 +323,12 @@ public function render_update_billing_address() { $membership = wu_get_membership_by_hash(wu_request('membership')); - if ( ! $membership) { + /* + * The form pre-fills the saved billing address, so it needs the same + * ownership check as the handler. Missing and foreign records get the + * same empty response, which does not reveal whether a hash exists. + */ + if ( ! $membership || ! $membership->is_customer_allowed()) { return; } diff --git a/inc/ui/class-current-site-element.php b/inc/ui/class-current-site-element.php index ca0849a21..eba8d68e8 100644 --- a/inc/ui/class-current-site-element.php +++ b/inc/ui/class-current-site-element.php @@ -401,7 +401,12 @@ public function render_edit_site() { $site = wu_get_site_by_hash(wu_request('site')); - if ( ! $site) { + /* + * The form pre-fills the site title and description, so it needs the + * same ownership check as the handler. Missing and foreign records get + * the same empty response, which does not reveal whether a hash exists. + */ + if ( ! $site || ! $site->is_customer_allowed()) { return; } diff --git a/inc/ui/class-site-actions-element.php b/inc/ui/class-site-actions-element.php index 5921ffbd2..90204ee5f 100644 --- a/inc/ui/class-site-actions-element.php +++ b/inc/ui/class-site-actions-element.php @@ -546,7 +546,8 @@ public function render_delete_site(): void { $customer = wu_get_current_customer(); - if ( ! $customer || $customer->get_id() !== $site->get_customer_id()) { + // A missing site has no owner to compare against. + if ( ! $error && (! $customer || $customer->get_id() !== $site->get_customer_id())) { $error = __('You are not allowed to do this.', 'ultimate-multisite'); } @@ -1156,7 +1157,8 @@ public function render_cancel_membership(): void { $customer = wu_get_current_customer(); - if ( ! is_super_admin() && (! $customer || $customer->get_id() !== $membership->get_customer_id())) { + // A missing membership has no owner to compare against. + if ( ! $error && ! is_super_admin() && (! $customer || $customer->get_id() !== $membership->get_customer_id())) { $error = __('You are not allowed to do this.', 'ultimate-multisite'); } @@ -1397,7 +1399,8 @@ public function render_resubscribe_membership(): void { $customer = wu_get_current_customer(); - if ( ! is_super_admin() && (! $customer || $customer->get_id() !== $membership->get_customer_id())) { + // A missing membership has no owner to compare against. + if ( ! $error && ! is_super_admin() && (! $customer || $customer->get_id() !== $membership->get_customer_id())) { $error = __('You are not allowed to do this.', 'ultimate-multisite'); } From a4ce16e2b520dc81701640ac74bee2dafe9c4468 Mon Sep 17 00:00:00 2001 From: David Stone Date: Sat, 21 Nov 2026 10:38:34 -0700 Subject: [PATCH 7/8] fix: keep the account page's query string in change-payment, cancel and resubscribe links The three actions passed the current page URL to wu_get_form_url() as a form-link argument. That builds the link with add_query_arg(), which does not encode values, so a page with its own query string leaked that string into the form link and the return URL was cut at the first "&" before it reached the Billing Portal fix one hop later. Encode the URL at the call site, the convention already used elsewhere (for example the site list table's redirect_to). A small private helper keeps the three call sites identical. Verified on the dev site against the Stripe sandbox, from /qa-plain-account/?tab=billing&utm=a%26b: the modal's portal link carries the whole URL, Stripe's "Return" link is .../qa-plain-account/?tab=billing&utm=a%26b&updated=payment_method, and following it lands back on the account page. The cancel modal's hidden return field now holds the full URL as well. Pages with no query string are unchanged. --- inc/ui/class-site-actions-element.php | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/inc/ui/class-site-actions-element.php b/inc/ui/class-site-actions-element.php index 90204ee5f..c05ede961 100644 --- a/inc/ui/class-site-actions-element.php +++ b/inc/ui/class-site-actions-element.php @@ -444,7 +444,7 @@ public function get_actions($atts) { 'change_payment_method', [ 'membership' => $this->membership->get_hash(), - 'redirect_url' => wu_get_current_url(), + 'redirect_url' => $this->get_encoded_current_url(), ] ), ]; @@ -454,6 +454,21 @@ public function get_actions($atts) { return apply_filters('wu_element_get_site_actions', $actions, $atts, $this->site, $this->membership); } + /** + * Returns the current page URL, encoded to travel inside a form link. + * + * Form links are built with add_query_arg(), which does not encode values. + * A page with its own query string would otherwise leak that string into + * the form link and lose everything after the first "&" on the way back. + * + * @since n.e.x.t + * @return string + */ + private function get_encoded_current_url(): string { + + return rawurlencode(wu_get_current_url()); + } + /** * Returns the danger actions actions for the element. These can be filtered. * @@ -496,7 +511,7 @@ public function get_danger_zone_actions($atts) { 'cancel_membership', [ 'membership' => $this->membership->get_hash(), - 'redirect_url' => wu_get_current_url(), + 'redirect_url' => $this->get_encoded_current_url(), ] ), ], @@ -516,7 +531,7 @@ public function get_danger_zone_actions($atts) { 'resubscribe_membership', [ 'membership' => $this->membership->get_hash(), - 'redirect_url' => wu_get_current_url(), + 'redirect_url' => $this->get_encoded_current_url(), ] ), ], From ce52d96504eeac42e34bbd89b49edeb391664553 Mon Sep 17 00:00:00 2001 From: David Stone Date: Sat, 21 Nov 2026 11:19:39 -0700 Subject: [PATCH 8/8] fix: keep the portal return default and stop add-on payments extending the plan Two findings from the review of the re-land, both valid and both in code this branch added or changed. Stripe Billing Portal link - My earlier encoding fix read the requested return URL on its own, but wp_validate_redirect() returns an empty string for an empty value, not its fallback. A link built on an ordinary page request with no redirect_url parameter, which is how the Payment Methods widget builds its Change link, carried an empty return URL instead of the current page. Default to the current page when the request names none, then validate. - Test: the link returns to the current page without a requested URL, and keeps a requested URL's own query string whole. Fails against the previous code. Payment editor - The "Activate Membership?" toggle is offered for on-hold memberships, which is how an add-on bought through the Manual gateway waits for payment. Confirming it ran the ordinary renewal: the plan's period was extended by a cycle and its bill count raised, although an add-on is not a billing cycle of the plan. An add-on payment, recognised by the cart type stored with it, now lifts the hold and nothing else. - Test: an on-hold plan payment still renews, and an on-hold add-on payment activates without moving the expiration or the bill count. The add-on row fails when the detection is disabled. --- .../class-payment-edit-admin-page.php | 32 ++++++++++++- inc/gateways/class-base-stripe-gateway.php | 5 ++- .../Payment_Edit_Admin_Page_Test.php | 43 ++++++++++++++++-- .../Gateways/Base_Stripe_Gateway_Test.php | 45 +++++++++++++++++++ 4 files changed, 118 insertions(+), 7 deletions(-) diff --git a/inc/admin-pages/class-payment-edit-admin-page.php b/inc/admin-pages/class-payment-edit-admin-page.php index 47ff1cbec..eb6e542e4 100644 --- a/inc/admin-pages/class-payment-edit-admin-page.php +++ b/inc/admin-pages/class-payment-edit-admin-page.php @@ -1481,13 +1481,23 @@ public function handle_save(): bool { if ($should_confirm_membership && $membership) { $is_initial_payment = Membership_Status::PENDING === $membership->get_status() && 0 === $membership->get_times_billed(); + $is_addon_payment = $this->is_addon_payment($payment); - // The initial payment counts as a bill, but checkout already set its period. - $membership->add_to_times_billed(1); + if ( ! $is_addon_payment) { + // The initial payment counts as a bill, but checkout already set its period. + $membership->add_to_times_billed(1); + } if ($is_initial_payment) { $membership->set_status(Membership_Status::ACTIVE); $membership_saved = $membership->save(); + } elseif ($is_addon_payment) { + /* + * Add-ons are extras on the plan, not one of its billing cycles: lift + * the hold without moving the plan's period or its bill count. + */ + $membership->set_status(Membership_Status::ACTIVE); + $membership_saved = $membership->save(); } elseif (in_array($membership->get_status(), [Membership_Status::CANCELLED, Membership_Status::EXPIRED], true)) { /* * A paid reactivation. Like the Stripe and PayPal gateways, use @@ -1542,4 +1552,22 @@ public function handle_save(): bool { return $saved; } + + /** + * Checks whether a payment came from an add-on checkout. + * + * An add-on cart holds only the extras to add to a membership. Paying for it + * is not a billing cycle of the membership's plan. + * + * @since n.e.x.t + * + * @param \WP_Ultimo\Models\Payment $payment The payment. + * @return bool + */ + private function is_addon_payment($payment): bool { + + $cart = $payment->get_meta(Payment::META_ORIGINAL_CART); + + return $cart instanceof \WP_Ultimo\Checkout\Cart && 'addon' === $cart->get_cart_type(); + } } diff --git a/inc/gateways/class-base-stripe-gateway.php b/inc/gateways/class-base-stripe-gateway.php index 7bdd7cd90..3161b8bca 100644 --- a/inc/gateways/class-base-stripe-gateway.php +++ b/inc/gateways/class-base-stripe-gateway.php @@ -822,12 +822,15 @@ public function get_change_payment_method_url($membership) { $current_url = wu_get_current_url(); + // Return to the page that asked for it, or to this one when the request names none. + $return_url = $this->get_requested_return_url() ?: $current_url; + return add_query_arg( [ 'wu-stripe-portal' => true, 'membership' => $membership->get_hash(), // Encoded: the page has its own query string, which must not leak into this link. - 'redirect_url' => rawurlencode(wp_validate_redirect($this->get_requested_return_url(), $current_url)), + 'redirect_url' => rawurlencode(wp_validate_redirect($return_url, $current_url)), ], home_url('/') ); diff --git a/tests/WP_Ultimo/Admin_Pages/Payment_Edit_Admin_Page_Test.php b/tests/WP_Ultimo/Admin_Pages/Payment_Edit_Admin_Page_Test.php index 37b5635a4..d296a2524 100644 --- a/tests/WP_Ultimo/Admin_Pages/Payment_Edit_Admin_Page_Test.php +++ b/tests/WP_Ultimo/Admin_Pages/Payment_Edit_Admin_Page_Test.php @@ -745,7 +745,7 @@ public function test_handle_save_no_membership_renewal_when_absent(): void { * * @dataProvider manual_confirmation_periods */ - public function test_manual_confirmation_period(string $status, int $times_billed, bool $renews, bool $fail_first = false): void { + public function test_manual_confirmation_period(string $status, int $times_billed, bool $renews, bool $fail_first = false, bool $addon = false): void { $customer = wu_create_customer([ 'user_id' => self::factory()->user->create(), 'email_verification' => 'none', @@ -767,7 +767,8 @@ public function test_manual_confirmation_period(string $status, int $times_bille $membership_args = [ 'customer_id' => $customer->get_id(), 'plan_id' => $product->get_id(), - 'status' => $status, + // An add-on is bought while the membership runs; the Manual gateway then puts it on hold. + 'status' => $addon ? 'active' : $status, 'amount' => 29.99, 'recurring' => true, 'duration' => 1, @@ -789,6 +790,36 @@ public function test_manual_confirmation_period(string $status, int $times_bille ]); $this->assertNotWPError($payment); + if ($addon) { + $extra = wu_create_product([ + 'name' => 'Manual Confirmation Add-on', + 'slug' => 'manual-confirmation-addon-' . wp_generate_password(8, false), + 'type' => 'service', + 'pricing_type' => 'paid', + 'amount' => 5.00, + 'recurring' => true, + 'duration' => 1, + 'duration_unit' => 'month', + 'active' => true, + ]); + $this->assertNotWPError($extra); + + // A cart only builds for the membership's own customer. One with only extras keeps that membership's plan, which makes it an add-on cart. + wp_set_current_user($customer->get_user_id()); + $cart = new \WP_Ultimo\Checkout\Cart([ + 'products' => [$extra->get_id()], + 'membership_id' => $membership->get_id(), + 'currency' => 'USD', + 'country' => 'US', + ]); + wp_set_current_user(0); + $this->assertSame('addon', $cart->get_cart_type()); + $payment->update_meta(Payment::META_ORIGINAL_CART, $cart); + + $membership->set_status($status); + $this->assertNotWPError($membership->save()); + } + $membership->create_pending_site([ 'title' => 'Manual Confirmation Site', 'path' => '/manual-confirmation-' . strtolower(wp_generate_password(8, false)) . '/', @@ -805,6 +836,8 @@ public function test_manual_confirmation_period(string $status, int $times_bille $_POST['status'] = Payment_Status::COMPLETED; $_REQUEST['status'] = Payment_Status::COMPLETED; $expected_expiration = $renews ? gmdate('Y-m-d H:i:s', strtotime('+1 month', strtotime($expiration))) : $expiration; + // An add-on payment is not a billing cycle of the plan. + $expected_billed = $addon ? $times_billed : $times_billed + 1; try { if ($fail_first) { @@ -838,7 +871,7 @@ public function test_manual_confirmation_period(string $status, int $times_bille $this->assertSame($reactivated_before + 1, did_action('wu_membership_post_reactivate')); } $this->assertSame($expected_expiration, $membership->get_date_expiration()); - $this->assertSame($times_billed + 1, $membership->get_times_billed()); + $this->assertSame($expected_billed, $membership->get_times_billed()); $this->assertSame(Payment_Status::COMPLETED, wu_get_payment($payment->get_id())->get_status()); if ('pending' === $status) { $this->assertEmpty($membership->get_pending_site()); @@ -850,7 +883,7 @@ public function test_manual_confirmation_period(string $status, int $times_bille $this->assertTrue($this->page->handle_save()); $membership = wu_get_membership($membership->get_id()); $this->assertSame($expected_expiration, $membership->get_date_expiration()); - $this->assertSame($times_billed + 1, $membership->get_times_billed()); + $this->assertSame($expected_billed, $membership->get_times_billed()); } finally { remove_filter('wp_redirect', '__return_false'); wu_save_setting('force_publish_sites_sync', $force_sync); @@ -864,6 +897,8 @@ public function manual_confirmation_periods(): array { 'pending billed renewal' => ['pending', 1, true], 'expired renewal' => ['expired', 1, true], 'cancelled reactivation' => ['cancelled', 1, true], + 'on-hold renewal' => ['on-hold', 1, true], + 'on-hold add-on' => ['on-hold', 1, false, false, true], 'initial save retry' => ['pending', 0, false, true], 'renewal save retry' => ['active', 1, true, true], ]; diff --git a/tests/WP_Ultimo/Gateways/Base_Stripe_Gateway_Test.php b/tests/WP_Ultimo/Gateways/Base_Stripe_Gateway_Test.php index eea6912fd..37651c7ab 100644 --- a/tests/WP_Ultimo/Gateways/Base_Stripe_Gateway_Test.php +++ b/tests/WP_Ultimo/Gateways/Base_Stripe_Gateway_Test.php @@ -633,6 +633,51 @@ public function test_get_change_payment_method_url_returns_url(): void { $this->assertStringContainsString('abc123hash', $result); } + /** + * The portal link returns to the page that built it, whole. + * + * Without a requested return URL it falls back to the current page. With one, + * the URL's own query string must survive: add_query_arg() does not encode + * values, so the URL has to be encoded before it is nested in the link. + */ + public function test_get_change_payment_method_url_keeps_the_return_url(): void { + wu_save_setting('stripe_enable_portal', 1); + + $membership_mock = $this->getMockBuilder(\WP_Ultimo\Models\Membership::class) + ->disableOriginalConstructor() + ->onlyMethods(['get_gateway_subscription_id', 'get_hash']) + ->getMock(); + + $membership_mock->method('get_gateway_subscription_id')->willReturn('sub_test123'); + $membership_mock->method('get_hash')->willReturn('abc123hash'); + + $server = $_SERVER; + // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Fixture: saves the incoming request to restore it. + $request = $_REQUEST; + + try { + $_SERVER['HTTP_HOST'] = 'example.org'; + $_SERVER['REQUEST_URI'] = '/account/?tab=billing'; + + unset($_REQUEST['redirect_url']); + + parse_str((string) wp_parse_url($this->gateway->get_change_payment_method_url($membership_mock), PHP_URL_QUERY), $query); + + $this->assertSame('http://example.org/account/?tab=billing', $query['redirect_url'], 'Without a requested return URL the link returns to the current page.'); + + $_REQUEST['redirect_url'] = 'http://example.org/account/?tab=billing&utm=a%26b'; + + parse_str((string) wp_parse_url($this->gateway->get_change_payment_method_url($membership_mock), PHP_URL_QUERY), $query); + + $this->assertSame('http://example.org/account/?tab=billing&utm=a%26b', $query['redirect_url']); + $this->assertSame('abc123hash', $query['membership']); + $this->assertArrayNotHasKey('utm', $query, 'The return URL\'s own query string must not leak into the link.'); + } finally { + $_SERVER = $server; + $_REQUEST = $request; + } + } + // ========================================================================= // get_payment_method_display // =========================================================================