Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
57.14% covered (warning)
57.14%
72 / 126
18.18% covered (danger)
18.18%
2 / 11
CRAP
n/a
0 / 0
Automattic\Jetpack\Extensions\Premium_Content\membership_checks
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
Automattic\Jetpack\Extensions\Premium_Content\required_plan_checks
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
Automattic\Jetpack\Extensions\Premium_Content\pre_render_checks
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
Automattic\Jetpack\Extensions\Premium_Content\current_user_can_edit
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
Automattic\Jetpack\Extensions\Premium_Content\maybe_renew_session_cookie
97.06% covered (success)
97.06%
33 / 34
0.00% covered (danger)
0.00%
0 / 1
11
Automattic\Jetpack\Extensions\Premium_Content\get_subscriptions_for_logged_in_user
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
Automattic\Jetpack\Extensions\Premium_Content\prewarm_premium_content_session_cookie
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
12.04
Automattic\Jetpack\Extensions\Premium_Content\current_visitor_can_access
89.47% covered (warning)
89.47%
17 / 19
0.00% covered (danger)
0.00%
0 / 1
11.14
Automattic\Jetpack\Extensions\Premium_Content\visitor_can_access_plan_ids
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Automattic\Jetpack\Extensions\Premium_Content\visitor_has_subscription_access_to_plan_ids
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
Automattic\Jetpack\Extensions\Premium_Content\check_subscription_plan_access
0.00% covered (danger)
0.00%
0 / 35
0.00% covered (danger)
0.00%
0 / 1
306
1<?php
2/**
3 * Determine access to premium content.
4 *
5 * @package Automattic\Jetpack\Extensions\Premium_Content
6 */
7
8namespace Automattic\Jetpack\Extensions\Premium_Content;
9
10use Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service\Abstract_Token_Subscription_Service;
11use Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service\WPCOM_Online_Subscription_Service;
12
13require_once __DIR__ . '/subscription-service/include.php';
14
15/**
16 * Determines if the memberships module is set up.
17 *
18 * @return bool Whether the memberships module is set up.
19 */
20function membership_checks() {
21    // If Jetpack is not yet configured, don't show anything ...
22    if ( ! class_exists( '\Jetpack_Memberships' ) ) {
23        return false;
24    }
25    // if stripe not connected don't show anything...
26    if ( ! \Jetpack_Memberships::has_connected_account() ) {
27        return false;
28    }
29    return true;
30}
31
32/**
33 * Determines if the site has a plan that supports the
34 * Premium Content block.
35 *
36 * @return bool
37 */
38function required_plan_checks() {
39    $availability = \Jetpack_Gutenberg::get_cached_availability();
40    $slug         = 'premium-content/container';
41    return ( isset( $availability[ $slug ] ) && $availability[ $slug ]['available'] );
42}
43
44/**
45 * Determines if the block should be rendered. Returns true
46 * if the block passes all required checks, or if the user is
47 * an editor.
48 *
49 * @return bool Whether the block should be rendered.
50 */
51function pre_render_checks() {
52    return ( current_user_can_edit() || membership_checks() );
53}
54
55/**
56 * Determines whether the current user can edit.
57 *
58 * @return bool Whether the user can edit.
59 */
60function current_user_can_edit() {
61    if ( is_rendering_for_activitypub() ) {
62        return false;
63    }
64
65    $user = wp_get_current_user();
66
67    return 0 !== $user->ID && current_user_can( 'edit_post', get_the_ID() );
68}
69
70/**
71 * Mint and persist a fresh premium-content session cookie for the current visitor.
72 *
73 * When the WPCOM Memberships filter returns authoritative subscriptions for a logged-in
74 * visitor but no JWT cookie is present (e.g. the previous one expired or was cleared),
75 * we wrap those subscriptions in a JWT signed with the site's Jetpack blog token and
76 * persist it as the standard `wp-jp-premium-content-session` cookie. Subsequent requests
77 * within the cookie TTL take the fast cached path instead of the WPCOM round-trip.
78 *
79 * Returns the minted JWT so callers can act on it; returns null when no token should be
80 * minted because there are no subscriptions, a valid cookie already exists, or the
81 * signing key is unavailable. The cookie itself is set on a best-effort basis: if headers
82 * have already been sent, the token is still returned so the caller can decide what to do.
83 *
84 * @param object $paywall                   Subscription service (provides the signing key).
85 * @param int    $user_id                   User id the subscriptions belong to (WPCOM id when available, otherwise local).
86 * @param array  $abbreviated_subscriptions Subscriptions after `abbreviate_subscriptions()`.
87 * @return string|null The encoded JWT, or null when no cookie was minted.
88 */
89function maybe_renew_session_cookie( $paywall, $user_id, $abbreviated_subscriptions ) {
90    if ( empty( $abbreviated_subscriptions ) ) {
91        return null;
92    }
93    if ( Abstract_Token_Subscription_Service::has_token_from_cookie() ) {
94        $session_cookie_name = Abstract_Token_Subscription_Service::JWT_AUTH_TOKEN_COOKIE_NAME;
95        $existing_payload    = null;
96        if ( isset( $_COOKIE[ $session_cookie_name ] ) ) {
97            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
98            $existing_payload = $paywall->decode_token( $_COOKIE[ $session_cookie_name ] );
99        }
100        if ( ! empty( $existing_payload ) ) {
101            return null;
102        }
103    }
104
105    $key = $paywall->get_key();
106    if ( ! $key ) {
107        return null;
108    }
109
110    $payload_subscriptions = array();
111    foreach ( $abbreviated_subscriptions as $pid => $sub ) {
112        $sub                           = (array) $sub;
113        $payload_subscriptions[ $pid ] = array(
114            'status'     => 'active',
115            'end_date'   => $sub['end_date'] ?? gmdate( 'Y-m-d H:i:s', time() + MONTH_IN_SECONDS ),
116            'product_id' => (int) $pid,
117        );
118        if ( ! empty( $sub['is_comp'] ) ) {
119            $payload_subscriptions[ $pid ]['is_comp'] = true;
120        }
121    }
122
123    $token = JWT::encode(
124        array(
125            'user_id'       => $user_id,
126            'blog_sub'      => 'active',
127            'subscriptions' => $payload_subscriptions,
128        ),
129        $key
130    );
131
132    if ( ! ( defined( 'TESTING_IN_JETPACK' ) && TESTING_IN_JETPACK ) && ! headers_sent() ) {
133        // phpcs:ignore Jetpack.Functions.SetCookie.FoundNonHTTPOnlyFalse
134        setcookie( Abstract_Token_Subscription_Service::JWT_AUTH_TOKEN_COOKIE_NAME, $token, strtotime( '+1 month' ), '/', '', is_ssl(), false );
135    }
136
137    // Reflect the cookie in the current request so the render path (and any later code in
138    // this request) reads the freshly minted token instead of re-querying the filter.
139    $_COOKIE[ Abstract_Token_Subscription_Service::JWT_AUTH_TOKEN_COOKIE_NAME ] = $token;
140
141    return $token;
142}
143
144/**
145 * Resolve the current logged-in visitor's subscriptions from the authoritative
146 * WordPress.com Memberships filter.
147 *
148 * Translates the local user id to the WordPress.com user id (via the `wpcom_user_id`
149 * user_meta populated by Jetpack SSO) and queries the filter with the paywall's
150 * WordPress.com blog id (not get_current_blog_id(), which is the independent local id
151 * on Atomic/WoA). Shared by the access decision and the cookie self-heal.
152 *
153 * @param object $paywall Subscription service (provides the WordPress.com blog id).
154 * @return array{0:int,1:array,2:array} [ user_id (WPCOM id when available, otherwise local), raw_subscriptions, abbreviated_subscriptions ].
155 */
156function get_subscriptions_for_logged_in_user( $paywall ) {
157    $local_user_id = wp_get_current_user()->ID;
158    $wpcom_user_id = (int) get_user_meta( $local_user_id, 'wpcom_user_id', true );
159    $user_id       = $wpcom_user_id > 0 ? $wpcom_user_id : $local_user_id;
160    $site_id       = $paywall->get_site_id();
161
162    /**
163     * Filter the subscriptions attached to a specific user on a given site.
164     *
165     * @since 9.4.0
166     *
167     * @param array $subscriptions Array of subscriptions.
168     * @param int   $user_id The user's ID.
169     * @param int   $site_id ID of the current site.
170     */
171    $raw_subscriptions         = apply_filters( 'earn_get_user_subscriptions_for_site_id', array(), $user_id, $site_id );
172    $abbreviated_subscriptions = WPCOM_Online_Subscription_Service::abbreviate_subscriptions( $raw_subscriptions );
173
174    return array( $user_id, $raw_subscriptions, $abbreviated_subscriptions );
175}
176
177/**
178 * Pre-warm the premium-content session cookie before output starts.
179 *
180 * `current_visitor_can_access()` runs during `the_content`, by which point headers are
181 * already sent and `setcookie()` is a no-op. This `template_redirect` callback runs earlier —
182 * after the main query resolves but before the template renders — so the self-heal cookie can
183 * actually persist for subsequent requests. It does work only on front-end page views that
184 * contain the block, for logged-in visitors who do not already have a valid cookie.
185 *
186 * @return void
187 */
188function prewarm_premium_content_session_cookie() {
189    if ( ! is_user_logged_in() ) {
190        return;
191    }
192
193    // Front-end page views only — skip admin, REST, feeds and cron.
194    if ( is_admin() || is_feed() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || ( defined( 'DOING_CRON' ) && DOING_CRON ) ) {
195        return;
196    }
197
198    // Only on singular content that actually contains the block, so we never pay the filter
199    // round-trip on unrelated pages.
200    $queried = get_queried_object();
201    if ( ! ( $queried instanceof \WP_Post ) || ! has_block( 'premium-content/container', $queried ) ) {
202        return;
203    }
204
205    // Editors/authors of this post already bypass gating in current_visitor_can_access(), so
206    // there is no cookie to pre-warm for them — skip the Memberships filter round-trip.
207    if ( current_user_can( 'edit_post', $queried->ID ) ) {
208        return;
209    }
210
211    $paywall = subscription_service();
212
213    // Already have a valid cached session? Nothing to heal — and don't query the filter.
214    $existing_payload = $paywall->decode_token( $paywall->get_and_set_token_from_request() );
215    if ( ! empty( $existing_payload ) ) {
216        return;
217    }
218
219    list( $user_id, , $abbreviated_subscriptions ) = get_subscriptions_for_logged_in_user( $paywall );
220    maybe_renew_session_cookie( $paywall, $user_id, $abbreviated_subscriptions );
221}
222
223/**
224 * Determines if the current user can view the protected content of the given block.
225 *
226 * @param array  $attributes Block attributes.
227 * @param object $block Block to check.
228 *
229 * @return bool Whether the use can view the content.
230 */
231function current_visitor_can_access( $attributes, $block ) {
232    // The ActivityPub copy is public, so a subscriber token on the request must not unlock it.
233    if ( is_rendering_for_activitypub() ) {
234        return false;
235    }
236
237    /**
238     * If the current WordPress install has as signed in user
239     * they can see the content.
240     */
241
242    if ( current_user_can_edit() ) {
243        return true;
244    }
245
246    $selected_plan_ids = array();
247
248    if ( isset( $attributes['selectedPlanIds'] ) ) {
249        $selected_plan_ids = $attributes['selectedPlanIds'];
250    } elseif ( isset( $attributes['selectedPlanId'] ) ) {
251        $selected_plan_ids = array( $attributes['selectedPlanId'] );
252    }
253
254    if ( isset( $block ) && ! empty( $block->context['premium-content/planId'] ) ) {
255        $selected_plan_ids = array( $block->context['premium-content/planId'] );
256    } elseif ( isset( $block ) && ! empty( $block->context['premium-content/planIds'] ) ) {
257        $selected_plan_ids = $block->context['premium-content/planIds'];
258    }
259
260    if ( empty( $selected_plan_ids ) ) {
261        return false;
262    }
263
264    $can_view = visitor_can_access_plan_ids( $selected_plan_ids );
265
266    if ( $can_view ) {
267        /**
268         * Fires when a visitor can view protected content on a site.
269         *
270         * @since 9.4.0
271         */
272        do_action( 'jetpack_earn_remove_cache_headers' );
273    }
274
275    return $can_view;
276}
277
278/**
279 * Check plan access for rendering, including the subscription service's editorial exception.
280 *
281 * Playback callers must use visitor_has_subscription_access_to_plan_ids() to exclude editorial access.
282 *
283 * @since 16.4
284 *
285 * @param array    $selected_plan_ids Plan ids the content is gated behind.
286 * @param int|null $post_id           Post the gated content belongs to. Defaults to the loop post, so
287 *                                    callers outside the loop must pass it.
288 *
289 * @return bool Whether the visitor can view the content.
290 */
291function visitor_can_access_plan_ids( $selected_plan_ids, $post_id = null ) {
292    return check_subscription_plan_access( $selected_plan_ids, $post_id, false );
293}
294
295/**
296 * Check the required plans without granting access for editing the embedding post.
297 *
298 * @since 16.4
299 *
300 * @param array    $selected_plan_ids Required plan IDs from the stored content.
301 * @param int|null $post_id           Post to check, or the loop post when omitted.
302 * @return bool Whether the visitor has the required subscription entitlement.
303 */
304function visitor_has_subscription_access_to_plan_ids( $selected_plan_ids, $post_id = null ) {
305    return check_subscription_plan_access( $selected_plan_ids, $post_id, true );
306}
307
308/**
309 * Evaluate subscription plans for rendering or strict playback authorization.
310 *
311 * @since 16.4
312 *
313 * @param array    $selected_plan_ids   Required subscription plan IDs.
314 * @param int|null $post_id             Post to check.
315 * @param bool     $require_entitlement Whether editorial access must be excluded.
316 * @return bool Whether access is granted.
317 */
318function check_subscription_plan_access( $selected_plan_ids, $post_id, $require_entitlement ) {
319    // Callers outside the block render can get here first; this also defines the constants the paywall reads.
320    require_once JETPACK__PLUGIN_DIR . 'modules/memberships/class-jetpack-memberships.php';
321
322    $can_view     = false;
323    $paywall      = subscription_service();
324    $access_level = Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_PAID_SUBSCRIBERS; // Only paid subscribers should be granted access to the premium content
325    $tier_ids     = \Jetpack_Memberships::get_all_newsletter_plan_ids();
326    $tier_ids     = array_intersect( $tier_ids, $selected_plan_ids );
327    if ( ! empty( $tier_ids ) ) {
328        // If the selected plan is a tier, we want to check directly if user has a higher "tier".
329        // This is to prevent situation where the user upgrades and lose access to premium-gated content
330
331        $subscriptions = array();
332
333        // Cookie/token first (fast cached path, no WPCOM round-trip). Also covers anonymous
334        // visitors arriving via a `?token=` magic link, which takes precedence over the cookie.
335        $token   = $paywall->get_and_set_token_from_request();
336        $payload = $paywall->decode_token( $token );
337        if ( ! empty( $payload ) ) {
338            $subscriptions = (array) $payload['subscriptions'];
339        }
340
341        // No valid cookie yet, but logged in: consult the authoritative WPCOM filter. This is
342        // the first-visit / expired-cookie path; the template_redirect pre-warm hook mints the
343        // cookie for subsequent requests. Keeps CM-584 fixed (expired cookie still grants access).
344        if ( empty( $subscriptions ) && is_user_logged_in() ) {
345            list( , , $subscriptions ) = get_subscriptions_for_logged_in_user( $paywall );
346        }
347
348        foreach ( $tier_ids as $tier_id ) {
349            $can_view = ! $paywall->maybe_gate_access_for_user_if_tier( $tier_id, $subscriptions );
350            if ( $can_view ) {
351                break;
352            }
353        }
354
355        // Refresh-before-deny for the tier path. If the tier check denied access but the
356        // token already references a subscription whose product_id maps to one of the
357        // requested tiers, the most likely cause is a stale end_date from a renewal —
358        // attempt a single refresh against the WordPress.com token-refresh endpoint and
359        // re-check with the fresh subscriptions. Mirrors the same gate inside
360        // visitor_can_view_content() for the non-tier path.
361        if (
362            ! $can_view
363            && method_exists( $paywall, 'token_has_matching_product' )
364            && $paywall->token_has_matching_product( $tier_ids, $subscriptions )
365        ) {
366            $fresh_payload = $paywall->refresh_token_payload();
367            if ( ! empty( $fresh_payload ) ) {
368                $subscriptions = isset( $fresh_payload['subscriptions'] ) ? (array) $fresh_payload['subscriptions'] : array();
369                foreach ( $tier_ids as $tier_id ) {
370                    $can_view = ! $paywall->maybe_gate_access_for_user_if_tier( $tier_id, $subscriptions );
371                    if ( $can_view ) {
372                        break;
373                    }
374                }
375            }
376        }
377    }
378
379    $non_tier_ids = array_diff( $selected_plan_ids, $tier_ids );
380    if ( ! $can_view ) {
381        if ( $require_entitlement ) {
382            // Older or external services without the entitlement check deny.
383            $can_view = is_callable( array( $paywall, 'visitor_has_subscription_access' ) )
384                && $paywall->visitor_has_subscription_access( $non_tier_ids, $access_level, $post_id );
385        } else {
386            // For selected plans that are not tiers, we want to check if the user has any of the selected plans.
387            // @phan-suppress-next-line PhanParamTooMany -- Concrete services accept the optional $post_id; interface omits it on purpose.
388            $can_view = $paywall->visitor_can_view_content( $non_tier_ids, $access_level, $post_id );
389        }
390    }
391
392    return $can_view;
393}