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