Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
70.00% covered (warning)
70.00%
217 / 310
46.67% covered (danger)
46.67%
14 / 30
CRAP
0.00% covered (danger)
0.00%
0 / 1
Abstract_Token_Subscription_Service
70.45% covered (warning)
70.45%
217 / 308
46.67% covered (danger)
46.67%
14 / 30
838.86
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 initialize
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_and_set_token_from_request
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 maybe_link_wpcom_user_id
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
6
 refresh_token_payload
81.82% covered (warning)
81.82%
9 / 11
0.00% covered (danger)
0.00%
0 / 1
4.10
 fetch_refreshed_token
96.67% covered (success)
96.67%
29 / 30
0.00% covered (danger)
0.00%
0 / 1
9
 token_has_matching_product
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 get_site_id
n/a
0 / 0
n/a
0 / 0
0
 get_token_payload
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 get_token_property
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 visitor_can_view_content
96.67% covered (success)
96.67%
29 / 30
0.00% covered (danger)
0.00%
0 / 1
11
 visitor_has_subscription_access
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_subscriber_email
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 is_current_user_subscribed
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_current_user_pending_subscriber
n/a
0 / 0
n/a
0 / 0
0
 user_has_access
84.62% covered (warning)
84.62%
11 / 13
0.00% covered (danger)
0.00%
0 / 1
11.44
 maybe_gate_access_for_user_if_post_tier
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 get_valid_plan_ids_for_tier
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
462
 find_metadata
33.33% covered (danger)
33.33%
2 / 6
0.00% covered (danger)
0.00%
0 / 1
8.74
 maybe_gate_access_for_user_if_tier
89.29% covered (warning)
89.29%
50 / 56
0.00% covered (danger)
0.00%
0 / 1
28.96
 decode_token
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 get_key
n/a
0 / 0
n/a
0 / 0
0
 access_url
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 token_from_cookie
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 has_token_from_cookie
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 set_token_cookie
57.14% covered (warning)
57.14%
4 / 7
0.00% covered (danger)
0.00%
0 / 1
6.97
 clear_token_cookie
60.00% covered (warning)
60.00%
3 / 5
0.00% covered (danger)
0.00%
0 / 1
5.02
 pause_silent_subscriber_check
