Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
53.42% covered (warning)
53.42%
258 / 483
22.50% covered (danger)
22.50%
9 / 40
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Memberships
53.86% covered (warning)
53.86%
258 / 479
22.50% covered (danger)
22.50%
9 / 40
2359.80
0.00% covered (danger)
0.00%
0 / 1
 clear_post_access_level_cache
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_instance
33.33% covered (danger)
33.33%
2 / 6
0.00% covered (danger)
0.00%
0 / 1
8.74
 get_plan_property_mapping
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
2
 register_init_hook
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 init_hook_action
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
3.04
 subscriber_logout
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 map_plan_meta_cap
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
9.02
 setup_cpts
100.00% covered (success)
100.00%
47 / 47
100.00% covered (success)
100.00%
1 / 1
1
 allow_rest_api_types
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 allow_sync_post_meta
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
2
 return_meta
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 render_button_error
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 render_button_preview
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 should_render_button_preview
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
42
 render_button
0.00% covered (danger)
0.00%
0 / 36
0.00% covered (danger)
0.00%
0 / 1
210
 render_button_email
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
9.08
 get_subscription_url
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 deprecated_render_button_v1
0.00% covered (danger)
0.00%
0 / 33
0.00% covered (danger)
0.00%
0 / 1
20
 get_blog_id
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 has_connected_account
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 get_post_access_level
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
8.02
 get_post_tier
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 user_can_edit
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 clear_cache
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
6
 user_is_paid_subscriber
78.57% covered (warning)
78.57%
11 / 14
0.00% covered (danger)
0.00%
0 / 1
5.25
 user_is_pending_subscriber
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 user_can_view_post
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 user_has_subscription_access
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 check_post_access
90.00% covered (success)
90.00%
27 / 30
0.00% covered (danger)
0.00%
0 / 1
15.22
 is_enabled_jetpack_recurring_payments
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 should_enable_monetize_blocks_in_editor
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
4.94
 has_configured_plans_jetpack_recurring_payments
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
4
 get_all_plans
75.00% covered (warning)
75.00%
9 / 12
0.00% covered (danger)
0.00%
0 / 1
4.25
 get_all_newsletter_plan_ids
69.70% covered (warning)
69.70%
23 / 33
0.00% covered (danger)
0.00%
0 / 1
7.00
 register_gutenberg_block
