Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
35.75% covered (danger)
35.75%
261 / 730
11.90% covered (danger)
11.90%
5 / 42
CRAP
n/a
0 / 0
Automattic\Jetpack\Extensions\Subscriptions\register_block
86.07% covered (warning)
86.07%
105 / 122
0.00% covered (danger)
0.00%
0 / 1
11.33
Automattic\Jetpack\Extensions\Subscriptions\is_wpcom
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
Automattic\Jetpack\Extensions\Subscriptions\reject_unknown_access_level
92.00% covered (success)
92.00%
23 / 25
0.00% covered (danger)
0.00%
0 / 1
9.04
Automattic\Jetpack\Extensions\Subscriptions\register_newsletter_access_column
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
Automattic\Jetpack\Extensions\Subscriptions\add_paywalled_content_post_meta
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
7
Automattic\Jetpack\Extensions\Subscriptions\render_newsletter_access_rows
75.00% covered (warning)
75.00%
12 / 16
0.00% covered (danger)
0.00%
0 / 1
7.77
Automattic\Jetpack\Extensions\Subscriptions\newsletter_access_column_styles
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
Automattic\Jetpack\Extensions\Subscriptions\fetch_subscriber_counts
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
Automattic\Jetpack\Extensions\Subscriptions\get_subscriber_count
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
Automattic\Jetpack\Extensions\Subscriptions\has_attribute
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
Automattic\Jetpack\Extensions\Subscriptions\get_attribute
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
Automattic\Jetpack\Extensions\Subscriptions\get_setting_class_name
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
Automattic\Jetpack\Extensions\Subscriptions\get_element_class_names_from_attributes
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
6
Automattic\Jetpack\Extensions\Subscriptions\is_button_only_style
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
Automattic\Jetpack\Extensions\Subscriptions\get_element_styles_from_attributes
0.00% covered (danger)
0.00%
0 / 54
0.00% covered (danger)
0.00%
0 / 1
182
Automattic\Jetpack\Extensions\Subscriptions\get_attribute_color
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
Automattic\Jetpack\Extensions\Subscriptions\get_global_style_color
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
Automattic\Jetpack\Extensions\Subscriptions\get_color_from_slug
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
72
Automattic\Jetpack\Extensions\Subscriptions\is_jetpack_memberships_loaded
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
Automattic\Jetpack\Extensions\Subscriptions\render_block
0.00% covered (danger)
0.00%
0 / 53
0.00% covered (danger)
0.00%
0 / 1
462
Automattic\Jetpack\Extensions\Subscriptions\get_post_access_level_for_current_post
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
Automattic\Jetpack\Extensions\Subscriptions\render_for_website
0.00% covered (danger)
0.00%
0 / 117
0.00% covered (danger)
0.00%
0 / 1
702
Automattic\Jetpack\Extensions\Subscriptions\render_for_email
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
Automattic\Jetpack\Extensions\Subscriptions\render_email
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
6
Automattic\Jetpack\Extensions\Subscriptions\add_paywall
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
42
Automattic\Jetpack\Extensions\Subscriptions\maybe_close_comments
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
Automattic\Jetpack\Extensions\Subscriptions\maybe_gate_existing_comments
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
Automattic\Jetpack\Extensions\Subscriptions\is_jetpack_token_subscription_service_loaded
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\Extensions\Subscriptions\maybe_prevent_super_cache_caching
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
Automattic\Jetpack\Extensions\Subscriptions\get_paywall_content
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
Automattic\Jetpack\Extensions\Subscriptions\get_current_url
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
110
Automattic\Jetpack\Extensions\Subscriptions\get_submit_button_text
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
Automattic\Jetpack\Extensions\Subscriptions\is_top_subscription
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
Automattic\Jetpack\Extensions\Subscriptions\sanitize_submit_text
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
Automattic\Jetpack\Extensions\Subscriptions\get_paywall_blocks
63.83% covered (warning)
63.83%
30 / 47
0.00% covered (danger)
0.00%
0 / 1
14.73
Automattic\Jetpack\Extensions\Subscriptions\is_user_auth
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
6.56
Automattic\Jetpack\Extensions\Subscriptions\print_silent_subscriber_check
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
10
Automattic\Jetpack\Extensions\Subscriptions\print_silent_subscriber_check_cleanup
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
Automattic\Jetpack\Extensions\Subscriptions\is_paid_post
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
Automattic\Jetpack\Extensions\Subscriptions\is_subscribers_post
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
Automattic\Jetpack\Extensions\Subscriptions\get_paywall_blocks_subscribe_pending
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
Automattic\Jetpack\Extensions\Subscriptions\get_paywall_simple
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
42
1<?php
2/**
3 * Subscriptions Block.
4 *
5 * @package automattic/jetpack
6 */
7
8namespace Automattic\Jetpack\Extensions\Subscriptions;
9
10use Automattic\Jetpack\Blocks;
11use Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service\Abstract_Token_Subscription_Service;
12use Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service\Jetpack_Token_Subscription_Service;
13use Automattic\Jetpack\Modules;
14use Automattic\Jetpack\Status;
15use Automattic\Jetpack\Status\Host;
16use Automattic\Jetpack\Status\Request;
17use Jetpack_Gutenberg;
18use Jetpack_Memberships;
19use Jetpack_Subscriptions_Widget;
20
21if ( ! defined( 'ABSPATH' ) ) {
22    exit( 0 );
23}
24
25require_once __DIR__ . '/class-jetpack-subscription-site.php';
26require_once __DIR__ . '/constants.php';
27require_once JETPACK__PLUGIN_DIR . 'modules/subscriptions/class-jetpack-subscriber-data.php';
28require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/premium-content/_inc/subscription-service/include.php';
29
30/**
31 * These block defaults should match ./constants.js
32 */
33const DEFAULT_BORDER_RADIUS_VALUE = 0;
34const DEFAULT_BORDER_WEIGHT_VALUE = 1;
35const DEFAULT_FONTSIZE_VALUE      = '16px';
36const DEFAULT_PADDING_VALUE       = 15;
37const DEFAULT_SPACING_VALUE       = 10;
38const DEFAULT_BUTTON_WIDTH        = 'auto';
39
40/**
41 * Registers the block for use in Gutenberg
42 * This is done via an action so that we can disable
43 * registration if we need to.
44 */
45function register_block() {
46    /*
47     * Disable the feature on P2 blogs
48     */
49    if ( function_exists( '\WPForTeams\is_wpforteams_site' ) &&
50        \WPForTeams\is_wpforteams_site( get_current_blog_id() ) ) {
51        return;
52    }
53
54    /*
55     * Do not proceed if the newsletter feature (Subscriptions module) is not enabled
56     */
57    if ( ! ( new Modules() )->is_active( 'subscriptions' ) ) {
58        Jetpack_Gutenberg::set_extension_unavailable( 'subscriptions', 'missing_module', array( 'module' => 'subscriptions' ) );
59        return;
60    }
61
62    require_once JETPACK__PLUGIN_DIR . '/modules/memberships/class-jetpack-memberships.php';
63
64    if ( \Jetpack_Memberships::should_enable_monetize_blocks_in_editor() ) {
65        Blocks::jetpack_register_block(
66            __DIR__,
67            array(
68                'render_callback'       => __NAMESPACE__ . '\render_block',
69                'render_email_callback' => __NAMESPACE__ . '\render_email',
70                'supports'              => array(
71                    'spacing' => array(
72                        'margin'  => true,
73                        'padding' => true,
74                    ),
75                    'align'   => array( 'wide', 'full' ),
76                ),
77            )
78        );
79    }
80
81    register_post_meta(
82        'post',
83        META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS,
84        array(
85            'show_in_rest'      => true,
86            'single'            => true,
87            'type'              => 'string',
88            /* translators: Keep the quoted values, block names and meta keys in English. */
89            'description'       => __( 'Who can read the post on the site: "everybody" (the default, also when empty), "subscribers" (free and paid) or "paid_subscribers" (paid only). Anyone without access sees a subscribe prompt instead. "everybody" and "subscribers" posts are emailed to all subscribers, "paid_subscribers" posts only to paid ones; with newsletter categories on, only to those subscribed to one of its categories or to all content. To show a free preview, add a Paywall block (jetpack/paywall) where it should end: everything above it stays public, the post is emailed to all subscribers and cut off at the paywall for anyone without access, and an "everybody" post becomes subscribers-only below the block. "paid_subscribers" works only on sites that already have a paid newsletter tier. Without one, the owner first connects Stripe and adds a tier under Monetize > Payment Settings in the WordPress.com dashboard (Jetpack Cloud on self-hosted sites). If unsure a tier exists, check with the site owner first.', 'jetpack' ),
90            // The REST schema already rejects non-strings, but non-REST writers
91            // (importers, XML-RPC, WP-CLI, direct update_post_meta, sync) only pass
92            // through sanitize_meta(). Coerce anything that isn't a string to ''
93            // ("everybody") so a corrupt value can't be persisted and later fatal the
94            // strict string-typed access checks.
95            'sanitize_callback' => function ( $value ) {
96                return is_string( $value ) ? $value : '';
97            },
98            'auth_callback'     => function () {
99                return wp_get_current_user()->has_cap( 'edit_posts' );
100            },
101        )
102    );
103
104    // The meta is a "don't send" flag, so invert the blog option (which defaults to true = "send").
105    $dont_email_default = ! get_option( 'wpcom_newsletter_send_default', true );
106
107    register_post_meta(
108        'post',
109        META_NAME_FOR_POST_DONT_EMAIL_TO_SUBS,
110        array(
111            'default'       => $dont_email_default,
112            'show_in_rest'  => true,
113            'single'        => true,
114            'type'          => 'boolean',
115            /* translators: Keep the quoted values, block names and meta keys in English. */
116            'description'   => __( 'Set to true to publish without emailing the post to subscribers. The email is sent once, when the post goes live, so this has to be set in the request that publishes it, or any time before the date of a scheduled post. Once the post is published, changing it neither sends nor recalls the email. The default comes from the site\'s newsletter settings and can be either value, so send it explicitly when the email matters.', 'jetpack' ),
117            'auth_callback' => function () {
118                return wp_get_current_user()->has_cap( 'edit_posts' );
119            },
120        )
121    );
122
123    register_post_meta(
124        'post',
125        META_NAME_FOR_POST_TIER_ID_SETTINGS,
126        array(
127            'show_in_rest'  => true,
128            'single'        => true,
129            'type'          => 'integer',
130            /* translators: Keep the quoted values, block names and meta keys in English. */
131            'description'   => __( 'Only applies when _jetpack_newsletter_access is "paid_subscribers": the ID of the monthly paid newsletter tier a reader needs. Subscribers on that tier, its yearly plan or a plan priced the same or higher in the same currency can read the post and get the email. Unset or 0 lets every paid subscriber in, which is the right value unless the site owner names a specific tier. An ID that matches no tier is ignored.', 'jetpack' ),
132            'auth_callback' => function () {
133                return wp_get_current_user()->has_cap( 'edit_posts' );
134            },
135        )
136    );
137
138    register_post_meta(
139        'post',
140        META_NAME_CONTAINS_PAYWALLED_CONTENT,
141        array(
142            'show_in_rest'  => true,
143            'single'        => true,
144            'type'          => 'boolean',
145            /* translators: Keep the quoted values, block names and meta keys in English. */
146            'description'   => __( 'Computed on every save: true when the post has a Paywall block or its _jetpack_newsletter_access is "subscribers" or "paid_subscribers". Any value sent here is overwritten; change _jetpack_newsletter_access or the content instead.', 'jetpack' ),
147            'auth_callback' => function () {
148                return wp_get_current_user()->has_cap( 'edit_posts' );
149            },
150        )
151    );
152
153    // This ensures Jetpack will sync this post meta to WPCOM.
154    add_filter(
155        'jetpack_sync_post_meta_whitelist',
156        function ( $allowed_meta ) {
157            return array_merge(
158                $allowed_meta,
159                array(
160                    META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS,
161                    META_NAME_FOR_POST_DONT_EMAIL_TO_SUBS,
162                    META_NAME_CONTAINS_PAYWALLED_CONTENT,
163                    META_NAME_FOR_POST_TIER_ID_SETTINGS,
164                    META_NAME_CONTAINS_PAID_CONTENT,
165                )
166            );
167        }
168    );
169
170    // Hide the content â€“ Priority 8 makes it run before do_blocks gets called for the content
171    add_filter( 'the_content', __NAMESPACE__ . '\add_paywall', 8 );
172
173    // Close comments on the front-end
174    add_filter( 'comments_open', __NAMESPACE__ . '\maybe_close_comments', 10, 2 );
175    add_filter( 'pings_open', __NAMESPACE__ . '\maybe_close_comments', 10, 2 );
176
177    // Hide existing comments
178    add_filter( 'get_comment', __NAMESPACE__ . '\maybe_gate_existing_comments' );
179
180    // Add a 'Newsletter' column to the Edit posts page
181    // We only display the "Newsletter" column if we have configured the paid newsletter plan
182    if ( defined( 'WP_ADMIN' ) && WP_ADMIN && Jetpack_Memberships::has_configured_plans_jetpack_recurring_payments( 'newsletter' ) ) {
183        add_action( 'manage_post_posts_columns', __NAMESPACE__ . '\register_newsletter_access_column' );
184        add_action( 'manage_post_posts_custom_column', __NAMESPACE__ . '\render_newsletter_access_rows', 10, 2 );
185        add_action( 'admin_head', __NAMESPACE__ . '\newsletter_access_column_styles' );
186    }
187
188    add_action( 'init', __NAMESPACE__ . '\maybe_prevent_super_cache_caching' );
189
190    add_action( 'wp_head', __NAMESPACE__ . '\print_silent_subscriber_check_cleanup', 1 );
191
192    add_action( 'wp_after_insert_post', __NAMESPACE__ . '\add_paywalled_content_post_meta', 99, 2 );
193
194    add_filter( 'rest_pre_insert_post', __NAMESPACE__ . '\reject_unknown_access_level', 10, 2 );
195
196    add_filter(
197        'jetpack_options_whitelist',
198        function ( $options ) {
199            $options[] = 'jetpack_subscriptions_subscribe_post_end_enabled';
200            $options[] = 'jetpack_subscriptions_subscribe_navigation_enabled';
201
202            return $options;
203        }
204    );
205
206    // The WordPress.com Simple JSON API loads the theme late and replays `init` as `restapi_theme_init`.
207    if ( ( new Host() )->is_wpcom_simple() && ! Request::is_frontend() ) {
208        add_action(
209            'restapi_theme_init',
210            function () {
211                Jetpack_Subscription_Site::init()->handle_subscribe_block_placements();
212            }
213        );
214    } else {
215        Jetpack_Subscription_Site::init()->handle_subscribe_block_placements();
216    }
217}
218add_action( 'init', __NAMESPACE__ . '\register_block', 9 );
219
220/**
221 * Returns true when in a WP.com environment.
222 *
223 * @return boolean
224 */
225function is_wpcom() {
226    return defined( 'IS_WPCOM' ) && IS_WPCOM;
227}
228
229/**
230 * Rejects a REST request that sets an unknown access level, before the post is saved.
231 *
232 * The access check treats an unknown value as "everybody", so a typo like "paid"
233 * would publish a paid post to everyone. This runs here rather than as a schema
234 * enum because core checks meta against the schema only after the post is saved.
235 *
236 * @param \stdClass|\WP_Error $prepared_post Post about to be saved.
237 * @param \WP_REST_Request    $request       Request being handled.
238 * @return \stdClass|\WP_Error
239 */
240function reject_unknown_access_level( $prepared_post, $request ) {
241    // A missing value is left alone, and null deletes the meta, which core handles.
242    if (
243        is_wp_error( $prepared_post )
244        || ! $request instanceof \WP_REST_Request
245        || ! isset( $request['meta'][ META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS ] )
246    ) {
247        return $prepared_post;
248    }
249
250    // Autosaves never store this meta, and the autosaves controller doesn't check
251    // for an error here, so rejecting would drop the author's autosaved edits.
252    if ( str_ends_with( strtolower( $request->get_route() ), '/autosaves' ) ) {
253        return $prepared_post;
254    }
255
256    // PAID_SUBSCRIBERS_ALL_TIERS is left out: no editor or API client sets it, and
257    // WordPress.com would email such a post to every subscriber.
258    $allowed      = array(
259        Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_EVERYBODY,
260        Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_SUBSCRIBERS,
261        Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_PAID_SUBSCRIBERS,
262    );
263    $access_level = $request['meta'][ META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS ];
264    // REST returns '' for a post with no value set and the editor sends it back on
265    // save; the access check reads '' as "everybody".
266    if ( '' === $access_level || in_array( $access_level, $allowed, true ) ) {
267        return $prepared_post;
268    }
269
270    // The editor sends every meta value back on save, so a post that already holds an
271    // unknown value must still save as long as the request doesn't change it.
272    if ( ! empty( $prepared_post->ID ) && get_post_meta( $prepared_post->ID, META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS, true ) === $access_level ) {
273        return $prepared_post;
274    }
275
276    return new \WP_Error(
277        'rest_invalid_param',
278        sprintf(
279            /* translators: 1: meta key, 2: comma-separated list of allowed values. Both are displayed in English. */
280            __( '%1$s must be one of %2$s.', 'jetpack' ),
281            META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS,
282            '"' . implode( '", "', $allowed ) . '"'
283        ),
284        array( 'status' => 400 )
285    );
286}
287
288/**
289 * Adds a 'Newsletter' column after the 'Title' column in the post list
290 *
291 * @param array $columns An array of column names.
292 * @return array An array of column names.
293 */
294function register_newsletter_access_column( $columns ) {
295    $position   = array_search( 'title', array_keys( $columns ), true );
296    $new_column = array( NEWSLETTER_COLUMN_ID => __( 'Newsletter', 'jetpack' ) );
297    return array_merge(
298        array_slice( $columns, 0, $position + 1, true ),
299        $new_column,
300        array_slice( $columns, $position, null, true )
301    );
302}
303
304/**
305 * Add a meta to prevent publication on firehose, ES AI or Reader
306 *
307 * @param int      $post_id Post id being saved.
308 * @param \WP_Post $post Post being saved.
309 * @return void
310 */
311function add_paywalled_content_post_meta( int $post_id, \WP_Post $post ) {
312    if ( $post->post_type !== 'post' ) {
313        return;
314    }
315
316    $access_level = get_post_meta( $post_id, META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS, true );
317
318    // A Paywall block gates the post whatever the stored access level; see Jetpack_Memberships::get_post_access_level().
319    $is_paywalled = has_block( \Automattic\Jetpack\Extensions\Paywall\BLOCK_NAME, $post );
320    switch ( $access_level ) {
321        case Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_PAID_SUBSCRIBERS_ALL_TIERS:
322        case Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_PAID_SUBSCRIBERS:
323        case Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_SUBSCRIBERS:
324            $is_paywalled = true;
325    }
326    if ( $is_paywalled ) {
327        update_post_meta( $post_id, META_NAME_CONTAINS_PAYWALLED_CONTENT, $is_paywalled );
328    }
329    if ( ! $is_paywalled ) {
330        delete_post_meta( $post_id, META_NAME_CONTAINS_PAYWALLED_CONTENT );
331    }
332}
333
334/**
335 * Displays the newsletter access level.
336 *
337 * @param string $column_id The ID of the column to display.
338 * @param int    $post_id The current post ID.
339 */
340function render_newsletter_access_rows( $column_id, $post_id ) {
341    if ( NEWSLETTER_COLUMN_ID !== $column_id ) {
342        return;
343    }
344
345    $access_level = Jetpack_Memberships::get_post_access_level( $post_id );
346
347    switch ( $access_level ) {
348        case Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_PAID_SUBSCRIBERS_ALL_TIERS:
349            echo esc_html__( 'Paid Subscribers (all plans)', 'jetpack' );
350            break;
351        case Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_PAID_SUBSCRIBERS:
352            echo esc_html__( 'Paid Subscribers', 'jetpack' );
353            break;
354        case Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_SUBSCRIBERS:
355            echo esc_html__( 'Subscribers', 'jetpack' );
356            break;
357        case Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_EVERYBODY:
358            echo esc_html__( 'Everybody', 'jetpack' );
359            break;
360        default:
361            echo '';
362    }
363}
364
365/**
366 * Adds the Newsletter column styles
367 */
368function newsletter_access_column_styles() {
369    echo '<style id="jetpack-newsletter-newsletter-access-column"> table.fixed .column-newsletter_access { width: 10%; } </style>';
370}
371
372/**
373 * Determine the amount of folks currently subscribed to the blog, splitted out in total_subscribers, email_subscribers, social_followers & paid_subscribers.
374 *
375 * @return array containing ['value' => ['total_subscribers' => 0, 'email_subscribers' => 0, 'paid_subscribers' => 0, 'social_followers' => 0]]
376 */
377function fetch_subscriber_counts() {
378    return \Jetpack_Subscriber_Data::get_counts();
379}
380
381/**
382 * Returns subscriber count based on include_social_followers attribute
383 *
384 * @param bool $include_social_followers Whether to include social followers in the count.
385 * @return int
386 */
387function get_subscriber_count( $include_social_followers ) {
388    $counts = fetch_subscriber_counts();
389
390    if ( $include_social_followers ) {
391        $subscriber_count = $counts['value']['total_subscribers'] + $counts['value']['social_followers'];
392    } else {
393        $subscriber_count = $counts['value']['total_subscribers'];
394    }
395    return $subscriber_count;
396}
397
398/**
399 * Returns true if the block attributes contain a value for the given key.
400 *
401 * @param array  $attributes Array containing the block attributes.
402 * @param string $key        Block attribute key.
403 *
404 * @return boolean
405 */
406function has_attribute( $attributes, $key ) {
407    return isset( $attributes[ $key ] ) && $attributes[ $key ] !== 'undefined';
408}
409
410/**
411 * Returns the value for the given attribute key, with the option of providing a default fallback value.
412 *
413 * @param array  $attributes Array containing the block attributes.
414 * @param string $key        Block attribute key.
415 * @param mixed  $default    Optional fallback value in case the key doesn't exist.
416 *
417 * @return mixed
418 */
419function get_attribute( $attributes, $key, $default = null ) {
420    return has_attribute( $attributes, $key ) ? $attributes[ $key ] : $default;
421}
422
423/**
424 * Mimics getColorClassName, getFontSizeClass and getGradientClass from @wordpress/block-editor js package.
425 *
426 * @param string $setting Setting name.
427 * @param string $value   Setting value.
428 *
429 * @return string
430 */
431function get_setting_class_name( $setting, $value ) {
432    if ( ! $setting || ! $value ) {
433        return '';
434    }
435
436    return sprintf( 'has-%s-%s', $value, $setting );
437}
438
439/**
440 * Uses block attributes to generate an array containing the classes for various block elements.
441 * Based on Jetpack_Subscriptions_Widget::do_subscription_form() which the block was originally using.
442 *
443 * @param array $attributes Array containing the block attributes.
444 *
445 * @return array
446 */
447function get_element_class_names_from_attributes( $attributes ) {
448    $text_color_class = get_setting_class_name( 'color', get_attribute( $attributes, 'textColor' ) );
449    $font_size_class  = get_setting_class_name( 'font-size', get_attribute( $attributes, 'fontSize' ) );
450    $border_class     = get_setting_class_name( 'border-color', get_attribute( $attributes, 'borderColor' ) );
451
452    $button_background_class = get_setting_class_name( 'background-color', get_attribute( $attributes, 'buttonBackgroundColor' ) );
453    $button_gradient_class   = get_setting_class_name( 'gradient-background', get_attribute( $attributes, 'buttonGradient' ) );
454
455    $email_field_background_class = get_setting_class_name( 'background-color', get_attribute( $attributes, 'emailFieldBackgroundColor' ) );
456    $email_field_gradient_class   = get_setting_class_name( 'gradient-background', get_attribute( $attributes, 'emailFieldGradient' ) );
457
458    $submit_button_classes = array_filter(
459        array(
460            'wp-block-button__link'  => true,
461            'no-border-radius'       => 0 === get_attribute( $attributes, 'borderRadius', 0 ),
462            $font_size_class         => true,
463            $border_class            => true,
464            'has-text-color'         => ! empty( $text_color_class ),
465            $text_color_class        => true,
466            'has-background'         => ! empty( $button_background_class ) || ! empty( $button_gradient_class ),
467            $button_background_class => ! empty( $button_background_class ),
468            $button_gradient_class   => ! empty( $button_gradient_class ),
469        )
470    );
471
472    $email_field_classes = array_filter(
473        array(
474            'no-border-radius'            => 0 === get_attribute( $attributes, 'borderRadius', 0 ),
475            $font_size_class              => true,
476            $border_class                 => true,
477            $email_field_background_class => true,
478            $email_field_gradient_class   => true,
479        )
480    );
481
482    $block_wrapper_classes = array_filter(
483        array(
484            'wp-block-jetpack-subscriptions__supports-newline' => true,
485            'wp-block-jetpack-subscriptions__use-newline' => (bool) get_attribute( $attributes, 'buttonOnNewLine' ),
486            'wp-block-jetpack-subscriptions__show-subs'   => (bool) get_attribute( $attributes, 'showSubscribersTotal' ),
487        )
488    );
489
490    return array(
491        'block_wrapper' => implode( ' ', array_keys( $block_wrapper_classes ) ),
492        'email_field'   => implode( ' ', array_keys( $email_field_classes ) ),
493        'submit_button' => implode( ' ', array_keys( $submit_button_classes ) ),
494    );
495}
496
497/**
498 * Checks if block style is "button only"
499 *
500 * @param string $class_name Block attribute className; multiple names are spearated by space.
501 *
502 * @return bool
503 */
504function is_button_only_style( $class_name ) {
505    if ( empty( $class_name ) ) {
506        return false;
507    }
508
509    $class_names = explode( ' ', $class_name );
510    return in_array( 'is-style-button', $class_names, true );
511}
512
513/**
514 * Uses block attributes to generate an array containing the styles for various block elements.
515 * Based on Jetpack_Subscriptions_Widget::do_subscription_form() which the block was originally using.
516 *
517 * @param array $attributes Array containing the block attributes.
518 *
519 * @return array
520 */
521function get_element_styles_from_attributes( $attributes ) {
522    $is_button_only_style = is_button_only_style( get_attribute( $attributes, 'className', '' ) );
523
524    $button_background_style = ! has_attribute( $attributes, 'buttonBackgroundColor' ) && has_attribute( $attributes, 'customButtonGradient' )
525        ? get_attribute( $attributes, 'customButtonGradient' )
526        : get_attribute( $attributes, 'customButtonBackgroundColor' );
527
528    $email_field_styles           = '';
529    $submit_button_wrapper_styles = '';
530    $submit_button_styles         = '';
531
532    if ( ! empty( $button_background_style ) ) {
533        $submit_button_styles .= sprintf( 'background: %s;', $button_background_style );
534    }
535
536    if ( has_attribute( $attributes, 'customTextColor' ) ) {
537        $submit_button_styles .= sprintf( 'color: %s;', get_attribute( $attributes, 'customTextColor' ) );
538    }
539
540    if ( has_attribute( $attributes, 'buttonWidth' ) ) {
541        $submit_button_wrapper_styles .= sprintf( 'width: %s;', get_attribute( $attributes, 'buttonWidth', DEFAULT_BUTTON_WIDTH ) );
542        $submit_button_wrapper_styles .= 'max-width: 100%;';
543
544        // Account for custom margins on inline forms.
545        $submit_button_styles .= true === get_attribute( $attributes, 'buttonOnNewLine' )
546            ? 'width: 100%;'
547            : sprintf( 'width: calc(100%% - %dpx);', get_attribute( $attributes, 'spacing', DEFAULT_SPACING_VALUE ) );
548    }
549
550    $font_size = get_attribute( $attributes, 'customFontSize', DEFAULT_FONTSIZE_VALUE );
551    $style     = sprintf( 'font-size: %s%s;', $font_size, is_numeric( $font_size ) ? 'px' : '' );
552
553    $submit_button_styles .= $style;
554    $email_field_styles   .= $style;
555
556    $padding = get_attribute( $attributes, 'padding', DEFAULT_PADDING_VALUE );
557    $style   = sprintf( 'padding: %1$dpx %2$dpx %1$dpx %2$dpx;', $padding, round( $padding * 1.5 ) );
558
559    $submit_button_styles .= $style;
560    $email_field_styles   .= $style;
561
562    if ( ! $is_button_only_style ) {
563        $button_spacing = get_attribute( $attributes, 'spacing', DEFAULT_SPACING_VALUE );
564        if ( true === get_attribute( $attributes, 'buttonOnNewLine' ) ) {
565            $submit_button_styles .= sprintf( 'margin-top: %dpx;', $button_spacing );
566        } else {
567            $submit_button_styles .= 'margin: 0; '; // Reset Safari's 2px default margin for buttons affecting input and button union
568            $submit_button_styles .= sprintf( 'margin-left: %dpx;', $button_spacing );
569        }
570    }
571
572    if ( has_attribute( $attributes, 'borderColor' ) ) {
573        $style                 = sprintf( 'border-color: %s;', get_attribute( $attributes, 'borderColor', '' ) );
574        $submit_button_styles .= $style;
575        $email_field_styles   .= $style;
576    }
577
578    $style                 = sprintf( 'border-radius: %dpx;', get_attribute( $attributes, 'borderRadius', DEFAULT_BORDER_RADIUS_VALUE ) );
579    $submit_button_styles .= $style;
580    $email_field_styles   .= $style;
581
582    $style                 = sprintf( 'border-width: %dpx;', get_attribute( $attributes, 'borderWeight', DEFAULT_BORDER_WEIGHT_VALUE ) );
583    $submit_button_styles .= $style;
584    $email_field_styles   .= $style;
585
586    if ( has_attribute( $attributes, 'customBorderColor' ) ) {
587        $style = sprintf( 'border-color: %s; border-style: solid;', get_attribute( $attributes, 'customBorderColor' ) );
588
589        $submit_button_styles .= $style;
590        $email_field_styles   .= $style;
591    }
592
593    if ( ! Request::is_frontend() ) {
594        $background_color_style = get_attribute_color( 'buttonBackgroundColor', $attributes, '#113AF5' /* default lettre theme color */ );
595        $text_color_style       = get_attribute_color( 'textColor', $attributes, '#FFFFFF' );
596        $submit_button_styles  .= sprintf( ' background-color: %s; color: %s;', $background_color_style, $text_color_style );
597    }
598
599    return array(
600        'email_field'           => $email_field_styles,
601        'submit_button'         => $submit_button_styles,
602        'submit_button_wrapper' => $submit_button_wrapper_styles,
603    );
604}
605
606/**
607 * Retrieve the resolved color for a given attribute.
608 *
609 * @param string $attribute_name The name of the attribute to resolve.
610 * @param array  $attributes     An array of all attributes.
611 * @param string $default_color  A fallback color in case no color can be resolved.
612 *
613 * @return string Returns the resolved color or the default color if no color is found.
614 */
615function get_attribute_color( $attribute_name, $attributes, $default_color ) {
616    if ( has_attribute( $attributes, $attribute_name ) ) {
617        $color_slug     = get_attribute( $attributes, $attribute_name );
618        $resolved_color = get_color_from_slug( $color_slug );
619
620        if ( $resolved_color ) {
621            return $resolved_color;
622        }
623    }
624
625    return get_global_style_color( $attribute_name, $default_color );
626}
627
628/**
629 * Retrieve the global style color based on a provided style key.
630 *
631 * @param string $style_key     The key for the desired style.
632 * @param string $default_color A fallback color in case the global style is not set.
633 *
634 * @return string Returns the color defined in global styles or the default color if not defined.
635 */
636function get_global_style_color( $style_key, $default_color ) {
637    $global_styles = wp_get_global_styles(
638        array( 'color' ),
639        array(
640            'block_name' => 'core/button',
641            'transforms' => array( 'resolve-variables' ),
642        )
643    );
644
645    if ( isset( $global_styles[ $style_key ] ) ) {
646        return $global_styles[ $style_key ];
647    }
648
649    return $default_color;
650}
651
652/**
653 * Convert a color slug into its corresponding color value.
654 *
655 * @param string $slug The slug representation of the color.
656 *
657 * @return string|null Returns the color value if found, or null otherwise.
658 */
659function get_color_from_slug( $slug ) {
660    $color_palettes = wp_get_global_settings( array( 'color', 'palette' ) );
661
662    if ( ! is_array( $color_palettes ) ) {
663        return null;
664    }
665
666    foreach ( $color_palettes as $palette ) {
667        if ( is_array( $palette ) ) {
668            foreach ( $palette as $color ) {
669                if ( isset( $color['slug'] ) && $color['slug'] === $slug && isset( $color['color'] ) ) {
670                    return $color['color'];
671                }
672            }
673        }
674    }
675
676    return null;
677}
678
679/**
680 * Is the Jetpack_Memberships class loaded.
681 */
682function is_jetpack_memberships_loaded(): bool {
683    return class_exists( '\Jetpack_Memberships' );
684}
685
686/**
687 * Subscriptions block render callback.
688 *
689 * @param array $attributes Array containing the block attributes.
690 *
691 * @return string
692 */
693function render_block( $attributes ) {
694    // If the Subscriptions module is not active, don't render the block.
695    if ( ! ( new Modules() )->is_active( 'subscriptions' ) ) {
696        return '';
697    }
698
699    if ( is_jetpack_memberships_loaded() ) {
700        // We only want the sites that have newsletter feature enabled to be graced by this JavaScript.
701        Jetpack_Gutenberg::load_assets_as_required( __DIR__ );
702    } else {
703        Jetpack_Gutenberg::load_styles_as_required( FEATURE_NAME );
704    }
705
706    if ( ! class_exists( 'Jetpack_Subscriptions_Widget' ) ) {
707        return '';
708    }
709
710    // Prefill the email field with the current user's email if they are logged in via Memberships premium content token
711    $subscribe_email = Jetpack_Memberships::get_current_user_email();
712
713    // If no email, then prefill the email field with the current user's email if they are logged in
714    if ( empty( $subscribe_email ) ) {
715        $current_user = wp_get_current_user();
716        if ( ! empty( $current_user->user_email ) ) {
717            $subscribe_email = $current_user->user_email;
718        }
719    }
720
721    // The block is using the Jetpack_Subscriptions_Widget backend, hence the need to increase the instance count.
722    ++Jetpack_Subscriptions_Widget::$instance_count;
723
724    $classes = get_element_class_names_from_attributes( $attributes );
725    $styles  = get_element_styles_from_attributes( $attributes );
726
727    // The default value was previously "true" in block.json. We don't want to rely setting "default" in block.json to falsy,
728    // because it would change the setting for previously saved blocks. Block editor doesn't store default values in attributes at all.
729    // Hence users without this set will still get social counts included in the subscriber counter.
730    // Lowering the subscriber count on their behalf with code change would be controversial.
731    // We want to disencourage including social count as it's misleading.
732    $include_social_followers = isset( $attributes['includeSocialFollowers'] ) ? (bool) get_attribute( $attributes, 'includeSocialFollowers' ) : true;
733
734    $data = array(
735        'widget_id'                         => Jetpack_Subscriptions_Widget::$instance_count,
736        'subscribe_email'                   => $subscribe_email,
737        'is_paid_subscriber'                => get_attribute( $attributes, 'isPaidSubscriber', false ),
738        'wrapper_attributes'                => get_block_wrapper_attributes(
739            array(
740                'class' => $classes['block_wrapper'],
741            )
742        ),
743        'subscribe_placeholder'             => get_attribute( $attributes, 'subscribePlaceholder', __( 'Type your email…', 'jetpack' ) ),
744        'submit_button_text'                => get_attribute( $attributes, 'submitButtonText', __( 'Subscribe', 'jetpack' ) ),
745        'submit_button_text_subscribed'     => get_attribute( $attributes, 'submitButtonTextSubscribed', __( 'Subscribed', 'jetpack' ) ),
746        'submit_button_text_upgrade'        => get_attribute( $attributes, 'submitButtonTextUpgrade', __( 'Upgrade subscription', 'jetpack' ) ),
747        'success_message'                   => get_attribute(
748            $attributes,
749            'successMessage',
750            esc_html__( "Success! An email was just sent to confirm your subscription. Please find the email now and click 'Confirm' to start subscribing.", 'jetpack' )
751        ),
752        'show_subscribers_total'            => (bool) get_attribute( $attributes, 'showSubscribersTotal' ),
753        'subscribers_total'                 => get_attribute( $attributes, 'showSubscribersTotal' ) ? get_subscriber_count( $include_social_followers ) : 0,
754        'referer'                           => esc_url_raw(
755            ( is_ssl() ? 'https' : 'http' ) . '://' . ( isset( $_SERVER['HTTP_HOST'] ) ? wp_unslash( $_SERVER['HTTP_HOST'] ) : '' ) .
756            ( isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '' )
757        ),
758        'source'                            => 'subscribe-block',
759        'app_source'                        => get_attribute( $attributes, 'appSource', null ),
760        'class_name'                        => get_attribute( $attributes, 'className' ),
761        'selected_newsletter_categories'    => get_attribute( $attributes, 'selectedNewsletterCategoryIds', array() ),
762        'preselected_newsletter_categories' => get_attribute( $attributes, 'preselectNewsletterCategories', false ),
763    );
764
765    // Only render the email version in non-frontend contexts.
766    if ( is_feed() || wp_is_xml_request() ||
767        ( defined( 'REST_REQUEST' ) && REST_REQUEST && ! wp_is_json_request() ) ||
768        ( defined( 'REST_API_REQUEST' ) && REST_API_REQUEST ) ||
769        ( defined( 'WP_CLI' ) && WP_CLI ) ||
770        wp_is_jsonp_request() ) {
771        return render_for_email( $data, $styles );
772    }
773
774    return render_for_website( $data, $classes, $styles );
775}
776
777/**
778 *  Get the post access level for the current post. Defaults to 'everybody' if the query is not for a single post
779 *
780 * @return string the actual post access level (see projects/plugins/jetpack/extensions/blocks/subscriptions/constants.js for the values).
781 */
782function get_post_access_level_for_current_post() {
783    if ( ! is_singular() ) {
784        // There is no "actual" current post.
785        return Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_EVERYBODY;
786    }
787
788    return Jetpack_Memberships::get_post_access_level();
789}
790
791/**
792 * Renders the subscriptions block at the site.
793 *
794 * @param array $data    Array containing block view data.
795 * @param array $classes Array containing the classes for different block elements.
796 * @param array $styles  Array containing the styles for different block elements.
797 *
798 * @return string
799 */
800function render_for_website( $data, $classes, $styles ) {
801    $lang                 = get_locale();
802    $blog_id              = \Jetpack_Options::get_option( 'id' );
803    $widget_id_suffix     = Jetpack_Subscriptions_Widget::$instance_count > 1 ? '-' . Jetpack_Subscriptions_Widget::$instance_count : '';
804    $form_id              = 'subscribe-blog' . $widget_id_suffix;
805    $form_url             = 'https://wordpress.com/email-subscriptions';
806    $post_access_level    = get_post_access_level_for_current_post();
807    $is_button_only_style = ! empty( $data['class_name'] ) ? is_button_only_style( $data['class_name'] ) : false;
808
809    // Post ID is used for pulling post-specific paid status, and returning to the right post after confirming subscription
810    $post_id = null;
811    if ( in_the_loop() ) {
812        $post_id = get_the_ID();
813    } elseif ( is_singular( 'post' ) || is_page() ) {
814        $post_id = get_queried_object_id();
815    } else {
816        $post_id = get_option( 'page_on_front' );
817    }
818
819    $subscribe_field_id    = apply_filters( 'subscribe_field_id', 'subscribe-field' . $widget_id_suffix, $data['widget_id'] );
820    $tier_id               = get_post_meta( $post_id, META_NAME_FOR_POST_TIER_ID_SETTINGS, true );
821    $is_subscribed         = Jetpack_Memberships::is_current_user_subscribed();
822    $button_text           = get_submit_button_text( $data );
823    $show_subscriber_count = $data['show_subscribers_total'] && $data['subscribers_total'] && ! $is_subscribed;
824
825    ob_start();
826
827    Jetpack_Subscriptions_Widget::render_widget_status_messages(
828        array(
829            'success_message' => $data['success_message'],
830        )
831    );
832    ?>
833    <div <?php echo wp_kses_data( $data['wrapper_attributes'] ); ?>>
834        <div class="wp-block-jetpack-subscriptions__container<?php echo ! $is_subscribed ? ' is-not-subscriber' : ''; ?>">
835            <?php if ( is_top_subscription() ) : ?>
836                <p id="subscribe-submit" class="is-link"
837                    <?php if ( ! empty( $styles['submit_button_wrapper'] ) ) : ?>
838                        style="<?php echo esc_attr( $styles['submit_button_wrapper'] ); ?>"
839                    <?php endif; ?>
840                >
841                        <a
842                            href="<?php echo esc_url( 'https://wordpress.com/reader/site/subscription/' . $blog_id ); ?>"
843                            <?php if ( ! empty( $classes['submit_button'] ) ) : ?>
844                                class="<?php echo esc_attr( $classes['submit_button'] ); ?>"
845                            <?php endif; ?>
846                            <?php if ( ! empty( $styles['submit_button'] ) ) : ?>
847                                style="<?php echo esc_attr( $styles['submit_button'] ); ?>"
848                            <?php endif; ?>
849                        >
850                            <?php echo sanitize_submit_text( $button_text ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
851                        </a>
852                </p>
853            <?php else : ?>
854                <form
855                    action="<?php echo esc_url( $form_url ); ?>"
856                    method="post"
857                    accept-charset="utf-8"
858                    data-blog="<?php echo esc_attr( $blog_id ); ?>"
859                    data-post_access_level="<?php echo esc_attr( $post_access_level ); ?>"
860                    data-subscriber_email="<?php echo esc_attr( $data['subscribe_email'] ); ?>"
861                    id="<?php echo esc_attr( $form_id ); ?>"
862                >
863                    <div class="wp-block-jetpack-subscriptions__form-elements">
864                        <?php if ( ! $is_subscribed && ! $is_button_only_style ) : ?>
865                        <p id="subscribe-email">
866                            <label
867                                id="<?php echo esc_attr( $subscribe_field_id . '-label' ); ?>"
868                                for="<?php echo esc_attr( $subscribe_field_id ); ?>"
869                                class="screen-reader-text"
870                            >
871                                <?php echo esc_html( $data['subscribe_placeholder'] ); ?>
872                            </label>
873                            <?php
874                            printf(
875                                '<input
876                                    aria-required="true"
877                                    type="email"
878                                    name="email"
879                                    autocomplete="email"
880                                    %1$s
881                                    style="%2$s"
882                                    placeholder="%3$s"
883                                    value="%4$s"
884                                    id="%5$s"
885                                    %6$s
886                                />',
887                                ( ! empty( $classes['email_field'] )
888                                    ? 'class="' . esc_attr( $classes['email_field'] ) . '"'
889                                    : ''
890                                ),
891                                ( ! empty( $styles['email_field'] )
892                                    ? esc_attr( $styles['email_field'] )
893                                    : 'width: 95%; padding: 1px 10px'
894                                ),
895                                esc_attr( $data['subscribe_placeholder'] ),
896                                esc_attr( $data['subscribe_email'] ),
897                                esc_attr( $subscribe_field_id ),
898                                ( ! empty( $data['subscribe_email'] )
899                                    ? 'disabled title="' . esc_attr__( "You're logged in with this email", 'jetpack' ) . '"'
900                                    : ''
901                                )
902                            );
903                            ?>
904                        </p>
905                        <?php endif; ?>
906                        <p id="subscribe-submit"
907                            <?php if ( ! empty( $styles['submit_button_wrapper'] ) ) : ?>
908                                style="<?php echo esc_attr( $styles['submit_button_wrapper'] ); ?>"
909                            <?php endif; ?>
910                        >
911                            <input type="hidden" name="action" value="subscribe"/>
912                            <input type="hidden" name="blog_id" value="<?php echo (int) $blog_id; ?>"/>
913                            <input type="hidden" name="source" value="<?php echo esc_url( $data['referer'] ); ?>"/>
914                            <input type="hidden" name="sub-type" value="<?php echo esc_attr( $data['source'] ); ?>"/>
915                            <input type="hidden" name="app_source" value="<?php echo esc_attr( $data['app_source'] ); ?>"/>
916                            <input type="hidden" name="redirect_fragment" value="<?php echo esc_attr( $form_id ); ?>"/>
917                            <input type="hidden" name="lang" value="<?php echo esc_attr( $lang ); ?>"/>
918                            <?php
919                            wp_nonce_field( 'blogsub_subscribe_' . $blog_id );
920
921                            if ( ! empty( $post_id ) ) {
922                                echo '<input type="hidden" name="post_id" value="' . esc_attr( $post_id ) . '"/>';
923                            }
924
925                            if ( ! empty( $tier_id ) ) {
926                                echo '<input type="hidden" name="tier_id" value="' . esc_attr( $tier_id ) . '"/>';
927                            }
928
929                            if ( $data['preselected_newsletter_categories'] && ! empty( $data['selected_newsletter_categories'] ) ) {
930                                echo '<input type="hidden" name="selected_newsletter_categories" value="' . esc_attr( implode( ',', $data['selected_newsletter_categories'] ) ) . '"/>';
931                            }
932                            ?>
933                            <button type="submit"
934                                <?php if ( ! empty( $classes['submit_button'] ) ) : ?>
935                                    class="<?php echo esc_attr( $classes['submit_button'] ); ?>"
936                                <?php endif; ?>
937                                <?php if ( ! empty( $styles['submit_button'] ) ) : ?>
938                                    style="<?php echo esc_attr( $styles['submit_button'] ); ?>"
939                                <?php endif; ?>
940                                name="jetpack_subscriptions_widget"
941                            >
942                                <?php echo sanitize_submit_text( $button_text ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
943                            </button>
944                        </p>
945                    </div>
946                </form>
947            <?php endif; ?>
948            <?php if ( $show_subscriber_count ) : ?>
949                <div class="wp-block-jetpack-subscriptions__subscount">
950                    <?php echo esc_html( Jetpack_Memberships::get_join_others_text( $data['subscribers_total'] ) ); ?>
951                </div>
952            <?php endif; ?>
953        </div>
954    </div>
955    <?php
956    return ob_get_clean();
957}
958
959/**
960 * Renders the email version of the subscriptions block.
961 *
962 * @param array $data    Array containing block view data.
963 * @param array $styles  Array containing the styles for different block elements.
964 *
965 * @return string
966 */
967function render_for_email( $data, $styles ) {
968    $submit_button_wrapper_style = ! empty( $styles['submit_button_wrapper'] ) ? 'style="' . esc_attr( $styles['submit_button_wrapper'] ) . '"' : '';
969    $button_text                 = get_submit_button_text( $data );
970
971    $html = '<div ' . wp_kses_data( $data['wrapper_attributes'] ) . '>
972        <div>
973            <div>
974                <div>
975                    <p ' . $submit_button_wrapper_style . '>
976                        <a href="' . esc_url( get_post_permalink() ) . '" style="' . esc_attr( $styles['submit_button'] ) . ' text-decoration: none; white-space: nowrap; margin-left: 0">' . sanitize_submit_text( $button_text ) . '</a>
977                    </p>
978                </div>
979            </div>
980        </div>
981    </div>';
982
983    return $html;
984}
985
986/**
987 * WooCommerce Email Editor render callback for the subscriptions block.
988 *
989 * @param string $block_content The block content.
990 * @param array  $parsed_block  The parsed block data.
991 * @param object $rendering_context The email rendering context.
992 *
993 * @return string
994 */
995function render_email( $block_content, array $parsed_block, $rendering_context ) {
996    if ( ! isset( $parsed_block['attrs'] ) || ! is_array( $parsed_block['attrs'] ) || ! function_exists( '\Automattic\Jetpack\Extensions\Button\render_email' ) || ! class_exists( '\Automattic\WooCommerce\EmailEditor\Integrations\Core\Renderer\Blocks\Button' ) ) {
997        return '';
998    }
999
1000    // Map subscription block attributes to button block attributes
1001    $button_attributes = array(
1002        'text'                  => ! empty( $parsed_block['attrs']['submitButtonText'] ) ? sanitize_text_field( $parsed_block['attrs']['submitButtonText'] ) : __( 'Subscribe', 'jetpack' ),
1003        'url'                   => get_post_permalink(),
1004        'element'               => 'a',
1005        // Map background colors
1006        'backgroundColor'       => $parsed_block['attrs']['buttonBackgroundColor'] ?? null,
1007        'customBackgroundColor' => $parsed_block['attrs']['customButtonBackgroundColor'] ?? null,
1008        // Map text colors
1009        'textColor'             => $parsed_block['attrs']['textColor'] ?? null,
1010        'customTextColor'       => $parsed_block['attrs']['customTextColor'] ?? null,
1011        // Map borders
1012        'borderRadius'          => $parsed_block['attrs']['borderRadius'] ?? 0,
1013        'borderWeight'          => $parsed_block['attrs']['borderWeight'] ?? 1,
1014        'borderColor'           => $parsed_block['attrs']['borderColor'] ?? null,
1015        'customBorderColor'     => $parsed_block['attrs']['customBorderColor'] ?? null,
1016        // Map typography
1017        'fontSize'              => $parsed_block['attrs']['fontSize'] ?? null,
1018        'customFontSize'        => $parsed_block['attrs']['customFontSize'] ?? null,
1019        // Map spacing
1020        'padding'               => $parsed_block['attrs']['padding'] ?? null,
1021    );
1022
1023    // Create a mock button block structure
1024    $button_parsed_block = array(
1025        'attrs'       => $button_attributes,
1026        'email_attrs' => $parsed_block['email_attrs'] ?? array(),
1027    );
1028
1029    // Call the Jetpack button's email rendering
1030    return \Automattic\Jetpack\Extensions\Button\render_email(
1031        $block_content,
1032        $button_parsed_block,
1033        $rendering_context
1034    );
1035}
1036
1037/**
1038 * Gate access to posts
1039 *
1040 * @param string $the_content Post content.
1041 *
1042 * @return string
1043 */
1044function add_paywall( $the_content ) {
1045    require_once JETPACK__PLUGIN_DIR . 'modules/memberships/class-jetpack-memberships.php';
1046
1047    $post_access_level = Jetpack_Memberships::get_post_access_level();
1048
1049    if ( Jetpack_Memberships::user_can_view_post() ) {
1050        if ( $post_access_level !== Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_EVERYBODY ) {
1051            do_action(
1052                'earn_track_paywalled_post_view',
1053                array(
1054                    'post_id' => get_the_ID(),
1055                )
1056            );
1057        }
1058        return $the_content;
1059    }
1060
1061    $paywalled_content = get_paywall_content();
1062
1063    if ( has_block( \Automattic\Jetpack\Extensions\Paywall\BLOCK_NAME ) ) {
1064        if ( strpos( $the_content, \Automattic\Jetpack\Extensions\Paywall\BLOCK_HTML ) ) {
1065            return strstr( $the_content, \Automattic\Jetpack\Extensions\Paywall\BLOCK_HTML, true ) . $paywalled_content;
1066        }
1067        // WordPress generates excerpts by either rendering or stripping blocks before invoking the `the_content` filter.
1068        // In the context of generating an excerpt, the Paywall block specifically renders THE_EXCERPT_BLOCK.
1069        if ( strpos( $the_content, \Automattic\Jetpack\Extensions\Paywall\THE_EXCERPT_BLOCK ) ) {
1070            return strstr( $the_content, \Automattic\Jetpack\Extensions\Paywall\THE_EXCERPT_BLOCK, true );
1071        }
1072    }
1073
1074    return $paywalled_content;
1075}
1076
1077/**
1078 * Gate access to comments. We want to close comments on private sites.
1079 *
1080 * @param bool $default_comments_open Default state of the comments_open filter.
1081 * @param int  $post_id Current post id.
1082 *
1083 * @return bool
1084 */
1085function maybe_close_comments( $default_comments_open, $post_id ) {
1086    if ( ! $default_comments_open || ! $post_id ) {
1087        return $default_comments_open;
1088    }
1089
1090    require_once JETPACK__PLUGIN_DIR . 'modules/memberships/class-jetpack-memberships.php';
1091    return Jetpack_Memberships::user_can_view_post();
1092}
1093
1094/**
1095 * Gate access to existing comments
1096 *
1097 * @param string $comment The comment.
1098 *
1099 * @return string
1100 */
1101function maybe_gate_existing_comments( $comment ) {
1102    if ( empty( $comment ) ) {
1103        return $comment;
1104    }
1105
1106    require_once JETPACK__PLUGIN_DIR . 'modules/memberships/class-jetpack-memberships.php';
1107    if ( Jetpack_Memberships::user_can_view_post() ) {
1108        return $comment;
1109    }
1110    return '';
1111}
1112
1113/**
1114 * Is the Jetpack_Token_Subscription_Service class loaded
1115 *
1116 * @return bool
1117 */
1118function is_jetpack_token_subscription_service_loaded(): bool {
1119    return class_exists( 'Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service\Jetpack_Token_Subscription_Service' );
1120}
1121
1122/**
1123 * Adds support for WP Super cache and Boost cache
1124 */
1125function maybe_prevent_super_cache_caching() {
1126    // Prevents cached page to be served if the Membership cookie is present
1127    if ( is_jetpack_token_subscription_service_loaded() ) {
1128        do_action( 'wpsc_add_cookie', Jetpack_Token_Subscription_Service::JWT_AUTH_TOKEN_COOKIE_NAME );
1129    }
1130
1131    if ( is_user_auth() ) {
1132        // Do not cache the page if user is auth with Membership token
1133        if ( ! defined( 'DONOTCACHEPAGE' ) ) {
1134            define( 'DONOTCACHEPAGE', true );
1135        }
1136    }
1137}
1138
1139/**
1140 * Returns paywall content blocks
1141 *
1142 * @return string
1143 */
1144function get_paywall_content() {
1145    if ( Jetpack_Memberships::user_is_pending_subscriber() ) {
1146        return get_paywall_blocks_subscribe_pending();
1147    }
1148    if ( doing_filter( 'get_the_excerpt' ) ) {
1149        return '';
1150    }
1151    return get_paywall_blocks();
1152}
1153
1154/**
1155 * Returns the current URL.
1156 *
1157 * TODO: Copied from https://github.com/Automattic/jetpack/blob/bb885061dc3ee7a80a78a5f0116ab3fcebfddb09/projects/packages/boost-core/src/lib/class-url.php#L39
1158 * TODO: Move to a shared package
1159 *
1160 * @return string
1161 */
1162function get_current_url() {
1163    // Fallback to the site URL if we're unable to determine the URL from $_SERVER global.
1164    $current_url = site_url();
1165
1166    if ( isset( $_SERVER ) && is_array( $_SERVER ) ) {
1167        // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitization happens at the end
1168        $scheme = isset( $_SERVER['HTTPS'] ) && 'on' === $_SERVER['HTTPS'] ? 'https' : 'http';
1169        $host   = ! empty( $_SERVER['HTTP_HOST'] ) ? wp_unslash( $_SERVER['HTTP_HOST'] ) : null;
1170        $path   = ! empty( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '';
1171
1172        // Support for local plugin development and testing using ngrok.
1173        if ( ! empty( $_SERVER['HTTP_X_ORIGINAL_HOST'] ) && str_contains( $_SERVER['HTTP_X_ORIGINAL_HOST'], 'ngrok.io' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- This is validating.
1174            $host = wp_unslash( $_SERVER['HTTP_X_ORIGINAL_HOST'] );
1175        }
1176        // phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
1177
1178        if ( $host ) {
1179            $current_url = esc_url_raw( sprintf( '%s://%s%s', $scheme, $host, $path ) );
1180        }
1181    }
1182
1183    return $current_url;
1184}
1185
1186/**
1187 * Get the submit button text based on the subscription status.
1188 *
1189 * @param array $data Array containing block view data.
1190 *
1191 * @return string
1192 */
1193function get_submit_button_text( $data ) {
1194    if ( ! Jetpack_Memberships::is_current_user_subscribed() ) {
1195        return $data['submit_button_text'];
1196    }
1197    if ( ! Jetpack_Memberships::user_can_view_post() ) {
1198        return $data['submit_button_text_upgrade'];
1199    }
1200    return '✓ ' . $data['submit_button_text_subscribed'];
1201}
1202
1203/**
1204 * Returns true if there are no more tiers to upgrade to.
1205 *
1206 * @return boolean
1207 */
1208function is_top_subscription() {
1209    if ( ! Jetpack_Memberships::is_current_user_subscribed() ) {
1210        return false;
1211    }
1212    if ( ! Jetpack_Memberships::user_can_view_post() ) {
1213        return false;
1214    }
1215    return true;
1216}
1217
1218/**
1219 * Sanitize the submit button text.
1220 *
1221 * @param string $text String containing the submit button text.
1222 *
1223 * @return string
1224 */
1225function sanitize_submit_text( $text ) {
1226    return wp_kses(
1227        html_entity_decode( $text, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 ),
1228        Jetpack_Subscriptions_Widget::$allowed_html_tags_for_submit_button
1229    );
1230}
1231
1232/**
1233 * Returns paywall content blocks if user is not authenticated
1234 *
1235 * @return string
1236 */
1237function get_paywall_blocks() {
1238    $custom_paywall = apply_filters( 'jetpack_custom_paywall_blocks', false );
1239    if ( ! empty( $custom_paywall ) ) {
1240        return $custom_paywall;
1241    }
1242
1243    if ( ! Request::is_frontend() ) { // emails
1244        return get_paywall_simple();
1245    }
1246
1247    require_once JETPACK__PLUGIN_DIR . 'modules/memberships/class-jetpack-memberships.php';
1248    $is_paid_post       = is_paid_post();
1249    $is_paid_subscriber = Jetpack_Memberships::user_is_paid_subscriber();
1250
1251    $access_heading = $is_paid_subscriber
1252        ? esc_html__( 'Upgrade to continue reading', 'jetpack' )
1253        : esc_html__( 'Subscribe to continue reading', 'jetpack' );
1254
1255    $subscribe_text = $is_paid_post
1256        // translators: %s is the name of the site.
1257        ? (
1258            $is_paid_subscriber
1259                ? esc_html__( 'Upgrade to get access to the rest of this post and other exclusive content.', 'jetpack' )
1260                : esc_html__( 'Become a paid subscriber to get access to the rest of this post and other exclusive content.', 'jetpack' )
1261        )
1262        // translators: %s is the name of the site.
1263        : esc_html__( 'Subscribe to get access to the rest of this post and other subscriber-only content.', 'jetpack' );
1264
1265    $login_block = '';
1266
1267    if ( is_user_auth() ) {
1268        if ( ( new Host() )->is_wpcom_simple() ) {
1269            // We cannot use wpcom_logmein_redirect_url since it returns redirect URL when user is already logged in.
1270            $login_link           = add_query_arg(
1271                array(
1272                    'redirect_to' => rawurlencode( get_current_url() ),
1273                    'blog_id'     => get_current_blog_id(),
1274                ),
1275                'https://wordpress.com/log-in/link'
1276            );
1277            $switch_accounts_link = wp_logout_url( $login_link );
1278            $login_block          = '<!-- wp:paragraph {"align":"center","style":{"typography":{"fontSize":"14px"}}} -->
1279<p class="has-text-align-center" style="font-size:14px">
1280    <a href="' . $switch_accounts_link . '">' . __( 'Switch accounts', 'jetpack' ) . '</a>
1281</p>
1282<!-- /wp:paragraph -->';
1283        }
1284    } else {
1285        add_action( 'wp_footer', __NAMESPACE__ . '\print_silent_subscriber_check' );
1286
1287        $access_question = $is_paid_post ? esc_html__( 'Already a paid subscriber?', 'jetpack' ) : esc_html__( 'Already a subscriber?', 'jetpack' );
1288        $login_block     = '<!-- wp:group {"style":{"typography":{"fontSize":"14px"}},"layout":{"type":"flex","justifyContent":"center"}} -->
1289<div class="wp-block-group" style="font-size:14px">
1290    <!-- wp:jetpack/subscriber-login {"logInLabel":"' . $access_question . '"} /-->
1291</div>
1292<!-- /wp:group -->';
1293    }
1294
1295    $lock_svg = plugins_url( 'images/lock-paywall.svg', JETPACK__PLUGIN_FILE );
1296
1297    return '
1298<!-- wp:group {"style":{"border":{"width":"1px","radius":"4px"},"spacing":{"padding":{"top":"32px","bottom":"32px","left":"32px","right":"32px"}}},"borderColor":"primary","className":"jetpack-subscribe-paywall","layout":{"type":"constrained","contentSize":"400px"}} -->
1299<div class="wp-block-group jetpack-subscribe-paywall has-border-color has-primary-border-color" style="border-width:1px;border-radius:4px;padding-top:32px;padding-right:32px;padding-bottom:32px;padding-left:32px">
1300<!-- wp:image {"align":"center","width":24,"height":24,"sizeSlug":"large","linkDestination":"none"} -->
1301<figure class="wp-block-image aligncenter size-large is-resized"><img src="' . $lock_svg . '" alt="" width="24" height="24"/></figure>
1302<!-- /wp:image -->
1303
1304<!-- wp:heading {"textAlign":"center","style":{"typography":{"fontStyle":"normal","fontWeight":"600","fontSize":"24px"},"layout":{"selfStretch":"fit"}}} -->
1305<h2 class="wp-block-heading has-text-align-center" style="font-size:24px;font-style:normal;font-weight:600">' . $access_heading . '</h2>
1306<!-- /wp:heading -->
1307
1308<!-- wp:paragraph {"align":"center","style":{"typography":{"fontSize":"14px"},"spacing":{"margin":{"top":"10px","bottom":"10px"}}}} -->
1309<p class="has-text-align-center" style="margin-top:10px;margin-bottom:10px;font-size:14px">' . $subscribe_text . '</p>
1310<!-- /wp:paragraph -->
1311
1312<!-- wp:jetpack/subscriptions {"borderRadius":50,"borderColor":"primary","className":"is-style-compact","isPaidSubscriber":' . ( $is_paid_subscriber ? 'true' : 'false' ) . '} /-->
1313' . $login_block . '
1314</div>
1315<!-- /wp:group -->
1316';
1317}
1318
1319/**
1320 * Returns true if user is auth for subscriptions check, otherwise returns false.
1321 *
1322 * @return bool
1323 */
1324function is_user_auth(): bool {
1325    if ( ( new Host() )->is_wpcom_simple() && is_user_logged_in() ) {
1326        return true;
1327    }
1328    if ( current_user_can( 'manage_options' ) ) {
1329        return true;
1330    }
1331
1332    if ( is_jetpack_token_subscription_service_loaded() ) {
1333        if ( Jetpack_Token_Subscription_Service::has_token_from_cookie() ) {
1334            return true;
1335        }
1336    }
1337    return false;
1338}
1339
1340/**
1341 * Prints a script that checks once a day whether a paywalled visitor already subscribes through WordPress.com.
1342 *
1343 * A custom domain can't see the WordPress.com login, so the script sends the visitor there and back (NL-267).
1344 *
1345 * @since 16.5
1346 */
1347function print_silent_subscriber_check() {
1348    // The visitor is on the way back from a check, so never send them round again.
1349    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only checks that the marker is present.
1350    if ( isset( $_GET['jp_sub_check'] ) ) {
1351        return;
1352    }
1353
1354    /**
1355     * Filters whether the paywall checks for a WordPress.com subscriber without a click.
1356     *
1357     * @since 16.5
1358     *
1359     * @param bool $enabled Whether to run the check. Default true.
1360     */
1361    if ( ! apply_filters( 'jetpack_subscriptions_silent_subscriber_check', true ) ) {
1362        return;
1363    }
1364
1365    $home = wp_parse_url( home_url( '/' ) );
1366    // WordPress.com only issues a silent token over https.
1367    if ( 'https' !== ( $home['scheme'] ?? '' ) ) {
1368        return;
1369    }
1370    $home_host = $home['host'] ?? '';
1371
1372    if ( ( new Host() )->is_wpcom_simple() ) {
1373        // A *.wordpress.com address already shares the WordPress.com login.
1374        if ( str_ends_with( $home_host, '.wordpress.com' ) ) {
1375            return;
1376        }
1377        $site_id   = get_current_blog_id();
1378        $auth_base = '';
1379    } else {
1380        $site_id = (int) \Jetpack_Options::get_option( 'id' );
1381        $status  = new Status();
1382        // A staging copy or a site with a mismatched address would send visitors to the wrong host.
1383        if ( ! $site_id || $status->is_offline_mode() || $status->in_safe_mode() || Status::is_development_site() ) {
1384            return;
1385        }
1386        $auth_base = add_query_arg( 'silent', '1', rest_url( 'jetpack/v4/subscribers/auth' ) );
1387    }
1388
1389    $config = array(
1390        'host'        => $home_host,
1391        'tokenCookie' => Abstract_Token_Subscription_Service::JWT_AUTH_TOKEN_COOKIE_NAME,
1392        'pauseCookie' => Abstract_Token_Subscription_Service::SILENT_SUBSCRIBER_CHECK_COOKIE,
1393        'jwtBase'     => add_query_arg(
1394            array(
1395                'site_id' => $site_id,
1396                'silent'  => '1',
1397            ),
1398            Abstract_Token_Subscription_Service::REST_URL_ORIGIN . 'memberships/jwt/'
1399        ),
1400        'authBase'    => $auth_base,
1401    );
1402
1403    $script = <<<'JS'
1404( function ( c ) {
1405    try {
1406        if ( window.top !== window.self || document.prerendering || navigator.webdriver || location.hostname !== c.host ) {
1407            return;
1408        }
1409        if ( /bot|crawl|spider|slurp|facebookexternalhit|lighthouse|preview/i.test( navigator.userAgent ) ) {
1410            return;
1411        }
1412        var hasCookie = function ( name ) {
1413            return new RegExp( '(^|; )' + name + '=' ).test( document.cookie );
1414        };
1415        if ( hasCookie( c.tokenCookie ) || hasCookie( c.pauseCookie ) ) {
1416            return;
1417        }
1418        document.cookie = c.pauseCookie + '=1; max-age=86400; path=/; SameSite=Lax; secure';
1419        if ( ! hasCookie( c.pauseCookie ) ) {
1420            return;
1421        }
1422        var back = new URL( location.href );
1423        back.searchParams.set( 'jp_sub_check', '1' );
1424        var url = back.toString();
1425        if ( c.authBase ) {
1426            url = c.authBase + '&redirect_url=' + encodeURIComponent( url );
1427        }
1428        location.replace( c.jwtBase + '&redirect_url=' + encodeURIComponent( url ) );
1429    } catch ( e ) {}
1430} )( %s );
1431JS;
1432
1433    wp_print_inline_script_tag( sprintf( $script, wp_json_encode( $config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_UNESCAPED_SLASHES ) ) );
1434}
1435
1436/**
1437 * Removes the silent check's marker and token from the address bar after the visitor comes back.
1438 *
1439 * @since 16.5
1440 */
1441function print_silent_subscriber_check_cleanup() {
1442    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only checks that the marker is present.
1443    if ( ! isset( $_GET['jp_sub_check'] ) ) {
1444        return;
1445    }
1446
1447    $script = <<<'JS'
1448( function () {
1449    try {
1450        var u = new URL( location.href );
1451        u.searchParams.delete( 'jp_sub_check' );
1452        u.searchParams.delete( 'token' );
1453        history.replaceState( history.state, '', u.toString() );
1454    } catch ( e ) {}
1455} )();
1456JS;
1457
1458    wp_print_inline_script_tag( $script );
1459}
1460
1461/**
1462 * Returns `true` if the post is a paid post.
1463 */
1464function is_paid_post(): bool {
1465    require_once JETPACK__PLUGIN_DIR . 'modules/memberships/class-jetpack-memberships.php';
1466
1467    // Make sure Stripe is connected and the post is marked for paid subscribers.
1468    if ( Jetpack_Memberships::has_connected_account() && is_jetpack_token_subscription_service_loaded() ) {
1469        return Jetpack_Memberships::get_post_access_level() === Jetpack_Token_Subscription_Service::POST_ACCESS_LEVEL_PAID_SUBSCRIBERS;
1470    }
1471
1472    return false;
1473}
1474
1475/**
1476 * Returns true if the post is a subscribers post.
1477 */
1478function is_subscribers_post(): bool {
1479    require_once JETPACK__PLUGIN_DIR . 'modules/memberships/class-jetpack-memberships.php';
1480
1481    // Make sure Stripe is connected and the post is marked for paid subscribers.
1482    if ( Jetpack_Memberships::has_connected_account() && is_jetpack_token_subscription_service_loaded() ) {
1483        return Jetpack_Memberships::get_post_access_level() === Jetpack_Token_Subscription_Service::POST_ACCESS_LEVEL_SUBSCRIBERS;
1484    }
1485
1486    return false;
1487}
1488
1489/**
1490 * Returns paywall content blocks when email confirmation is pending
1491 *
1492 * @return string
1493 */
1494function get_paywall_blocks_subscribe_pending() {
1495    $subscribe_email = Jetpack_Memberships::get_current_user_email();
1496
1497    /** This filter is documented in \Automattic\Jetpack\Forms\ContactForm\Contact_Form */
1498    if ( is_wpcom() || false !== apply_filters( 'jetpack_auto_fill_logged_in_user', false ) ) {
1499        $current_user = wp_get_current_user();
1500        if ( ! empty( $current_user->user_email ) ) {
1501            $subscribe_email = $current_user->user_email;
1502        }
1503    }
1504
1505    $access_heading = esc_html__( 'Confirm your subscription to continue reading', 'jetpack' );
1506
1507    /* translators: %s: email address */
1508    $subscribe_text = sprintf( esc_html__( 'Head to your inbox and confirm your email address %s.', 'jetpack' ), $subscribe_email );
1509
1510    $lock_svg = plugins_url( 'images/lock-paywall.svg', JETPACK__PLUGIN_FILE );
1511
1512    return '
1513<!-- wp:group {"style":{"border":{"width":"1px","radius":"4px"},"spacing":{"padding":{"top":"32px","bottom":"32px","left":"32px","right":"32px"}}},"borderColor":"primary","className":"jetpack-subscribe-paywall","layout":{"type":"constrained","contentSize":"400px"}} -->
1514<div class="wp-block-group jetpack-subscribe-paywall has-border-color has-primary-border-color" style="border-width:1px;border-radius:4px;padding-top:32px;padding-right:32px;padding-bottom:32px;padding-left:32px">
1515<!-- wp:image {"align":"center","width":24,"height":24,"sizeSlug":"large","linkDestination":"none"} -->
1516<figure class="wp-block-image aligncenter size-large is-resized"><img src="' . $lock_svg . '" alt="" width="24" height="24"/></figure>
1517<!-- /wp:image -->
1518
1519<!-- wp:heading {"textAlign":"center","style":{"typography":{"fontStyle":"normal","fontWeight":"600","fontSize":"24px", "maxWidth":"initial"},"layout":{"selfStretch":"fit"}}} -->
1520<h2 class="wp-block-heading has-text-align-center" style="font-size:24px;font-style:normal;font-weight:600;max-width:initial">' . $access_heading . '</h2>
1521<!-- /wp:heading -->
1522
1523<!-- wp:paragraph {"align":"center","style":{"typography":{"fontSize":"14px"},"spacing":{"margin":{"top":"10px","bottom":"10px"}}}} -->
1524<p class="has-text-align-center" style="margin-top:10px;margin-bottom:10px;font-size:14px">' . $subscribe_text . '</p>
1525<!-- /wp:paragraph -->
1526</div>
1527<!-- /wp:group -->
1528';
1529}
1530
1531/**
1532 * Return content for non frontend views like Reader, emails.
1533 */
1534function get_paywall_simple(): string {
1535    $is_paid_post        = is_paid_post();
1536    $is_subscribers_post = is_subscribers_post();
1537    $is_subscriber       = is_jetpack_memberships_loaded() && Jetpack_Memberships::is_current_user_subscribed();
1538    $paywall_heading     = esc_html__( 'Subscribe to keep reading', 'jetpack' );
1539
1540    if ( $is_subscribers_post && ! $is_subscriber ) {
1541        $paywall_description = esc_html__( "It's a subscribers only post. Subscribe to get access to the rest of this post and other subscriber-only content.", 'jetpack' );
1542        $paywall_action_btn  = esc_html__( 'Subscribe', 'jetpack' );
1543    } elseif ( $is_paid_post && $is_subscriber ) {
1544        $paywall_description = esc_html__( "You're currently a free subscriber. Upgrade your subscription to get access to the rest of this post and other paid-subscriber only content.", 'jetpack' );
1545        $paywall_action_btn  = esc_html__( 'Upgrade subscription', 'jetpack' );
1546    } else {
1547        // - For paid post when the user is not a subscriber.
1548        // - Default for all other cases.
1549        $paywall_description = esc_html__( 'Become a paid subscriber to get access to the rest of this post and other exclusive content.', 'jetpack' );
1550        $paywall_action_btn  = esc_html__( 'Subscribe', 'jetpack' );
1551    }
1552
1553    return '
1554<!-- wp:columns -->
1555<div class="wp-block-columns jetpack-paywall-simple" style="display: inline-block; width: 90%">
1556    <!-- wp:column -->
1557    <div class="wp-block-column" style="background-color: #F6F7F7; padding: 32px; 24px;">
1558        <!-- wp:heading -->
1559        <h2 class="has-text-align-center" style="margin: 0 0 12px; font-weight: 600;">' . $paywall_heading . '</h2>
1560        <!-- /wp:heading -->
1561        <!-- wp:paragraph -->
1562        <p class="has-text-align-center"
1563           style="text-align: center;
1564                  color: #50575E;
1565                  font-weight: 400;
1566                  font-size: 16px;
1567                  font-family: \'SF Pro Text\', sans-serif;
1568                  line-height: 28.8px;">
1569        ' . $paywall_description . '
1570        </p>
1571        <!-- /wp:paragraph -->
1572        <!-- wp:buttons -->
1573        <div class="wp-block-buttons" style="text-align: center;">
1574            <!-- wp:button -->
1575            <div class="wp-block-button" style="display: inline-block; margin: 10px 0; border-style: none; padding: 0;">
1576                <a href="' . esc_url( get_post_permalink() ) . '" class="wp-block-button__link wp-element-button"
1577                   data-wpcom-track data-tracks-link-desc="paywall-email-click"
1578                   style="display: inline-block;
1579                          padding: 12px 15px;
1580                          background-color: #3858e9;
1581                          color: #FFFFFF;
1582                          text-decoration: none;
1583                          border-radius: 5px;
1584                          font-family: \'SF Pro Display\', sans-serif;
1585                          font-weight: 500;
1586                          font-size: 16px;
1587                          text-align: center;">' . $paywall_action_btn . '</a>
1588            </div>
1589            <!-- /wp:button -->
1590        </div>
1591        <!-- /wp:buttons -->
1592    </div>
1593    <!-- /wp:column -->
1594</div>
1595<!-- /wp:columns -->
1596';
1597}