60.00% covered (warning)
60.00%
3 / 5
0.00% covered (danger)
0.00%
0 / 1
5.02
 token_from_request
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 subscription_grants_access
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
4.25
 validate_subscriptions
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
6
 get_rest_api_token_url
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 abbreviate_subscriptions
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
90
1<?php
2/**
3 * A paywall that exchanges JWT tokens from WordPress.com to allow
4 * a current visitor to view content that has been deemed "Premium content".
5 *
6 * @package Automattic\Jetpack\Extensions\Premium_Content
7 */
8
9namespace Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service;
10
11use Automattic\Jetpack\Extensions\Premium_Content\JWT;
12use WP_Error;
13use WP_Post;
14use const Automattic\Jetpack\Extensions\Subscriptions\META_NAME_FOR_POST_TIER_ID_SETTINGS;
15
16if ( ! defined( 'ABSPATH' ) ) {
17    exit( 0 );
18}
19
20/**
21 * Class Abstract_Token_Subscription_Service
22 *
23 * @package Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service
24 */
25abstract class Abstract_Token_Subscription_Service implements Subscription_Service {
26
27    const JWT_AUTH_TOKEN_COOKIE_NAME                   = 'wp-jp-premium-content-session'; // wp prefix helps with skipping batcache
28    const SILENT_SUBSCRIBER_CHECK_COOKIE               = 'jp-sub-check';
29    const DECODE_EXCEPTION_FEATURE                     = 'memberships';
30    const DECODE_EXCEPTION_MESSAGE                     = 'Problem decoding provided token';
31    const REST_URL_ORIGIN                              = 'https://subscribe.wordpress.com/';
32    const BLOG_SUB_ACTIVE                              = 'active';
33    const BLOG_SUB_PENDING                             = 'pending';
34    const POST_ACCESS_LEVEL_EVERYBODY                  = 'everybody';
35    const POST_ACCESS_LEVEL_SUBSCRIBERS                = 'subscribers';
36    const POST_ACCESS_LEVEL_PAID_SUBSCRIBERS           = 'paid_subscribers';
37    const POST_ACCESS_LEVEL_PAID_SUBSCRIBERS_ALL_TIERS = 'paid_subscribers_all_tiers';
38
39    /**
40     * An optional user_id to query against (omitting this will use either the token or current user id)
41     *
42     * @var int|null
43     */
44    protected $user_id = null;
45
46    /**
47     * Whether editorial permissions satisfy subscription requirements.
48     *
49     * @var bool
50     */
51    private $allow_editor_access = true;
52
53    /**
54     * Constructor
55     *
56     * @param int|null $user_id An optional user_id to query subscriptions against. Uses token from request/cookie or logged-in user information if omitted.
57     */
58    public function __construct( $user_id = null ) {
59        $this->user_id = $user_id;
60    }
61
62    /**
63     * Initialize the token subscription service.
64     *
65     * @inheritDoc
66     */
67    public function initialize() {
68        $this->get_and_set_token_from_request();
69    }
70
71    /**
72     * Set the token from the Request to the cookie and retrieve the token.
73     *
74     * @return string|null
75     */
76    public function get_and_set_token_from_request() {
77        // URL token always has a precedence, so it can overwrite the cookie when new data available.
78        $token = $this->token_from_request();
79        if ( null !== $token ) {
80            $this->set_token_cookie( $token );
81            $this->maybe_link_wpcom_user_id( $token );
82            return $token;
83        }
84
85        return $this->token_from_cookie();
86    }
87
88    /**
89     * Self-heals the local user's wpcom_user_id meta from a freshly-verified magic-link
90     * token, so future requests can resolve this visitor's subscriptions via the
91     * authoritative filter (see get_subscriptions_for_logged_in_user() in access-check.php)
92     * without needing another magic-link round trip once the token/cookie expires.
93     *
94     * Safe because the token's user_id was just verified by WordPress.com's own session
95     * at subscribe.wordpress.com -- never read from anything stored locally. A local
96     * account's email is not proof of identity by itself (anyone with admin access could
97     * type in any email when creating a local user), so this additionally requires the
98     * local account's own email to match the token's blog_subscriber email before linking,
99     * to avoid mis-linking a local account to whichever WordPress.com session happens to
100     * be active in the browser (e.g. a shared device) when the two aren't otherwise related.
101     *
102     * @param string $token The raw token string from the incoming request.
103     * @return void
104     */
105    private function maybe_link_wpcom_user_id( $token ) {
106        if ( ! is_user_logged_in() ) {
107            return;
108        }
109
110        $payload = $this->decode_token( $token );
111        if ( empty( $payload['user_id'] ) || empty( $payload['blog_subscriber'] ) ) {
112            return;
113        }
114
115        $local_user = wp_get_current_user();
116        if ( strcasecmp( $local_user->user_email, $payload['blog_subscriber'] ) !== 0 ) {
117            return;
118        }
119
120        if ( (int) get_user_meta( $local_user->ID, 'wpcom_user_id', true ) === (int) $payload['user_id'] ) {
121            return;
122        }
123
124        update_user_meta( $local_user->ID, 'wpcom_user_id', (int) $payload['user_id'] );
125    }
126
127    /**
128     * Attempt to refresh the current token against the WordPress.com refresh endpoint
129     * and, on success, persist the fresh token in the cookie and return the decoded
130     * payload.
131     *
132     * This is called when a subscriber has a JWT token whose subscription data is
133     * stale (e.g. the cookie contains an old end_date from before a Stripe renewal).
134     * The refresh endpoint accepts the existing token, re-queries billing, and
135     * returns a fresh token reflecting current subscription state.
136     *
137     * @return array|null Decoded fresh payload on success, null on any failure.
138     */
139    public function refresh_token_payload() {
140        $current_token = $this->get_and_set_token_from_request();
141        if ( empty( $current_token ) ) {
142            return null;
143        }
144
145        $fresh_token = $this->fetch_refreshed_token( $current_token );
146        if ( empty( $fresh_token ) ) {
147            return null;
148        }
149
150        $fresh_payload = $this->decode_token( $fresh_token );
151        if ( empty( $fresh_payload ) ) {
152            return null;
153        }
154
155        $this->set_token_cookie( $fresh_token );
156        return $fresh_payload;
157    }
158
159    /**
160     * POST the current token to the WordPress.com memberships token-refresh endpoint
161     * and return a fresh JWT string, or null on any failure.
162     *
163     * Endpoint contract (POST /sites/<site_id>/memberships/token/refresh):
164     *  - 200 + { success: true,  jwt_token: "<jwt>" } â†’ fresh token; return it.
165     *  - 200 + { success: false, ... }                â†’ wpcom refused the refresh
166     *    (token no longer eligible, or signature/site/user check failed).
167     *    Deterministic; clear the cookie so the visitor is routed through the normal
168     *    auth flow on the next page load.
169     *  - Anything else (non-200, WP_Error, network timeout, malformed body) â†’ transient;
170     *    leave the cookie alone so a temporary outage does not mass-log-out subscribers.
171     *
172     * @param string $current_token The token to present for refresh.
173     * @return string|null Fresh token string, or null on failure.
174     */
175    protected function fetch_refreshed_token( $current_token ) {
176        $site_id = (int) $this->get_site_id();
177        if ( $site_id <= 0 ) {
178            return null;
179        }
180
181        $response = wp_remote_post(
182            sprintf(
183                'https://public-api.wordpress.com/rest/v1.1/sites/%d/memberships/token/refresh',
184                $site_id
185            ),
186            array(
187                'timeout' => 5,
188                'headers' => array( 'Content-Type' => 'application/json' ),
189                'body'    => wp_json_encode(
190                    array( 'jwt_token' => $current_token ),
191                    JSON_UNESCAPED_SLASHES
192                ),
193            )
194        );
195
196        if ( is_wp_error( $response ) ) {
197            return null;
198        }
199
200        if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
201            return null;
202        }
203
204        $body = json_decode( wp_remote_retrieve_body( $response ), true );
205        if ( ! is_array( $body ) || ! isset( $body['success'] ) ) {
206            return null;
207        }
208
209        if ( true === $body['success'] ) {
210            if ( ! empty( $body['jwt_token'] ) && is_string( $body['jwt_token'] ) ) {
211                return $body['jwt_token'];
212            }
213            // Malformed 200: success: true but no usable jwt_token. Treat as transient â€”
214            // leave the cookie alone rather than logging the visitor out over a response
215            // shape problem.
216            return null;
217        }
218
219        // success === false â†’ deterministic auth failure. Clear cookie.
220        self::clear_token_cookie();
221        return null;
222    }
223
224    /**
225     * Whether the token already carries a subscription whose product_id matches one of
226     * the required plans. Used to gate the refresh path: combined with `validate_subscriptions`
227     * having returned false, a match here implies the matching subscription's end_date is
228     * in the past â€” the only case the refresh endpoint can help with.
229     *
230     * @param int[] $valid_plan_ids      Plan IDs required by the post.
231     * @param array $token_subscriptions Subscriptions from the current token (keyed by product_id).
232     * @return bool
233     */
234    public function token_has_matching_product( array $valid_plan_ids, array $token_subscriptions ) {
235        if ( empty( $token_subscriptions ) ) {
236            return false;
237        }
238        foreach ( $valid_plan_ids as $plan_id ) {
239            $product_id = (int) get_post_meta( $plan_id, 'jetpack_memberships_product_id', true );
240            if ( $product_id > 0 && isset( $token_subscriptions[ $product_id ] ) ) {
241                return true;
242            }
243        }
244        return false;
245    }
246
247    /**
248     * Get the site ID for the current site.
249     *
250     * @return int
251     */
252    abstract public function get_site_id();
253
254    /**
255     * Get the token payload .
256     *
257     * @return array
258     */
259    public function get_token_payload() {
260        $token = $this->get_and_set_token_from_request();
261        if ( empty( $token ) ) {
262            return array();
263        }
264        $token_payload = $this->decode_token( $token );
265        if ( ! is_array( $token_payload ) ) {
266            return array();
267        }
268        return $token_payload;
269    }
270
271    /**
272     * Get a token property, otherwise return false.
273     *
274     * @param string $key the property name.
275     *
276     * @return mixed|false
277     */
278    public function get_token_property( $key ) {
279        $token_payload = $this->get_token_payload();
280        if ( ! isset( $token_payload[ $key ] ) ) {
281            return false;
282        }
283        return $token_payload[ $key ];
284    }
285
286    /**
287     * The user is visiting with a subscriber token cookie.
288     *
289     * This is theoretically where the cookie JWT signature verification
290     * thing will happen.
291     *
292     * How to obtain one of these (or what exactly it is) is
293     * still a WIP (see api/auth branch)
294     *
295     * @inheritDoc
296     *
297     * @param array    $valid_plan_ids List of valid plan IDs.
298     * @param string   $access_level Access level for content.
299     * @param int|null $post_id Post to gate against. Defaults to the loop post, which is only right while rendering it.
300     *
301     * @return bool Whether the user can view the content
302     */
303    public function visitor_can_view_content( $valid_plan_ids, $access_level, $post_id = null ) {
304        global $current_user;
305        $old_user = $current_user; // backup the current user so we can set the current user to the token user for paywall purposes
306
307        $payload        = $this->get_token_payload();
308        $is_valid_token = ! empty( $payload );
309
310        if ( $is_valid_token && isset( $payload['user_id'] ) ) {
311            // set the current user to the payload's user id
312            // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
313            $current_user = get_user_by( 'id', $payload['user_id'] );
314        }
315
316        $is_blog_subscriber = false;
317        $is_paid_subscriber = false;
318        $subscriptions      = array();
319
320        if ( $is_valid_token ) {
321            /**
322             * Allow access to the content if:
323             *
324             * Active: user has a valid subscription
325             */
326            $is_blog_subscriber = in_array(
327                $payload['blog_sub'],
328                array(
329                    self::BLOG_SUB_ACTIVE,
330                ),
331                true
332            );
333            $subscriptions      = (array) $payload['subscriptions'];
334            $is_paid_subscriber = static::validate_subscriptions( $valid_plan_ids, $subscriptions );
335
336            // Only attempt a refresh in the specific stale-end_date case: the token already carries a
337            // subscription whose product_id matches one of the required plans, but validation failed
338            // (which, given the match, can only be because end_date is in the past). This excludes
339            // free subscribers, tier mismatches, and cancellations from triggering an HTTP call on
340            // every render.
341            if (
342                ! $is_paid_subscriber
343                && ! empty( $valid_plan_ids )
344                && $this->token_has_matching_product( $valid_plan_ids, $subscriptions )
345            ) {
346                $fresh_payload = $this->refresh_token_payload();
347                if ( ! empty( $fresh_payload ) ) {
348                    $payload            = $fresh_payload;
349                    $is_blog_subscriber = isset( $payload['blog_sub'] ) && self::BLOG_SUB_ACTIVE === $payload['blog_sub'];
350                    $subscriptions      = isset( $payload['subscriptions'] ) ? (array) $payload['subscriptions'] : array();
351                    $is_paid_subscriber = static::validate_subscriptions( $valid_plan_ids, $subscriptions );
352                }
353            }
354        }
355
356        $has_access = $this->user_has_access( $access_level, $is_blog_subscriber, $is_paid_subscriber, null === $post_id ? get_the_ID() : $post_id, $subscriptions );
357        // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
358        $current_user = $old_user;
359        return $has_access;
360    }
361
362    /**
363     * Check subscription entitlement without granting access for editing the post.
364     *
365     * @since 16.4
366     *
367     * @param array    $valid_plan_ids Required subscription plan IDs.
368     * @param string   $access_level   Required access level.
369     * @param int|null $post_id        Post to check, or the loop post when omitted.
370     * @return bool Whether the visitor meets the subscription requirement.
371     */
372    public function visitor_has_subscription_access( $valid_plan_ids, $access_level, $post_id = null ) {
373        $allow_editor_access       = $this->allow_editor_access;
374        $this->allow_editor_access = false;
375        try {
376            return $this->visitor_can_view_content( $valid_plan_ids, $access_level, $post_id );
377        } finally {
378            $this->allow_editor_access = $allow_editor_access;
379        }
380    }
381
382    /**
383     * Retrieves the email of the currently authenticated subscriber.
384     *
385     * @return string The email address of the current user.
386     */
387    public function get_subscriber_email() {
388        $email = $this->get_token_property( 'blog_subscriber' );
389        if ( empty( $email ) ) {
390            return '';
391        }
392        return $email;
393    }
394
395    /**
396     * Returns true if the current authenticated user is subscribed to the current site.
397     *
398     * @return boolean
399     */
400    public function is_current_user_subscribed() {
401        return $this->get_token_property( 'blog_sub' ) === 'active';
402    }
403
404    /**
405     * Returns true if the current authenticated user has a pending subscription to the current site.
406     *
407     * @return bool
408     */
409    abstract public function is_current_user_pending_subscriber(): bool;
410
411    /**
412     * Return if the user has access to the content depending on the access level and the user rights
413     *
414     * @param string $access_level Post or blog access level.
415     * @param bool   $is_blog_subscriber Is user a subscriber of the blog.
416     * @param bool   $is_paid_subscriber Is user a paid subscriber of the blog.
417     * @param int    $post_id Post ID.
418     * @param array  $user_abbreviated_subscriptions User subscription abbreviated.
419     *
420     * @return bool Whether the user has access to the content.
421     */
422    protected function user_has_access( $access_level, $is_blog_subscriber, $is_paid_subscriber, $post_id, $user_abbreviated_subscriptions ) {
423
424        if ( $this->allow_editor_access && is_user_logged_in() && current_user_can( 'edit_post', $post_id ) ) {
425            // Admin has access
426            $has_access = true;
427        } else {
428            switch ( $access_level ) {
429                case self::POST_ACCESS_LEVEL_EVERYBODY:
430                default:
431                    $has_access = true;
432                    break;
433                case self::POST_ACCESS_LEVEL_SUBSCRIBERS:
434                    $has_access = $is_blog_subscriber || $is_paid_subscriber;
435                    break;
436                case self::POST_ACCESS_LEVEL_PAID_SUBSCRIBERS_ALL_TIERS:
437                    $has_access = $is_paid_subscriber;
438                    break;
439                case self::POST_ACCESS_LEVEL_PAID_SUBSCRIBERS:
440                    $has_access = $is_paid_subscriber &&
441                        ! $this->maybe_gate_access_for_user_if_post_tier( $post_id, $user_abbreviated_subscriptions );
442                    break;
443            }
444        }
445
446        do_action( 'earn_user_has_access', $access_level, $has_access, $is_blog_subscriber, $is_paid_subscriber, $post_id );
447        return $has_access;
448    }
449
450    /**
451     * Check post access for tiers.
452     *
453     * @param int   $post_id Current post id.
454     * @param array $user_abbreviated_subscriptions User subscription abbreviated.
455     *
456     * @return bool
457     */
458    private function maybe_gate_access_for_user_if_post_tier( $post_id, $user_abbreviated_subscriptions ) {
459        $tier_id = intval(
460            get_post_meta( $post_id, META_NAME_FOR_POST_TIER_ID_SETTINGS, true )
461        );
462
463        if ( ! $tier_id ) {
464            return false;
465        }
466
467        return $this->maybe_gate_access_for_user_if_tier( $tier_id, $user_abbreviated_subscriptions );
468    }
469
470    /**
471     * Get all plans id that make access valid for a post with this tier id.
472     *
473     * @param int $tier_id Newsletter tier post ID.
474     *
475     * @return array|WP_Error
476     */
477    public static function get_valid_plan_ids_for_tier( int $tier_id ) {
478        // Valid plans are:
479        // - monthly plan with ID $tier_id
480        // - yearly plan related to this $tier_id (in meta jetpack_memberships_tier)
481        // - monthly tiers with same currency and price same or higher than original tier
482        // - yearly plans that are more expensive than the yearly plan linked to the original tier
483
484        $valid_plan_ids = array();
485
486        $all_plans = \Jetpack_Memberships::get_all_plans();
487
488        // Let's get the current tier
489        $tier = null;
490        foreach ( $all_plans as $post ) {
491            if ( $post->ID === $tier_id ) {
492                $tier = $post;
493                break;
494            }
495        }
496
497        if ( $tier === null ) {
498            // We have an error
499            return new WP_Error( 'related-plan-not-found', 'The plan related to the tier cannot be found' );
500        }
501
502        $tier_price      = self::find_metadata( $tier, 'jetpack_memberships_price' );
503        $tier_currency   = self::find_metadata( $tier, 'jetpack_memberships_currency' );
504        $tier_product_id = self::find_metadata( $tier, 'jetpack_memberships_product_id' );
505
506        if ( $tier_price === null || $tier_currency === null || $tier_product_id === null ) {
507            // There is an issue with the meta
508            return new WP_Error( 'wrong-data-plan-not-found', 'The plan related to the tier is missing data' );
509        }
510
511        $valid_plan_ids[] = $tier_id;
512
513        $tier_price = floatval( $tier_price );
514
515        // At this point we know the post is
516        $annual_tier = null;
517        foreach ( $all_plans as $plan ) {
518            if ( intval( self::find_metadata( $plan, 'jetpack_memberships_tier' ) ) === $tier_id ) {
519                $annual_tier = $plan;
520                break;
521            }
522        }
523
524        $annual_tier_price = null;
525        if ( ! empty( $annual_tier ) ) {
526            $annual_tier_price = floatval( self::find_metadata( $annual_tier, 'jetpack_memberships_price' ) );
527            $valid_plan_ids[]  = $annual_tier->ID;
528        }
529
530        foreach ( $all_plans as $post ) {
531            if ( in_array( $post->ID, $valid_plan_ids, true ) ) {
532                continue;
533            }
534
535            $plan_price    = self::find_metadata( $post, 'jetpack_memberships_price' );
536            $plan_currency = self::find_metadata( $post, 'jetpack_memberships_currency' );
537            $plan_interval = self::find_metadata( $post, 'jetpack_memberships_interval' );
538
539            if ( $plan_price === null || $plan_currency === null || $plan_interval === null ) {
540                // There is an issue with the meta
541                continue;
542            }
543
544            $plan_price = floatval( $plan_price );
545
546            if ( $tier_currency !== $plan_currency ) {
547                // For now, we don't count if there are different currency (not sure how to convert price in a pure JP env)
548                continue;
549            }
550
551            if ( ( $plan_interval === '1 month' && $plan_price >= $tier_price ) ||
552                ( $annual_tier_price !== null && $plan_interval === '1 year' && $plan_price >= $annual_tier_price )
553            ) {
554                $valid_plan_ids [] = $post->ID;
555            }
556        }
557
558        return $valid_plan_ids;
559    }
560
561    /**
562     * Find metadata in post
563     *
564     * @param WP_Post|object $post        Post.
565     * @param string         $meta_key    Meta to retrieve.
566     *
567     * @return mixed|null
568     */
569    private static function find_metadata( $post, $meta_key ) {
570
571        if ( $post instanceof WP_Post ) {
572            return $post->{$meta_key};
573        }
574
575        foreach ( $post->metadata as $meta ) {
576            if ( $meta->key === $meta_key ) {
577                return $meta->value;
578            }
579        }
580
581        return null;
582    }
583
584    /**
585     * Check access for tier.
586     *
587     * @param int   $tier_id Tier id.
588     * @param array $user_abbreviated_subscriptions User subscription abbreviated.
589     *
590     * @return bool
591     */
592    public function maybe_gate_access_for_user_if_tier( $tier_id, $user_abbreviated_subscriptions ) {
593
594        $plan_ids = \Jetpack_Memberships::get_all_newsletter_plan_ids();
595
596        if ( ! in_array( $tier_id, $plan_ids, true ) ) {
597            // If the tier is not in the plans, we bail
598            return false;
599        }
600
601        // We now need the tier price and currency, and the same for the annual price (if available)
602        $all_plans = \Jetpack_Memberships::get_all_plans();
603        $tier      = null;
604        foreach ( $all_plans as $post ) {
605            if ( $post->ID === $tier_id ) {
606                $tier = $post;
607                break;
608            }
609        }
610
611        if ( $tier === null ) {
612            return false;
613        }
614
615        $tier_price        = self::find_metadata( $tier, 'jetpack_memberships_price' );
616        $tier_currency     = self::find_metadata( $tier, 'jetpack_memberships_currency' );
617        $tier_product_id   = self::find_metadata( $tier, 'jetpack_memberships_product_id' );
618        $annual_tier_price = $tier_price * 12;
619
620        if ( $tier_price === null || $tier_currency === null || $tier_product_id === null ) {
621            // There is an issue with the meta
622            return false;
623        }
624
625        $tier_price = floatval( $tier_price );
626
627        // At this point we know the post is
628        $annual_tier_id = null;
629        $annual_tier    = null;
630        foreach ( $all_plans as $plan ) {
631            if ( intval( self::find_metadata( $plan, 'jetpack_memberships_tier' ) ) === $tier_id ) {
632                $annual_tier = $plan;
633                break;
634            }
635        }
636
637        $annual_tier_price = null;
638        if ( ! empty( $annual_tier ) ) {
639            $annual_tier_id    = $annual_tier->ID;
640            $annual_tier_price = floatval( self::find_metadata( $annual_tier, 'jetpack_memberships_price' ) );
641        }
642
643        foreach ( $user_abbreviated_subscriptions as $subscription_plan_id => $details ) {
644            $details = (array) $details;
645
646            if ( ! self::subscription_grants_access( $details ) ) {
647                // Subscription not active anymore (its end_date day has fully passed).
648                continue;
649            }
650
651            $subscription_post = null;
652            foreach ( $all_plans as $plan ) {
653                if ( intval( self::find_metadata( $plan, 'jetpack_memberships_product_id' ) ) === intval( $subscription_plan_id ) ) {
654                    $subscription_post = $plan;
655                    break;
656                }
657            }
658
659            if ( empty( $subscription_post ) ) {
660                // No post linked to this plan
661                continue;
662            }
663
664            // Comp grants linked to a plan on this site bypass the tier price comparison.
665            if ( ! empty( $details['is_comp'] ) ) {
666                return false;
667            }
668
669            $subscription_post_id = $subscription_post->ID;
670
671            if ( $subscription_post_id === $tier_id || $subscription_post_id === $annual_tier_id ) {
672                // User is subscribed to the right tier
673                return false;
674            }
675
676            $subscription_price    = self::find_metadata( $subscription_post, 'jetpack_memberships_price' );
677            $subscription_currency = self::find_metadata( $subscription_post, 'jetpack_memberships_currency' );
678            $subscription_interval = self::find_metadata( $subscription_post, 'jetpack_memberships_interval' );
679
680            if ( $subscription_price === null || $subscription_currency === null || $subscription_interval === null ) {
681                // There is an issue with the meta
682                continue;
683            }
684
685            $subscription_price = floatval( $subscription_price );
686
687            if ( $tier_currency !== $subscription_currency ) {
688                // For now, we don't count if there are different currency (not sure how to convert price in a pure JP env)
689                continue;
690            }
691
692            if ( ( $subscription_interval === '1 month' && $subscription_price >= $tier_price ) ||
693                    ( $annual_tier_price !== null && $subscription_interval === '1 year' && $subscription_price >= $annual_tier_price )
694            ) {
695                // One subscription is more expensive than the minimum set by the post' selected tier
696                return false;
697            }
698        }
699        return true; // No user subscription is more expensive than the post's tier price...
700    }
701
702    /**
703     * Decode the given token.
704     *
705     * @param string $token Token to decode.
706     *
707     * @return array|false
708     */
709    public function decode_token( $token ) {
710        if ( empty( $token ) ) {
711            return false;
712        }
713
714        try {
715            $key = $this->get_key();
716            return $key ? (array) JWT::decode( $token, $key, array( 'HS256' ) ) : false;
717        } catch ( \Exception $exception ) {
718            return false;
719        }
720    }
721
722    /**
723     * Get the key for decoding the auth token.
724     *
725     * @return string|false
726     */
727    abstract public function get_key();
728
729    // phpcs:disable
730    /**
731     * Get the URL to access the protected content.
732     *
733     * @param string $mode Access mode (either "subscribe" or "login").
734     */
735    public function access_url( $mode = 'subscribe', $permalink = null ) {
736        global $wp;
737        if ( empty( $permalink ) ) {
738            $permalink = get_permalink();
739            if ( empty( $permalink ) ) {
740                $permalink = add_query_arg( $wp->query_vars, home_url( $wp->request ) );
741            }
742        }
743
744        $login_url = $this->get_rest_api_token_url( $this->get_site_id(), $permalink );
745        return $login_url;
746    }
747    // phpcs:enable
748
749    /**
750     * Get the token stored in the auth cookie.
751     *
752     * @return ?string
753     */
754    private function token_from_cookie() {
755        if ( isset( $_COOKIE[ self::JWT_AUTH_TOKEN_COOKIE_NAME ] ) ) {
756            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
757            return $_COOKIE[ self::JWT_AUTH_TOKEN_COOKIE_NAME ];
758        }
759    }
760
761    /**
762     * Check whether the JWT_TOKEN cookie is set
763     *
764     * @return bool
765     */
766    public static function has_token_from_cookie() {
767        return isset( $_COOKIE[ self::JWT_AUTH_TOKEN_COOKIE_NAME ] ) && ! empty( $_COOKIE[ self::JWT_AUTH_TOKEN_COOKIE_NAME ] );
768    }
769
770    /**
771     * Store the auth cookie.
772     *
773     * Updates `$_COOKIE` in memory so subsequent code in the same request (e.g. another
774     * Premium Content block on the same post) reads the new value and doesn't re-trigger
775     * a refresh against a now-stale value. The Set-Cookie header is emitted via the
776     * standard `setcookie()` â€” on Atomic / wpcom the response is output-buffered so this
777     * still works during `the_content`; on stricter self-hosted setups the header may
778     * silently be dropped after output starts, in which case the browser keeps the prior
779     * cookie value and the refresh fires again on the next visit (correct degradation).
780     *
781     * @param  string $token Auth token.
782     * @return void
783     */
784    private function set_token_cookie( $token ) {
785        if ( empty( $token ) ) {
786            return;
787        }
788
789        $_COOKIE[ self::JWT_AUTH_TOKEN_COOKIE_NAME ] = $token;
790
791        if ( defined( 'TESTING_IN_JETPACK' ) && TESTING_IN_JETPACK ) {
792            return;
793        }
794
795        if ( ! headers_sent() ) {
796            // phpcs:ignore Jetpack.Functions.SetCookie.FoundNonHTTPOnlyFalse
797            setcookie( self::JWT_AUTH_TOKEN_COOKIE_NAME, $token, strtotime( '+1 month' ), '/', '', is_ssl(), false );
798        }
799    }
800
801    /**
802     * Clear the auth cookie. Mirrors set_token_cookie(): updates `$_COOKIE` for
803     * in-request consistency, then emits a clearing Set-Cookie header.
804     */
805    public static function clear_token_cookie() {
806        unset( $_COOKIE[ self::JWT_AUTH_TOKEN_COOKIE_NAME ] );
807
808        if ( defined( 'TESTING_IN_JETPACK' ) && TESTING_IN_JETPACK ) {
809            return;
810        }
811
812        if ( ! headers_sent() ) {
813            // phpcs:ignore Jetpack.Functions.SetCookie.FoundNonHTTPOnlyFalse
814            setcookie( self::JWT_AUTH_TOKEN_COOKIE_NAME, '', 1, '/', '', is_ssl(), false );
815        }
816    }
817
818    /**
819     * Pause the paywall's silent subscriber check for a month, so a subscriber who logs out
820     * isn't signed straight back in from their WordPress.com session. The check's script
821     * reads this cookie, so it can't be httponly.
822     *
823     * @since $$next-version$$
824     */
825    public static function pause_silent_subscriber_check() {
826        $_COOKIE[ self::SILENT_SUBSCRIBER_CHECK_COOKIE ] = '1';
827
828        if ( defined( 'TESTING_IN_JETPACK' ) && TESTING_IN_JETPACK ) {
829            return;
830        }
831
832        if ( ! headers_sent() ) {
833            // phpcs:ignore Jetpack.Functions.SetCookie.FoundNonHTTPOnlyFalse
834            setcookie( self::SILENT_SUBSCRIBER_CHECK_COOKIE, '1', strtotime( '+1 month' ), '/', '', is_ssl(), false );
835        }
836    }
837
838    /**
839     * Get the token if present in the current request.
840     *
841     * @return ?string
842     */
843    private function token_from_request() {
844        $token = null;
845        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
846        if ( isset( $_GET['token'] ) && is_string( $_GET['token'] ) ) {
847            // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.NonceVerification.Recommended
848            if ( preg_match( '/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/', $_GET['token'], $matches ) ) {
849                // token matches a valid JWT token pattern.
850                $token = reset( $matches );
851            }
852        }
853        return $token;
854    }
855
856    /**
857     * Return true if an abbreviated subscription currently grants access.
858     *
859     * Access is granted through the end of the subscription's end_date day
860     * (23:59:59 UTC), not the exact end_date timestamp. Memberships store
861     * end_date as the precise purchase timestamp, while billing renews via a
862     * deferred day-0 job that can run several hours after that timestamp. Since
863     * the wider platform already treats end-of-day as the formal expiration
864     * time for subscriptions, expiring at EOD here keeps a same-day auto-renewal
865     * from cutting off access before its renewal completes, and aligns Paid
866     * Content with the rest of WordPress.com / Jetpack.
867     *
868     * Cancelled and otherwise inactive subscriptions never reach this check â€”
869     * they are dropped by the `'active' === status` filter in
870     * abbreviate_subscriptions() â€” so this only ever extends an already-active
871     * subscription to the end of its final day.
872     *
873     * @param object|array $subscription Abbreviated subscription (see abbreviate_subscriptions()).
874     *
875     * @return bool
876     */
877    protected static function subscription_grants_access( $subscription ) {
878        $subscription = (array) $subscription;
879        if ( empty( $subscription['end_date'] ) ) {
880            return false;
881        }
882
883        $end = is_int( $subscription['end_date'] ) ? $subscription['end_date'] : strtotime( $subscription['end_date'] );
884        if ( false === $end ) {
885            return false;
886        }
887
888        // Expire at the end of the end_date's day (UTC), matching the platform's
889        // formal expiration convention rather than the exact purchase timestamp.
890        $end_of_day = strtotime( gmdate( 'Y-m-d 23:59:59', $end ) . ' UTC' );
891
892        return $end_of_day >= time();
893    }
894
895    /**
896     * Return true if any ID/date pairs are valid. Otherwise false.
897     *
898     * @param int[]    $valid_plan_ids List of valid plan IDs.
899     * @param object[] $token_subscriptions : ID must exist in the provided <code>$valid_subscriptions</code> parameter.
900     *                                                            The provided end date needs to fall on or after today,
901     *                                                            i.e. access lasts through the end of the end_date day (UTC).
902     *
903     * @return bool
904     */
905    public static function validate_subscriptions( array $valid_plan_ids, array $token_subscriptions ) {
906        // Create a list of product_ids to compare against.
907        $product_ids = array();
908        foreach ( $valid_plan_ids as $plan_id ) {
909            $product_id = (int) get_post_meta( $plan_id, 'jetpack_memberships_product_id', true );
910            if ( isset( $product_id ) ) {
911                $product_ids[] = $product_id;
912            }
913        }
914
915        foreach ( $token_subscriptions as $product_id => $token_subscription ) {
916            if ( in_array( intval( $product_id ), $product_ids, true ) ) {
917                if ( static::subscription_grants_access( $token_subscription ) ) {
918                    return true;
919                }
920            }
921        }
922        return false;
923    }
924
925    /**
926     * Get the URL of the JWT endpoint.
927     *
928     * @param  int    $site_id Site ID.
929     * @param  string $redirect_url URL to redirect after checking the token validity.
930     * @return string URL of the JWT endpoint.
931     */
932    private function get_rest_api_token_url( $site_id, $redirect_url ) {
933        // The redirect url might have a part URL encoded but not the whole URL.
934        $redirect_url = rawurldecode( $redirect_url );
935        return sprintf( '%smemberships/jwt?site_id=%d&redirect_url=%s', self::REST_URL_ORIGIN, $site_id, rawurlencode( $redirect_url ) );
936    }
937
938    /**
939     * Report the subscriptions as an ID => [ 'end_date' => ]. mapping
940     *
941     * @param array $subscriptions_from_bd List of subscriptions from BD.
942     *
943     * @return array<int, array>
944     */
945    public static function abbreviate_subscriptions( $subscriptions_from_bd ) {
946
947        if ( empty( $subscriptions_from_bd ) ) {
948            return array();
949        }
950
951        $subscriptions = array();
952        foreach ( $subscriptions_from_bd as $subscription ) {
953            // We are picking the expiry date that is the most in the future.
954            if (
955                'active' === $subscription['status'] && (
956                    ! isset( $subscriptions[ $subscription['product_id'] ] ) ||
957                    empty( $subscription['end_date'] ) || // Special condition when subscription has no expiry date - we will default to a year from now for the purposes of the token.
958                    strtotime( $subscription['end_date'] ) > strtotime( (string) $subscriptions[ $subscription['product_id'] ]->end_date )
959                )
960            ) {
961                $subscriptions[ $subscription['product_id'] ]           = new \stdClass();
962                $subscriptions[ $subscription['product_id'] ]->end_date = empty( $subscription['end_date'] ) ? ( time() + 365 * 24 * 3600 ) : $subscription['end_date'];
963                if ( ! empty( $subscription['is_comp'] ) ) {
964                    $subscriptions[ $subscription['product_id'] ]->is_comp = true;
965                }
966            }
967        }
968        return $subscriptions;
969    }
970}