65.22% covered (warning)
65.22%
15 / 23
0.00% covered (danger)
0.00%
0 / 1
3.38
 get_join_others_text
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
9
 get_current_user_email
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 is_current_user_subscribed
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 render_tier_description_html
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
4.00
1<?php
2/**
3 * Jetpack_Memberships: wrapper for memberships functions.
4 *
5 * @package    Jetpack
6 * @since      7.3.0
7 */
8
9use Automattic\Jetpack\Blocks;
10use Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service\Abstract_Token_Subscription_Service;
11use Automattic\Jetpack\Status;
12use Automattic\Jetpack\Status\Host;
13use Automattic\Jetpack\Status\Request;
14use const Automattic\Jetpack\Extensions\Subscriptions\META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS;
15use const Automattic\Jetpack\Extensions\Subscriptions\META_NAME_FOR_POST_TIER_ID_SETTINGS;
16
17if ( ! defined( 'ABSPATH' ) ) {
18    exit( 0 );
19}
20
21require_once __DIR__ . '/../../extensions/blocks/subscriptions/constants.php';
22
23/**
24 * Class Jetpack_Memberships
25 * This class represents the Memberships functionality.
26 */
27class Jetpack_Memberships {
28    /**
29     * CSS class prefix to use in the styling.
30     *
31     * @var string
32     */
33    public static $css_classname_prefix = 'jetpack-memberships';
34    /**
35     * Our CPT type for the product (plan).
36     *
37     * @var string
38     */
39    public static $post_type_plan = 'jp_mem_plan';
40
41    /**
42     * Our CPT type for the product (plan).
43     *
44     * @var string
45     */
46    public static $post_type_coupon = 'memberships_coupon';
47
48    /**
49     * Tier type for plans
50     *
51     * @var string
52     */
53    public static $type_tier = 'tier';
54
55    /**
56     * Option stores status for memberships (Stripe, etc.).
57     *
58     * @var string
59     */
60    public static $has_connected_account_option_name = 'jetpack-memberships-has-connected-account';
61
62    /**
63     * Post meta that will store the level of access for newsletters
64     *
65     * @var string
66     */
67    public static $post_access_level_meta_name = META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS;
68
69    /**
70     * Post meta that will store the tier ID of access for newsletters
71     *
72     * @var string
73     */
74    public static $post_access_tier_meta_name = META_NAME_FOR_POST_TIER_ID_SETTINGS;
75
76    /**
77     * Button block type to use.
78     *
79     * @var string
80     */
81    private static $button_block_name = 'recurring-payments';
82
83    /**
84     * These are defaults for wp_kses ran on the membership button.
85     *
86     * @var array
87     */
88    private static $tags_allowed_in_the_button = array( 'br' => array() );
89
90    /**
91     * Allowed HTML tags for a rendered tier description. Mirrors the wp.com
92     * subscribe modal's allowlist so the rendered markdown stays consistent
93     * across surfaces.
94     *
95     * @var array
96     */
97    const TIER_DESCRIPTION_ALLOWED_HTML = array(
98        'p'          => array(),
99        'br'         => array(),
100        'ul'         => array(),
101        'ol'         => array(),
102        'li'         => array(),
103        'strong'     => array(),
104        'em'         => array(),
105        'del'        => array(),
106        'code'       => array(),
107        'blockquote' => array(),
108        'a'          => array(
109            'href'   => true,
110            'rel'    => true,
111            'target' => true,
112        ),
113    );
114
115    /**
116     * The minimum required plan for this Gutenberg block.
117     *
118     * @var string Plan slug
119     */
120    private static $required_plan;
121
122    /**
123     * Track recurring payments block registration.
124     *
125     * @var boolean True if block registration has been executed.
126     */
127    private static $has_registered_block = false;
128
129    /**
130     * Classic singleton pattern
131     *
132     * @var Jetpack_Memberships
133     */
134    private static $instance;
135
136    /**
137     * Cached results of user_can_view_post() method.
138     *
139     * @var array
140     */
141    private static $user_can_view_post_cache = array();
142
143    /**
144     * Cached results of user_is_paid_subscriber() method.
145     *
146     * @var array
147     */
148    private static $user_is_paid_subscriber_cache = array();
149
150    /**
151     * Cached results of get_post_access_level method.
152     *
153     * @var array
154     */
155    private static $post_access_level_cache = array();
156
157    /**
158     * Clear cached results of get_post_access_level method.
159     */
160    public static function clear_post_access_level_cache() {
161        self::$post_access_level_cache = array();
162    }
163
164    /**
165     * Currencies we support and Stripe's minimum amount for a transaction in that currency.
166     *
167     * @link https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts
168     *
169     * List has to be in with `SUPPORTED_CURRENCIES` in extensions/shared/currencies.js.
170     */
171    const SUPPORTED_CURRENCIES = array(
172        'USD' => 0.5,
173        'AUD' => 0.5,
174        'BRL' => 0.5,
175        'CAD' => 0.5,
176        'CHF' => 0.5,
177        'DKK' => 2.5,
178        'EUR' => 0.5,
179        'GBP' => 0.3,
180        'HKD' => 4.0,
181        'INR' => 0.5,
182        'JPY' => 50,
183        'MXN' => 10,
184        'NOK' => 3.0,
185        'NZD' => 0.5,
186        'PLN' => 2.0,
187        'SEK' => 3.0,
188        'SGD' => 0.5,
189        'CZK' => 15.0,
190        'HUF' => 175.0,
191        'TWD' => 10.0,
192        'IDR' => 0,
193        'ILS' => 0,
194        'PHP' => 0,
195        'RUB' => 0,
196        'TRY' => 0,
197        'MYR' => 2.00,
198    );
199
200    /**
201     * Jetpack_Memberships constructor.
202     */
203    private function __construct() {}
204
205    /**
206     * The actual constructor initializing the object.
207     *
208     * @return Jetpack_Memberships
209     */
210    public static function get_instance() {
211        if ( ! self::$instance ) {
212            self::$instance = new self();
213            self::$instance->register_init_hook();
214            // Yes, `pro-plan` with a dash, `jetpack_personal` with an underscore. Check the v1.5 endpoint to verify.
215            $wpcom_plan_slug     = defined( 'ENABLE_PRO_PLAN' ) ? 'pro-plan' : 'personal-bundle';
216            self::$required_plan = ( new Host() )->is_wpcom_simple() ? $wpcom_plan_slug : 'jetpack_personal';
217        }
218
219        return self::$instance;
220    }
221    /**
222     * Get the map that defines the shape of CPT post. keys are names of fields and
223     * 'meta' is the name of actual WP post meta field that corresponds.
224     *
225     * @return array
226     */
227    private static function get_plan_property_mapping() {
228        $meta_prefix = 'jetpack_memberships_';
229        $properties  = array(
230            'price'           => array(
231                'meta' => $meta_prefix . 'price',
232            ),
233            'currency'        => array(
234                'meta' => $meta_prefix . 'currency',
235            ),
236            'site_subscriber' => array(
237                'meta' => $meta_prefix . 'site_subscriber',
238            ),
239            'product_id'      => array(
240                'meta' => $meta_prefix . 'product_id',
241            ),
242            'tier'            => array(
243                'meta' => $meta_prefix . 'tier',
244            ),
245            'is_deleted'      => array(
246                'meta' => $meta_prefix . 'is_deleted',
247            ),
248            'is_sandboxed'    => array(
249                'meta' => $meta_prefix . 'is_sandboxed',
250            ),
251        );
252        return $properties;
253    }
254
255    /**
256     * Inits further hooks on init hook.
257     */
258    private function register_init_hook() {
259        add_action( 'init', array( $this, 'init_hook_action' ) );
260        add_action( 'jetpack_register_gutenberg_extensions', array( $this, 'register_gutenberg_block' ) );
261        // phpcs:ignore WPCUT.SwitchBlog.SwitchBlog -- wpcom flags **every** use of switch_blog, apparently expecting valid instances to ignore or suppress the sniff.
262        add_action( 'switch_blog', array( $this, 'clear_post_access_level_cache' ) );
263    }
264
265    /**
266     * Actual hooks initializing on init.
267     */
268    public function init_hook_action() {
269        add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_rest_api_types' ) );
270        add_filter( 'jetpack_sync_post_meta_whitelist', array( $this, 'allow_sync_post_meta' ) );
271        add_filter( 'map_meta_cap', array( $this, 'map_plan_meta_cap' ), 10, 4 );
272        $this->setup_cpts();
273
274        if ( Jetpack::is_module_active( 'subscriptions' ) && Request::is_frontend() ) {
275            add_action( 'wp_logout', array( $this, 'subscriber_logout' ) );
276        }
277    }
278
279    /**
280     * Logs the subscriber out by clearing out the premium content cookie.
281     */
282    public function subscriber_logout() {
283        if ( ! class_exists( 'Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service\Abstract_Token_Subscription_Service' ) ) {
284            return;
285        }
286
287        Abstract_Token_Subscription_Service::clear_token_cookie();
288    }
289
290    /**
291     * Require ownership before editing or deleting a plan or coupon.
292     *
293     * These post types register with `map_meta_cap => false`, so core maps `edit_post`/`delete_post`
294     * to the flat `edit_posts`/`delete_posts` primitives with no author comparison, letting any
295     * `edit_posts` role edit another author's plan (e.g. reprice an admin-owned tier). We can't flip
296     * to `map_meta_cap => true` because code checks these types' meta caps without a post ID, which
297     * trips core's 6.1 meta-cap `_doing_it_wrong` notice. Core rewrites the meta cap to its primitive
298     * before this filter runs, so match the primitive and add the `_others_posts` cap for non-owners.
299     *
300     * @param string[] $caps    Primitive capabilities required of the user.
301     * @param string   $cap     Capability being checked, already mapped to the post type's primitive.
302     * @param int      $user_id User ID.
303     * @param array    $args    Arguments; $args[0] is the post ID when checking a post capability.
304     * @return string[]
305     */
306    public function map_plan_meta_cap( $caps, $cap, $user_id, $args ) {
307        if ( empty( $args[0] ) ) {
308            return $caps;
309        }
310
311        // Bail before get_post(): for other caps $args[0] may be a comment, user or term ID, and missing posts are not cached.
312        if ( 'edit_posts' !== $cap && 'delete_posts' !== $cap ) {
313            return $caps;
314        }
315
316        $post = get_post( $args[0] );
317        if ( ! $post instanceof WP_Post || ! in_array( $post->post_type, array( self::$post_type_plan, self::$post_type_coupon ), true ) ) {
318            return $caps;
319        }
320
321        if ( (int) $post->post_author === (int) $user_id ) {
322            return $caps;
323        }
324
325        $post_type = get_post_type_object( $post->post_type );
326        if ( $cap === $post_type->cap->edit_post ) {
327            $caps[] = 'edit_others_posts';
328        } elseif ( $cap === $post_type->cap->delete_post ) {
329            $caps[] = 'delete_others_posts';
330        }
331
332        return $caps;
333    }
334
335    /**
336     * Sets up the custom post types for the module.
337     */
338    private function setup_cpts() {
339        /*
340         * PLAN data structure.
341         */
342        $capabilities = array(
343            'edit_post'          => 'edit_posts',
344            'read_post'          => 'read_private_posts',
345            'delete_post'        => 'delete_posts',
346            'edit_posts'         => 'edit_posts',
347            'edit_others_posts'  => 'edit_others_posts',
348            'publish_posts'      => 'publish_posts',
349            'read_private_posts' => 'read_private_posts',
350        );
351        $order_args   = array(
352            'label'               => esc_html__( 'Plan', 'jetpack' ),
353            'description'         => esc_html__( 'Recurring Payments plans', 'jetpack' ),
354            'supports'            => array( 'title', 'custom-fields', 'content' ),
355            'hierarchical'        => false,
356            'public'              => false,
357            'show_ui'             => false,
358            'show_in_menu'        => false,
359            'show_in_admin_bar'   => false,
360            'show_in_nav_menus'   => false,
361            'can_export'          => true,
362            'has_archive'         => false,
363            'exclude_from_search' => true,
364            'publicly_queryable'  => false,
365            'rewrite'             => false,
366            'capabilities'        => $capabilities,
367            'show_in_rest'        => false,
368        );
369        register_post_type( self::$post_type_plan, $order_args );
370        $coupon_args = array(
371            'label'               => esc_html__( 'Coupon', 'jetpack' ),
372            'description'         => esc_html__( 'Memberships coupons', 'jetpack' ),
373            'supports'            => array( 'title', 'custom-fields', 'content' ),
374            'hierarchical'        => false,
375            'public'              => false,
376            'show_ui'             => false,
377            'show_in_menu'        => false,
378            'show_in_admin_bar'   => false,
379            'show_in_nav_menus'   => false,
380            'can_export'          => true,
381            'has_archive'         => false,
382            'exclude_from_search' => true,
383            'publicly_queryable'  => false,
384            'rewrite'             => false,
385            'capabilities'        => $capabilities,
386            'show_in_rest'        => false,
387        );
388        register_post_type( self::$post_type_coupon, $coupon_args );
389    }
390
391    /**
392     * Allows custom post types to be used by REST API.
393     *
394     * @param array $post_types - other post types.
395     *
396     * @see hook 'rest_api_allowed_post_types'
397     * @return array
398     */
399    public function allow_rest_api_types( $post_types ) {
400        $post_types[] = self::$post_type_plan;
401        $post_types[] = self::$post_type_coupon;
402
403        return $post_types;
404    }
405
406    /**
407     * Allows custom meta fields to sync.
408     *
409     * @param array $post_meta - previously changet post meta.
410     *
411     * @return array
412     */
413    public function allow_sync_post_meta( $post_meta ) {
414        $meta_keys_plans = array_map(
415            array( $this, 'return_meta' ),
416            self::get_plan_property_mapping()
417        );
418
419        $meta_coupons_prefix = self::$post_type_coupon . '_';
420        $meta_keys_coupons   = array(
421            $meta_coupons_prefix . 'coupon_code',
422            $meta_coupons_prefix . 'can_be_combined',
423            $meta_coupons_prefix . 'first_time_purchase_only',
424            $meta_coupons_prefix . 'limit_per_user',
425            $meta_coupons_prefix . 'discount_type',
426            $meta_coupons_prefix . 'discount_value',
427            $meta_coupons_prefix . 'discount_percentage',
428            $meta_coupons_prefix . 'discount_currency',
429            $meta_coupons_prefix . 'start_date',
430            $meta_coupons_prefix . 'end_date',
431            $meta_coupons_prefix . 'plan_ids_allow_list',
432            $meta_coupons_prefix . 'duration',
433            $meta_coupons_prefix . 'email_allow_list',
434            $meta_coupons_prefix . 'is_deleted',
435            $meta_coupons_prefix . 'is_sandboxed',
436        );
437
438        return array_merge(
439            $post_meta,
440            array_values( $meta_keys_plans ),
441            $meta_keys_coupons
442        );
443    }
444
445    /**
446     * This returns meta attribute of passet array.
447     * Used for array functions.
448     *
449     * @param array $map - stuff.
450     *
451     * @return mixed
452     */
453    public function return_meta( $map ) {
454        return $map['meta'];
455    }
456
457    /**
458     * Show an error to the user (or embed a clue in the HTML) when the button does not get rendered properly.
459     *
460     * @param WP_Error $error The error message with error code.
461     * @return string The error message rendered as HTML.
462     */
463    public function render_button_error( $error ) {
464        if ( static::user_can_edit() ) {
465            return '<div><strong>Jetpack Memberships Error: ' . $error->get_error_code() . '</strong><br />' . $error->get_error_message() . '</div>';
466        }
467        return '<div>Sorry! This product is not available for purchase at this time.</div><!-- Jetpack Memberships Error: ' . $error->get_error_code() . ' -->';
468    }
469
470    /**
471     * Renders a preview of the Recurring Payment button, which is not hooked
472     * up to the subscription url. Used to preview the block on the frontend
473     * for site editors when Stripe has not been connected.
474     *
475     * @param array  $attrs - attributes in the shortcode.
476     * @param string $content - Recurring Payment block content.
477     *
478     * @return string|void
479     */
480    public function render_button_preview( $attrs, $content = null ) {
481        if ( ! empty( $content ) ) {
482            $block_id = esc_attr( wp_unique_id( 'recurring-payments-block-' ) );
483            $content  = str_replace( 'recurring-payments-id', $block_id, $content );
484            $content  = str_replace( 'wp-block-jetpack-recurring-payments', 'wp-block-jetpack-recurring-payments wp-block-button', $content );
485            return $content;
486        }
487        return $this->deprecated_render_button_v1( $attrs, null );
488    }
489
490    /**
491     * Determines whether the button preview should be rendered. Returns true
492     * if the user has editing permissions, the button is not configured correctly
493     * (because it requires a plan upgrade or Stripe connection), and the
494     * button is a child of a Premium Content block.
495     *
496     * @param WP_Block $block Recurring Payments block instance.
497     *
498     * @return boolean
499     */
500    public function should_render_button_preview( $block ) {
501        $user_can_edit              = static::user_can_edit();
502        $requires_stripe_connection = ! static::has_connected_account();
503
504        $jetpack_ready = ! self::is_enabled_jetpack_recurring_payments();
505
506        $is_premium_content_child = false;
507        if ( isset( $block ) && isset( $block->context['isPremiumContentChild'] ) ) {
508            $is_premium_content_child = (int) $block->context['isPremiumContentChild'];
509        }
510
511        return $is_premium_content_child &&
512            $user_can_edit &&
513            $requires_stripe_connection &&
514            $jetpack_ready;
515    }
516
517    /**
518     * Callback that parses the membership purchase shortcode.
519     *
520     * @param array    $attributes - attributes in the shortcode. `id` here is the CPT id of the plan.
521     * @param string   $content - Recurring Payment block content.
522     * @param WP_Block $block - Recurring Payment block instance.
523     *
524     * @return string|void - HTML for the button, void removes the button.
525     */
526    public function render_button( $attributes, $content = null, $block = null ) {
527        Jetpack_Gutenberg::load_assets_as_required( self::$button_block_name );
528
529        if ( $this->should_render_button_preview( $block ) ) {
530            return $this->render_button_preview( $attributes, $content );
531        }
532
533        if ( empty( $attributes['planId'] ) && empty( $attributes['planIds'] ) ) {
534            return $this->render_button_error( new WP_Error( 'jetpack-memberships-rb-npi', __( 'No plan was configured for this button.', 'jetpack' ) . ' ' . __( 'Edit this post and confirm that an existing payment plan is selected for this block.', 'jetpack' ) ) );
535        }
536
537        // This is string of '+` separated plan ids. Loop through them and
538        // filter out the ones that are not valid.
539        $plan_ids = array();
540        if ( ! empty( $attributes['planIds'] ) ) {
541            $plan_ids = $attributes['planIds'];
542        } elseif ( ! empty( $attributes['planId'] ) ) {
543            $plan_ids = explode( '+', $attributes['planId'] );
544        }
545        $valid_plans = array();
546        foreach ( $plan_ids as $plan_id ) {
547            if ( ! is_numeric( $plan_id ) ) {
548                continue;
549            }
550            $product = get_post( $plan_id );
551            if ( ! $product ) {
552                return $this->render_button_error( new WP_Error( 'jetpack-memberships-rb-npf', __( 'Could not find a plan for this button.', 'jetpack' ) . ' ' . __( 'Edit this post and confirm that the selected payment plan still exists and is available for purchase.', 'jetpack' ) ) );
553            }
554            if ( is_wp_error( $product ) ) {
555                '@phan-var WP_Error $product'; // `get_post` isn't supposed to return a WP_Error, so Phan is confused here. See also https://github.com/phan/phan/issues/3127
556                return $this->render_button_error( new WP_Error( 'jetpack-memberships-rb-npf-we', __( 'Encountered an error when getting the plan associated with this button:', 'jetpack' ) . ' ' . $product->get_error_message() . '. ' . __( ' Edit this post and confirm that the selected payment plan still exists and is available for purchase.', 'jetpack' ) ) );
557            }
558            if ( $product->post_type !== self::$post_type_plan ) {
559                return $this->render_button_error( new WP_Error( 'jetpack-memberships-rb-pnplan', __( 'The payment plan selected is not actually a payment plan.', 'jetpack' ) . ' ' . __( 'Edit this post and confirm that the selected payment plan still exists and is available for purchase.', 'jetpack' ) ) );
560            }
561            if ( 'publish' !== $product->post_status ) {
562                return $this->render_button_error( new WP_Error( 'jetpack-memberships-rb-psnpub', __( 'The selected payment plan is not active.', 'jetpack' ) . ' ' . __( 'Edit this post and confirm that the selected payment plan still exists and is available for purchase.', 'jetpack' ) ) );
563            }
564            $valid_plans[] = $plan_id;
565        }
566
567        // If none are valid, return.
568        // (Returning like this makes the button disappear.)
569        if ( empty( $valid_plans ) ) {
570            return;
571        }
572        $plan_id = implode( '+', $valid_plans );
573
574        if ( ! empty( $content ) ) {
575            $block_id      = esc_attr( wp_unique_id( 'recurring-payments-block-' ) );
576            $content       = str_replace( 'recurring-payments-id', $block_id, $content );
577            $content       = str_replace( 'wp-block-jetpack-recurring-payments', 'wp-block-jetpack-recurring-payments wp-block-button', $content );
578            $subscribe_url = $this->get_subscription_url( $plan_id );
579
580            $content = preg_replace( '/(href=".*")/U', 'href="' . $subscribe_url . '"', $content );
581            $content = wp_kses_post( $content );
582
583            return $content;
584        }
585
586        return $this->deprecated_render_button_v1( $attributes, $plan_id );
587    }
588
589    /**
590     * Render email callback.
591     *
592     * @param string $block_content The block content.
593     * @param array  $parsed_block  The parsed block data.
594     * @param object $rendering_context The email rendering context.
595     *
596     * @return string
597     */
598    public function render_button_email( $block_content, array $parsed_block, $rendering_context ) {
599        // Check for the required renderers.
600        if ( ! function_exists( '\Automattic\Jetpack\Extensions\Button\render_email' ) || ! class_exists( '\Automattic\WooCommerce\EmailEditor\Integrations\Core\Renderer\Blocks\Button' ) ) {
601            return '';
602        }
603
604        // Get the first inner block, which should be the button block.
605        $button_block = $parsed_block['innerBlocks'][0] ?? array();
606
607        // We should only accept button blocks.
608        if ( empty( $button_block['blockName'] ) || 'jetpack/button' !== $button_block['blockName'] ) {
609            return '';
610        }
611
612        // We need attributes.
613        if ( ! isset( $button_block['attrs'] ) || ! is_array( $button_block['attrs'] ) ) {
614            return '';
615        }
616
617        // If the button block is missing text or url, return empty string.
618        if ( empty( $button_block['attrs']['text'] ) || empty( $button_block['attrs']['url'] ) ) {
619            return '';
620        }
621
622        // Reuse the button block's email rendering method.
623        return \Automattic\Jetpack\Extensions\Button\render_email( $block_content, $button_block, $rendering_context );
624    }
625
626    /**
627     * Builds subscription URL for this membership using the current blog and
628     * supplied plan IDs.
629     *
630     * @param integer $plan_id - Unique ID for the plan being subscribed to.
631     * @return string
632     */
633    public function get_subscription_url( $plan_id ) {
634        global $wp;
635
636        return add_query_arg(
637            array(
638                'blog'     => esc_attr( self::get_blog_id() ),
639                'plan'     => esc_attr( $plan_id ),
640                'lang'     => esc_attr( get_locale() ),
641                'pid'      => esc_attr( get_the_ID() ), // Needed for analytics purposes.
642                'redirect' => esc_attr( rawurlencode( home_url( $wp->request ) ) ), // Needed for redirect back in case of redirect-based flow.
643            ),
644            'https://subscribe.wordpress.com/memberships/'
645        );
646    }
647
648    /**
649     * Renders a deprecated legacy version of the button HTML.
650     *
651     * @param array   $attrs - Array containing the Recurring Payment block attributes.
652     * @param integer $plan_id - Unique plan ID the membership is for.
653     *
654     * @return string
655     */
656    public function deprecated_render_button_v1( $attrs, $plan_id ) {
657        $button_label = $attrs['submitButtonText'] ?? __( 'Your contribution', 'jetpack' );
658
659        $button_styles = array();
660        if ( ! empty( $attrs['customBackgroundButtonColor'] ) ) {
661            array_push(
662                $button_styles,
663                sprintf(
664                    'background-color: %s',
665                    sanitize_hex_color( $attrs['customBackgroundButtonColor'] )
666                )
667            );
668        }
669        if ( ! empty( $attrs['customTextButtonColor'] ) ) {
670            array_push(
671                $button_styles,
672                sprintf(
673                    'color: %s',
674                    sanitize_hex_color( $attrs['customTextButtonColor'] )
675                )
676            );
677        }
678        $button_styles = implode( ';', $button_styles );
679
680        return sprintf(
681            '<div class="%1$s"><a role="button" href="%2$s" class="%3$s" style="%4$s">%5$s</a></div>',
682            esc_attr(
683                Blocks::classes(
684                    self::$button_block_name,
685                    $attrs,
686                    array( 'wp-block-button' )
687                )
688            ),
689            esc_url( $this->get_subscription_url( $plan_id ) ),
690            isset( $attrs['submitButtonClasses'] ) ? esc_attr( $attrs['submitButtonClasses'] ) : 'wp-block-button__link',
691            esc_attr( $button_styles ),
692            wp_kses( $button_label, self::$tags_allowed_in_the_button )
693        );
694    }
695
696    /**
697     * Get current blog id.
698     *
699     * @return int
700     */
701    public static function get_blog_id() {
702        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
703            return get_current_blog_id();
704        }
705
706        return Jetpack_Options::get_option( 'id' );
707    }
708
709    /**
710     * Get the id of the connected payment acount (Stripe etc).
711     *
712     * @return bool
713     */
714    public static function has_connected_account() {
715
716        // This is the primary solution.
717        $has_option = get_option( self::$has_connected_account_option_name, false ) ? true : false;
718        if ( $has_option ) {
719            return true;
720        }
721
722        return false;
723    }
724
725    /**
726     * Get the post access level
727     *
728     * If no ID is provided, the method tries to get it from the global post object.
729     *
730     * @param int|null $post_id The ID of the post. Default is null.
731     *
732     * @return string the actual post access level (see projects/plugins/jetpack/extensions/blocks/subscriptions/constants.js for the values).
733     */
734    public static function get_post_access_level( $post_id = null ) {
735        if ( ! $post_id ) {
736            $post_id = get_the_ID();
737        }
738        if ( ! $post_id ) {
739            return Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_EVERYBODY;
740        }
741
742        $blog_id   = get_current_blog_id();
743        $cache_key = $blog_id . '_' . $post_id;
744
745        if ( isset( self::$post_access_level_cache[ $cache_key ] ) ) {
746            return self::$post_access_level_cache[ $cache_key ];
747        }
748
749        $post_access_level = get_post_meta( $post_id, self::$post_access_level_meta_name, true );
750        // Defaults to "everybody" when unset, and also when the stored value is not a
751        // string. Corrupt rows (e.g. a serialized array like a:1:{i:0;s:0:"";}) can be
752        // persisted by non-REST write paths, and an array flows unchanged into the
753        // strict string-typed `earn_user_has_access` callback on WPCOM, fataling the
754        // render. Coercing here keeps this canonical accessor's documented string
755        // contract regardless of how the meta was written.
756        if ( empty( $post_access_level ) || ! is_string( $post_access_level ) ) {
757            $post_access_level = Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_EVERYBODY;
758        }
759
760        // Only the editor switches a Paywall post to subscribers; REST, WP-CLI and importer saves don't.
761        // The block's name constant isn't loaded everywhere this runs, hence the literal.
762        if (
763            Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_EVERYBODY === $post_access_level
764            && has_block( 'jetpack/paywall', $post_id )
765        ) {
766            $post_access_level = Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_SUBSCRIBERS;
767        }
768
769        self::$post_access_level_cache[ $cache_key ] = $post_access_level;
770
771        return $post_access_level;
772    }
773
774    /**
775     * Get the post tier plan
776     *
777     * If no ID is provided, the method tries to get it from the global post object.
778     *
779     * @param int|null $post_id The ID of the post. Default is null.
780     *
781     * @return WP_Post|null the actual post tier.
782     */
783    public static function get_post_tier( $post_id = null ) {
784        if ( ! $post_id ) {
785            $post_id = get_the_ID();
786        }
787
788        if ( ! $post_id ) {
789            return null;
790        }
791
792        $post_tier_id = get_post_meta( $post_id, self::$post_access_tier_meta_name, true );
793        if ( empty( $post_tier_id ) ) {
794            return null;
795        }
796
797        return get_post( $post_tier_id );
798    }
799
800    /**
801     * Determines whether the current user can edit.
802     *
803     * @return bool Whether the user can edit.
804     */
805    public static function user_can_edit() {
806        $user = wp_get_current_user();
807        return 0 !== $user->ID && current_user_can( 'edit_post', get_the_ID() );
808    }
809
810    /**
811     * Clears the static cache for all users or for a given user.
812     *
813     * @param int|null $user_id The user_id to unset in the cache, otherwise the entire static cache is cleared.
814     * @return void
815     */
816    public static function clear_cache( ?int $user_id = null ) {
817        if ( empty( $user_id ) ) {
818            self::$user_is_paid_subscriber_cache = array();
819            self::$user_can_view_post_cache      = array();
820            return;
821        }
822        $prefix = $user_id . '_';
823        foreach ( array_keys( self::$user_is_paid_subscriber_cache ) as $cache_key ) {
824            if ( str_starts_with( $cache_key, $prefix ) ) {
825                unset( self::$user_is_paid_subscriber_cache[ $cache_key ] );
826            }
827        }
828        foreach ( array_keys( self::$user_can_view_post_cache ) as $cache_key ) {
829            if ( str_starts_with( $cache_key, $prefix ) ) {
830                unset( self::$user_can_view_post_cache[ $cache_key ] );
831            }
832        }
833    }
834
835    /**
836     * Determines whether the current user is a paid subscriber and caches the result.
837     *
838     * @param array    $valid_plan_ids An array of valid plan ids that the user could be subscribed to which would make the user able to view this content. Defaults to an empty array which will be filled with all newsletter plan IDs.
839     * @param int|null $user_id An optional user_id that can be used to determine service availability (defaults to checking if user is logged in if omitted).
840     * @return bool Whether the post can be viewed
841     */
842    public static function user_is_paid_subscriber( $valid_plan_ids = array(), $user_id = null ) {
843        if ( empty( $user_id ) ) {
844            $user_id = get_current_user_id();
845            if ( empty( $user_id ) ) {
846                return false;
847            }
848        }
849        // sort and stringify sorted valid plan ids to use as a cache key
850        sort( $valid_plan_ids );
851        $cache_key = $user_id . '_' . implode( ',', $valid_plan_ids );
852        if ( ! isset( self::$user_is_paid_subscriber_cache[ $cache_key ] ) ) {
853            require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/premium-content/_inc/subscription-service/include.php';
854            if ( empty( $valid_plan_ids ) ) {
855                $valid_plan_ids = self::get_all_newsletter_plan_ids();
856            }
857            $paywall            = \Automattic\Jetpack\Extensions\Premium_Content\subscription_service( $user_id );
858            $is_paid_subscriber = $paywall->visitor_can_view_content( $valid_plan_ids, Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_PAID_SUBSCRIBERS );
859            self::$user_is_paid_subscriber_cache[ $cache_key ] = $is_paid_subscriber;
860        }
861        return self::$user_is_paid_subscriber_cache[ $cache_key ];
862    }
863
864    /**
865     * Determines whether the current user has a pending subscription.
866     *
867     * @return bool Whether the user has a pending subscription
868     */
869    public static function user_is_pending_subscriber() {
870        require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/premium-content/_inc/subscription-service/include.php';
871        $subscription_service = \Automattic\Jetpack\Extensions\Premium_Content\subscription_service();
872        return $subscription_service->is_current_user_pending_subscriber();
873    }
874
875    /**
876     * Determines whether the current user can view the post based on the newsletter access level
877     * and caches the result.
878     *
879     * @param int|null $post_id Explicit post id to check against.
880     *
881     * @return bool Whether the post can be viewed
882     */
883    public static function user_can_view_post( $post_id = null ) {
884        return self::check_post_access( $post_id, true );
885    }
886
887    /**
888     * Check the post's subscription requirement without granting access for editing it.
889     *
890     * @since 16.4
891     *
892     * @param int|null $post_id Explicit post ID, or the loop post when omitted.
893     * @return bool Whether the visitor meets the post's subscription requirement.
894     */
895    public static function user_has_subscription_access( $post_id = null ) {
896        return self::check_post_access( $post_id, false );
897    }
898
899    /**
900     * Evaluate and cache post access with or without the editorial exception.
901     *
902     * @param int|null $post_id             Post to check.
903     * @param bool     $allow_editor_access Whether editing the post can grant access.
904     * @return bool Whether access is granted.
905     */
906    private static function check_post_access( $post_id, $allow_editor_access ) {
907        $user_id = get_current_user_id();
908        if ( null === $post_id ) {
909            $post_id = get_the_ID();
910        }
911
912        if ( false === $post_id ) {
913            $post_id = 0;
914        }
915
916        require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/premium-content/_inc/subscription-service/include.php';
917
918        // Answered before the cache: it is keyed by user, and the same request still renders for that user afterwards.
919        if ( \Automattic\Jetpack\Extensions\Premium_Content\is_rendering_for_activitypub() ) {
920            return Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_EVERYBODY === self::get_post_access_level( $post_id );
921        }
922
923        $cache_key = sprintf( '%d_%d_%d', $user_id, $post_id, (int) $allow_editor_access );
924        if ( isset( self::$user_can_view_post_cache[ $cache_key ] ) ) {
925            return self::$user_can_view_post_cache[ $cache_key ];
926        }
927
928        $post_access_level = self::get_post_access_level( $post_id );
929        if ( Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_EVERYBODY === $post_access_level ) {
930            self::$user_can_view_post_cache[ $cache_key ] = true;
931            return true;
932        }
933
934        // we are sending the post to subscribers so the user is a subscriber
935        if ( $allow_editor_access && defined( 'WPCOM_SENDING_POST_TO_SUBSCRIBERS' ) && WPCOM_SENDING_POST_TO_SUBSCRIBERS && Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_SUBSCRIBERS === $post_access_level ) {
936            self::$user_can_view_post_cache[ $cache_key ] = true;
937            return true;
938        }
939
940        $paywall = \Automattic\Jetpack\Extensions\Premium_Content\subscription_service();
941
942        $all_newsletters_plan_ids = self::get_all_newsletter_plan_ids();
943
944        if ( 0 === count( $all_newsletters_plan_ids ) &&
945            (
946                Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_PAID_SUBSCRIBERS === $post_access_level ||
947                Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_PAID_SUBSCRIBERS_ALL_TIERS === $post_access_level
948            )
949        ) {
950            // The post is paywalled but there is no newsletter plans on the site.
951            // We downgrade the post level to subscribers-only
952            $post_access_level = Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_SUBSCRIBERS;
953        }
954
955        // Pass the post explicitly: callers outside the loop have no get_the_ID() to fall back on.
956        if ( $allow_editor_access ) {
957            // @phan-suppress-next-line PhanParamTooMany -- Concrete services accept the optional $post_id; interface omits it on purpose.
958            $can_view_post = $paywall->visitor_can_view_content( $all_newsletters_plan_ids, $post_access_level, $post_id );
959        } else {
960            $can_view_post = is_callable( array( $paywall, 'visitor_has_subscription_access' ) )
961                && $paywall->visitor_has_subscription_access( $all_newsletters_plan_ids, $post_access_level, $post_id );
962        }
963
964        self::$user_can_view_post_cache[ $cache_key ] = $can_view_post;
965        return $can_view_post;
966    }
967
968    /**
969     * Whether Recurring Payments are enabled. True if the block
970     * is supported by the site's plan, or if it is a Jetpack site
971     * and the feature to enable upgrade nudges is active.
972     *
973     * @return bool
974     */
975    public static function is_enabled_jetpack_recurring_payments() {
976        $api_available = ( new Host() )->is_wpcom_simple() || Jetpack::is_connection_ready();
977        return $api_available;
978    }
979
980    /**
981     * Whether to enable the blocks in the editor.
982     * All Monetize blocks (except Simple Payments) need a user with at least `edit_posts` capability
983     *
984     * @return bool
985     */
986    public static function should_enable_monetize_blocks_in_editor() {
987        if ( ! is_admin() ) {
988            // We enable the block for the front-end in all cases
989            return true;
990
991        }
992
993        $is_offline_mode                  = ( new Status() )->is_offline_mode();
994        $enable_monetize_blocks_in_editor = ( new Host() )->is_wpcom_simple() || ( ! $is_offline_mode );
995        return $enable_monetize_blocks_in_editor;
996    }
997
998    /**
999     * Whether site has any paid plan.
1000     *
1001     * @param string $type - Type of a plan for which site is configured. For now supports empty and newsletter.
1002     *
1003     * @return bool
1004     */
1005    public static function has_configured_plans_jetpack_recurring_payments( $type = '' ) {
1006        if ( ! self::is_enabled_jetpack_recurring_payments() ) {
1007            return false;
1008        }
1009        $query = array(
1010            'post_type'      => self::$post_type_plan,
1011            'posts_per_page' => 1,
1012        );
1013
1014        // Newsletter tiers or legacy mailing list plans.
1015        if ( 'newsletter' === $type ) {
1016            $query['meta_query'] = array(
1017                // @phan-suppress-next-line PhanPluginMixedKeyNoKey
1018                'relation' => 'OR',
1019                array(
1020                    'key'   => 'jetpack_memberships_type',
1021                    'value' => self::$type_tier,
1022                ),
1023                array(
1024                    'key'   => 'jetpack_memberships_site_subscriber',
1025                    'value' => '1',
1026                ),
1027            );
1028        }
1029
1030        $plans = get_posts( $query );
1031        return ( is_countable( $plans ) && count( $plans ) > 0 );
1032    }
1033
1034    /**
1035     * Return the list of plan posts
1036     *
1037     * @return WP_Post[]|WP_Error
1038     */
1039    public static function get_all_plans() {
1040        if ( ! self::is_enabled_jetpack_recurring_payments() ) {
1041            return array();
1042        }
1043
1044        // We can retrieve the data directly except on a Jetpack/Atomic cached site or
1045        $is_cached_site = ( new Host() )->is_wpcom_simple() && is_jetpack_site();
1046        if ( ! $is_cached_site ) {
1047            return get_posts(
1048                array(
1049                    'posts_per_page' => -1,
1050                    'post_type'      => self::$post_type_plan,
1051                )
1052            );
1053        } else {
1054            // On cached site on WPCOM
1055            require_lib( 'memberships' );
1056            return Memberships_Product::get_plans_posts_list( get_current_blog_id() );
1057        }
1058    }
1059
1060    /**
1061     * Return all membership plans ids (deleted or not)
1062     * This function is used both on WPCOM or on Jetpack self-hosted.
1063     * Depending on the environment we need to mitigate where the data is retrieved from.
1064     *
1065     * @param bool $allow_deleted Whether to allow deleted plans to be returned. Defaults to true.
1066     *
1067     * @return array
1068     */
1069    public static function get_all_newsletter_plan_ids( $allow_deleted = true ) {
1070
1071        if ( ! self::is_enabled_jetpack_recurring_payments() ) {
1072            return array();
1073        }
1074
1075        // We can retrieve the data directly except on a Jetpack/Atomic cached site or
1076        $is_cached_site = ( new Host() )->is_wpcom_simple() && is_jetpack_site();
1077        if ( ! $is_cached_site ) {
1078            $meta_query = array(
1079                array(
1080                    'key'   => 'jetpack_memberships_type',
1081                    'value' => self::$type_tier,
1082                ),
1083            );
1084
1085            if ( $allow_deleted === false ) {
1086                $meta_query[] = array(
1087                    'key'     => 'jetpack_memberships_is_deleted',
1088                    'compare' => 'NOT EXISTS',
1089                );
1090            }
1091
1092            return get_posts(
1093                array(
1094                    'posts_per_page' => -1,
1095                    'fields'         => 'ids',
1096                    'post_type'      => self::$post_type_plan,
1097                    'meta_query'     => $meta_query,
1098                )
1099            );
1100
1101        } else {
1102            // On cached site on WPCOM
1103            require_lib( 'memberships' );
1104            $list = Memberships_Product::get_product_list( get_current_blog_id(), self::$type_tier, null, $allow_deleted );
1105
1106            if ( is_wp_error( $list ) ) {
1107                return array();
1108            }
1109
1110            return array_map(
1111                function ( $product ) {
1112                    return $product['id'];
1113                }, // Returning only post ids
1114                $list
1115            );
1116        }
1117    }
1118
1119    /**
1120     * Register the Recurring Payments Gutenberg block
1121     */
1122    public function register_gutenberg_block() {
1123        // This gate was introduced to prevent duplicate registration. A race condition exists where
1124        // the registration that happens via extensions/blocks/recurring-payments/recurring-payments.php
1125        // was adding the registration action after the action had been run in some contexts.
1126        if ( self::$has_registered_block ) {
1127            return;
1128        }
1129
1130        if ( self::is_enabled_jetpack_recurring_payments() ) {
1131            Blocks::jetpack_register_block(
1132                'jetpack/recurring-payments',
1133                array(
1134                    'render_callback'       => array( $this, 'render_button' ),
1135                    'render_email_callback' => array( $this, 'render_button_email' ),
1136                    'uses_context'          => array( 'isPremiumContentChild' ),
1137                    'provides_context'      => array(
1138                        'jetpack/parentBlockWidth' => 'width',
1139                    ),
1140                )
1141            );
1142        } else {
1143            Jetpack_Gutenberg::set_extension_unavailable(
1144                'recurring-payments',
1145                'missing_plan',
1146                array(
1147                    'required_feature' => 'memberships',
1148                    'required_plan'    => self::$required_plan,
1149                )
1150            );
1151        }
1152
1153        self::$has_registered_block = true;
1154    }
1155
1156    /**
1157     * Transforms a number into a human-readable join text string.
1158     *
1159     * Supports short form (e.g. 45.8K), longer rounded format (e.g. 45,800), and raw count (e.g. 45,806)
1160     * via the `jetpack_memberships_subscriber_count_format` filter.
1161     *
1162     * @param int $subscribers_total Total number of subscribers.
1163     *
1164     * @return string Human-readable version of the number in context.
1165     */
1166    public static function get_join_others_text( $subscribers_total ) {
1167        $subscribers_total = absint( $subscribers_total );
1168
1169        /**
1170         * Filter the format used for the subscriber count in the join others text.
1171         *
1172         * @since 16.4
1173         *
1174         * @param string $format            Subscriber count format: 'short', 'rounded', or 'raw'. Default 'short'.
1175         * @param int    $subscribers_total Total number of subscribers.
1176         */
1177        $format = apply_filters( 'jetpack_memberships_subscriber_count_format', 'short', $subscribers_total );
1178
1179        switch ( strtolower( (string) $format ) ) {
1180            case 'raw':
1181                /* translators: %s: number of folks following the blog */
1182                $text = sprintf( _n( 'Join %s other subscriber', 'Join %s other subscribers', $subscribers_total, 'jetpack' ), number_format_i18n( $subscribers_total ) );
1183                break;
1184
1185            case 'rounded':
1186                if ( $subscribers_total >= 1000000 ) {
1187                    $rounded_total = (int) round( round( $subscribers_total / 1000000, 1 ) * 1000000 );
1188                } elseif ( $subscribers_total >= 10000 ) {
1189                    $rounded_total = (int) round( round( $subscribers_total / 1000, 1 ) * 1000 );
1190                } else {
1191                    $rounded_total = $subscribers_total;
1192                }
1193
1194                /* translators: %s: number of folks following the blog */
1195                $text = sprintf( _n( 'Join %s other subscriber', 'Join %s other subscribers', $rounded_total, 'jetpack' ), number_format_i18n( $rounded_total ) );
1196                break;
1197
1198            case 'short':
1199            default:
1200                if ( $subscribers_total >= 1000000 ) {
1201                    /* translators: %s: number of folks following the blog, millions(M) with one decimal. i.e. 1.1 */
1202                    $text = sprintf( __( 'Join %sM other subscribers', 'jetpack' ), floatval( number_format_i18n( $subscribers_total / 1000000, 1 ) ) );
1203                } elseif ( $subscribers_total >= 10000 ) {
1204                    /* translators: %s: number of folks following the blog, thousands(K) with one decimal. i.e. 1.1 */
1205                    $text = sprintf( __( 'Join %sK other subscribers', 'jetpack' ), floatval( number_format_i18n( $subscribers_total / 1000, 1 ) ) );
1206                } else {
1207                    /* translators: %s: number of folks following the blog */
1208                    $text = sprintf( _n( 'Join %s other subscriber', 'Join %s other subscribers', $subscribers_total, 'jetpack' ), number_format_i18n( $subscribers_total ) );
1209                }
1210                break;
1211        }
1212
1213        return $text;
1214    }
1215
1216    /**
1217     * Returns the email of the current user.
1218     *
1219     * @return string
1220     */
1221    public static function get_current_user_email() {
1222        require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/premium-content/_inc/subscription-service/include.php';
1223        $subscription_service = \Automattic\Jetpack\Extensions\Premium_Content\subscription_service();
1224        return $subscription_service->get_subscriber_email();
1225    }
1226
1227    /**
1228     * Returns if the current user is subscribed or not.
1229     *
1230     * @return boolean
1231     */
1232    public static function is_current_user_subscribed() {
1233        require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/premium-content/_inc/subscription-service/include.php';
1234        $subscription_service = \Automattic\Jetpack\Extensions\Premium_Content\subscription_service();
1235        return $subscription_service->is_current_user_subscribed();
1236    }
1237
1238    /**
1239     * Render a tier description (stored as markdown text) to safe HTML.
1240     *
1241     * Uses Jetpack's markdown parser, restores paragraph structure (the parser
1242     * strips <p> tags expecting wpautop to run later), forces links to open in a
1243     * new tab (descriptions are shown inside the subscribe modal's iframe), and
1244     * finally sanitizes the output to a small tag allowlist.
1245     *
1246     * @param mixed $description Raw tier description (markdown text). Non-scalar
1247     *                          values are treated as empty.
1248     * @return string Sanitized HTML, or an empty string for an empty description.
1249     */
1250    public static function render_tier_description_html( $description ) {
1251        if ( ! is_scalar( $description ) ) {
1252            return '';
1253        }
1254        $description = (string) $description;
1255        if ( '' === trim( $description ) ) {
1256            return '';
1257        }
1258
1259        if ( ! class_exists( 'WPCom_Markdown' ) ) {
1260            require_once JETPACK__PLUGIN_DIR . 'modules/markdown/easy-markdown.php';
1261        }
1262
1263        $html = WPCom_Markdown::get_instance()->transform(
1264            $description,
1265            array(
1266                'unslash' => false,
1267                'id'      => false,
1268            )
1269        );
1270        $html = wpautop( $html );
1271        $html = links_add_target( $html, '_blank' );
1272
1273        return wp_kses( $html, self::TIER_DESCRIPTION_ALLOWED_HTML );
1274    }
1275}
1276Jetpack_Memberships::get_instance();