Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
88.26% covered (warning)
88.26%
203 / 230
54.17% covered (warning)
54.17%
13 / 24
CRAP
0.00% covered (danger)
0.00%
0 / 1
Access_Control
88.26% covered (warning)
88.26%
203 / 230
54.17% covered (warning)
54.17%
13 / 24
144.69
0.00% covered (danger)
0.00%
0 / 1
 set_guid_subscription
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 get_subscription_plan_id
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 instance
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 jetpack_memberships_available
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 jetpack_subscriptions_available
41.67% covered (danger)
41.67%
5 / 12
0.00% covered (danger)
0.00%
0 / 1
9.96
 get_default_user_capability_for_post
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 build_restriction_details
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
11
 check_block_level_access
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
5
 block_gate_grants_access
71.43% covered (warning)
71.43%
10 / 14
0.00% covered (danger)
0.00%
0 / 1
8.14
 get_subscriber_only_restriction_details
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 filter_video_restriction_details
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 default_video_restriction_details
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 build_and_cache_post_guids
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
5.01
 ensure_post_guids_cached
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
4.01
 collect_guids_from_content
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
10
 collect_guids_from_blocks
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
24
 get_required_plan_ids_for_guid
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 find_gating_plan_ids
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
9.06
 container_gates_guid
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 extract_plan_ids
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 post_embeds_videopress_guid_cached
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
4.03
 is_current_user_authed_for_video
79.41% covered (warning)
79.41%
27 / 34
0.00% covered (danger)
0.00%
0 / 1
16.96
 filter_is_current_user_authed_for_video
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_videopress_blog_id
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * VideoPress Access Control.
4 *
5 * @package automattic/jetpack-videopress
6 */
7
8namespace Automattic\Jetpack\VideoPress;
9
10use Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service\Abstract_Token_Subscription_Service;
11use Automattic\Jetpack\Modules;
12use VIDEOPRESS_PRIVACY;
13use WP_Post;
14
15/**
16 * VideoPress video access control utilities.
17 *
18 * Note: this is also being used on WordPress.com.
19 * Use IS_WPCOM checks for functionality that is specific to WPCOM/Jetpack.
20 */
21class Access_Control {
22
23    /**
24     * Singleton Access_Control instance.
25     *
26     * @var Access_Control
27     **/
28    private static $instance = null;
29
30    /**
31     * Guid to subscription plan, store, for when used inline on a page.
32     *
33     * @var array
34     */
35    private $guids_to_subscriptions = array();
36
37    /**
38     * Set that this guid is controlled by a subscription.
39     *
40     * @param string     $guid            The guid to set.
41     * @param string|int $subscription_id The subscription to set.
42     *
43     * @return Access_Control
44     */
45    public function set_guid_subscription( $guid, $subscription_id ) {
46        $this->guids_to_subscriptions[ $guid ] = $subscription_id;
47        return $this;
48    }
49
50    /**
51     * Get the subscription for a guid.
52     *
53     * @param string $guid The guid to get.
54     *
55     * @return string|int|false
56     */
57    public function get_subscription_plan_id( $guid ) {
58        return $this->guids_to_subscriptions[ $guid ] ?? false;
59    }
60
61    /**
62     * Get the singleton instance.
63     *
64     * @return self
65     */
66    public static function instance() {
67        if ( null === self::$instance ) {
68            self::$instance = new self();
69        }
70
71        return self::$instance;
72    }
73
74    /**
75     * Determines if Jetpack Memberships are available.
76     *
77     * @return bool
78     */
79    private function jetpack_memberships_available() {
80        return class_exists( '\Jetpack_Memberships' );
81    }
82
83    /**
84     * Determines if Jetpack Subscriptions are available.
85     *
86     * @return bool
87     */
88    private function jetpack_subscriptions_available() {
89        $is_module_active = ( new Modules() )->is_active( 'subscriptions' );
90        if ( ! $is_module_active ) {
91            return false;
92        }
93
94        if ( function_exists( '\Automattic\Jetpack\Extensions\Premium_Content\subscription_service' ) ) {
95            return true;
96        }
97
98        if ( ! defined( 'JETPACK__PLUGIN_DIR' ) ) {
99            return false;
100        }
101
102        $subscription_service_file_path = JETPACK__PLUGIN_DIR . 'extensions/blocks/premium-content/_inc/subscription-service/include.php';
103        if ( ! file_exists( $subscription_service_file_path ) ) {
104            return false;
105        }
106
107        require_once $subscription_service_file_path;
108
109        return function_exists( '\Automattic\Jetpack\Extensions\Premium_Content\subscription_service' );
110    }
111
112    /**
113     * Check default user access. By default, subscribers or higher can view videos.
114     *
115     * @param WP_Post $post_to_check The post to check.
116     *
117     * @return bool
118     **/
119    private function get_default_user_capability_for_post( $post_to_check ) {
120        if ( ! isset( $post_to_check->ID ) ) {
121            return false;
122        }
123
124        $default_auth = current_user_can( 'read_post', $post_to_check->ID );
125
126        return $default_auth;
127    }
128
129    /**
130     * Determines if the current user can access restricted content and builds the restriction_details array.
131     *
132     * @param string $guid the video guid.
133     * @param int    $embedded_post_id the post id.
134     * @param int    $selected_plan_id the selected plan id if applicable.
135     *
136     * @return array
137     */
138    private function build_restriction_details( $guid, $embedded_post_id, $selected_plan_id ) {
139        // A missing post ID does not fall back to the global post, as get_post( 0 ) would.
140        $post_to_check = $embedded_post_id > 0 ? get_post( $embedded_post_id ) : null;
141
142        // Only a published embedding post can authorize playback.
143        if ( ! $post_to_check instanceof WP_Post || 'publish' !== $post_to_check->post_status ) {
144            $restriction_details = $this->default_video_restriction_details( false );
145            return $this->filter_video_restriction_details( $restriction_details, $guid, $embedded_post_id, $selected_plan_id );
146        }
147
148        $default_auth        = $this->get_default_user_capability_for_post( $post_to_check );
149        $restriction_details = $this->default_video_restriction_details( $default_auth );
150        // Logged-out visitors never have read_post, so a public post admits them on its status alone.
151        // Neither check knows about post passwords, which the page enforces for everyone.
152        $password_required   = post_password_required( $post_to_check );
153        $post_admits_visitor = ( $default_auth || is_post_publicly_viewable( $post_to_check ) )
154            && ! $password_required;
155
156        if ( $this->jetpack_memberships_available() ) {
157            $post_access_level = \Jetpack_Memberships::get_post_access_level( $embedded_post_id );
158            if ( 'everybody' !== $post_access_level ) {
159                $memberships_can_view_post         = is_callable( array( '\Jetpack_Memberships', 'user_has_subscription_access' ) )
160                    && \Jetpack_Memberships::user_has_subscription_access( $embedded_post_id );
161                $restriction_details               = $this->get_subscriber_only_restriction_details( $default_auth );
162                $restriction_details['can_access'] = $memberships_can_view_post;
163                $post_admits_visitor               = $post_admits_visitor && $memberships_can_view_post;
164            }
165        }
166
167        $restriction_details['can_access'] = $restriction_details['can_access'] && ! $password_required;
168
169        return $this->check_block_level_access(
170            $restriction_details,
171            $guid,
172            $embedded_post_id,
173            $selected_plan_id,
174            $post_admits_visitor
175        );
176    }
177
178    /**
179     * Determines if the current user can access restricted block content and updates the restriction_details array.
180     *
181     * @param array  $restriction_details the restriction details array.
182     * @param string $guid the video guid.
183     * @param int    $embedded_post_id the post id.
184     * @param int    $selected_plan_id the plan id sent with the request. Only passed on to the filter below.
185     * @param bool   $post_admits_visitor Whether the embedding post itself, and any paywall on it, lets the visitor in.
186     *
187     * @return array
188     */
189    private function check_block_level_access( $restriction_details, $guid, $embedded_post_id, $selected_plan_id, $post_admits_visitor ) {
190        // Plans come from the stored block; null means no Paid Content block wraps the guid.
191        $required_plan_ids = $this->get_required_plan_ids_for_guid( $embedded_post_id, $guid );
192
193        if ( $this->jetpack_subscriptions_available() && null !== $required_plan_ids ) {
194            $prior_can_access    = $restriction_details['can_access'];
195            $restriction_details = $this->get_subscriber_only_restriction_details( $prior_can_access );
196
197            if ( empty( $required_plan_ids ) ) {
198                $restriction_details['can_access'] = false;
199            } else {
200                $can_view = $this->block_gate_grants_access( $required_plan_ids, $embedded_post_id );
201
202                // A block grant also requires the post-level decision.
203                $restriction_details['can_access'] = $post_admits_visitor && $can_view;
204            }
205        }
206
207        return $this->filter_video_restriction_details(
208            $restriction_details,
209            $guid,
210            $embedded_post_id,
211            $selected_plan_id
212        );
213    }
214
215    /**
216     * Ask the premium-content block's own gate whether the visitor may view content behind these plans.
217     *
218     * Sharing the gate keeps playback and the page in agreement, including on tier upgrades.
219     *
220     * @param int[] $required_plan_ids Plan ids derived from the block wrapping the guid.
221     * @param int   $embedded_post_id  The post the block lives in; there is no loop post to fall back on here.
222     *
223     * @return bool
224     */
225    private function block_gate_grants_access( $required_plan_ids, $embedded_post_id ) {
226        // The gate normally loads with the Paid Content block, which a site can have switched off.
227        if (
228            ! function_exists( '\Automattic\Jetpack\Extensions\Premium_Content\visitor_has_subscription_access_to_plan_ids' )
229            && defined( 'JETPACK__PLUGIN_DIR' )
230        ) {
231            $access_check_path = JETPACK__PLUGIN_DIR . 'extensions/blocks/premium-content/_inc/access-check.php';
232            if ( file_exists( $access_check_path ) ) {
233                require_once $access_check_path;
234            }
235        }
236
237        if ( function_exists( '\Automattic\Jetpack\Extensions\Premium_Content\visitor_has_subscription_access_to_plan_ids' ) ) {
238            return (bool) \Automattic\Jetpack\Extensions\Premium_Content\visitor_has_subscription_access_to_plan_ids( $required_plan_ids, $embedded_post_id );
239        }
240
241        // A newer standalone VideoPress can run beside an older Jetpack that lacks the shared gate.
242        // Exact plan matching is stricter than the gate for tiers, never more permissive.
243        $paywall = \Automattic\Jetpack\Extensions\Premium_Content\subscription_service();
244
245        // Only paid subscribers should be granted access to the premium content.
246        $access_level = '';
247        if ( class_exists( Abstract_Token_Subscription_Service::class ) ) {
248            $access_level = Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_PAID_SUBSCRIBERS;
249        }
250
251        // Deny when the service has no entitlement-only check.
252        return is_callable( array( $paywall, 'visitor_has_subscription_access' ) )
253            // @phan-suppress-next-line PhanUndeclaredMethod -- Optional method is checked above to support older services.
254            && $paywall->visitor_has_subscription_access( $required_plan_ids, $access_level, $embedded_post_id );
255    }
256
257    /**
258     * Returns the default restriction_details for a video.
259     *
260     * @param bool $default_can_access The default auth.
261     *
262     * @return array
263     **/
264    private function get_subscriber_only_restriction_details( $default_can_access = false ) {
265        return array(
266            'provider'             => 'jetpack_memberships',
267            'title'                => __( 'This video is subscriber-only', 'jetpack-videopress-pkg' ),
268            'unauthorized_message' => __( 'You need to be subscribed to view this video', 'jetpack-videopress-pkg' ),
269            'can_access'           => $default_can_access,
270        );
271    }
272
273    /**
274     * Filters restriction details.
275     *
276     * @param array  $video_restriction_details The restriction details.
277     * @param string $guid The video guid.
278     * @param int    $embedded_post_id The post id.
279     * @param int    $selected_plan_id The selected plan id if applicable.
280     *
281     * @return array
282     */
283    private function filter_video_restriction_details( $video_restriction_details, $guid, $embedded_post_id, $selected_plan_id ) {
284        /**
285         * Filters the video restriction details.
286         *
287         * @param array  $video_restriction_details The restriction details.
288         * @param string $guid The video guid.
289         * @param int    $embedded_post_id The post id.
290         * @param int    $selected_plan_id The selected plan id if applicable.
291         *
292         * @return array
293         */
294        return (array) apply_filters( 'videopress_video_restriction_details', $video_restriction_details, $guid, $embedded_post_id, $selected_plan_id );
295    }
296
297    /**
298     * Returns the default restriction_details for a video.
299     *
300     * @param bool $default_can_access The default auth.
301     *
302     * @return array
303     **/
304    private function default_video_restriction_details( $default_can_access = false ) {
305        $restriction_details = array(
306            'version'              => '1',
307            'provider'             => 'auth',
308            'title'                => __( 'Unauthorized', 'jetpack-videopress-pkg' ),
309            'unauthorized_message' => __( 'Unauthorized', 'jetpack-videopress-pkg' ),
310            'can_access'           => $default_can_access,
311        );
312
313        return $restriction_details;
314    }
315
316    /**
317     * How long the per-post GUID list stays cached.
318     *
319     * @var int
320     */
321    const GUID_CACHE_EXPIRATION = 12 * HOUR_IN_SECONDS;
322
323    /**
324     * Maximum number of synced-pattern (wp_block) refs resolved per scan.
325     *
326     * @var int
327     */
328    const MAX_PATTERN_REFS = 20;
329
330    /**
331     * Build and cache the list of VideoPress GUIDs present in a post.
332     *
333     * Scans the post content for VideoPress video and playlist blocks, shortcodes, and
334     * URLs, then caches the GUID list in a transient for fast lookup during authorization
335     * checks. Synced pattern (core/block) refs are resolved manually: parse_blocks() does
336     * NOT expand them â€” their content lives in the referenced wp_block post and is only
337     * expanded by WordPress at render time.
338     *
339     * @param int $post_id The post ID to scan.
340     * @return array Array of VideoPress GUIDs found in the post.
341     */
342    public static function build_and_cache_post_guids( $post_id ) {
343        if ( empty( $post_id ) ) {
344            return array();
345        }
346
347        $post_id       = absint( $post_id );
348        $transient_key = "videopress_guids_{$post_id}";
349
350        // Check if already cached.
351        $cached_guids = get_transient( $transient_key );
352        if ( false !== $cached_guids ) {
353            return (array) $cached_guids;
354        }
355
356        $post = get_post( $post_id );
357        if ( ! $post instanceof WP_Post || empty( $post->post_content ) ) {
358            set_transient( $transient_key, array(), self::GUID_CACHE_EXPIRATION );
359            return array();
360        }
361
362        $visited_refs = array();
363        $guids        = self::collect_guids_from_content( $post->post_content, $visited_refs );
364
365        // Cache and return unique GUIDs.
366        $unique_guids = array_values( array_unique( array_filter( $guids ) ) );
367        set_transient( $transient_key, $unique_guids, self::GUID_CACHE_EXPIRATION );
368
369        return $unique_guids;
370    }
371
372    /**
373     * Ensure the given rendered GUIDs are present in a post's cached GUID list.
374     *
375     * Called from block render callbacks, where the block has already been expanded by
376     * WordPress (synced patterns, templates, template parts, widget areas…): the render
377     * itself is proof the video is embedded in the page being served for this post, so
378     * the GUID can be added even when the static content scan cannot see it.
379     *
380     * @param int             $post_id The post ID the block is rendering on.
381     * @param string|string[] $guids   The GUID(s) being rendered.
382     */
383    public static function ensure_post_guids_cached( $post_id, $guids ) {
384        $post_id = absint( $post_id );
385        $guids   = array_filter( (array) $guids, 'is_string' );
386        if ( ! $post_id || ! $guids ) {
387            return;
388        }
389
390        $cached  = self::build_and_cache_post_guids( $post_id );
391        $missing = array_diff( $guids, $cached );
392        if ( $missing ) {
393            set_transient(
394                "videopress_guids_{$post_id}",
395                array_values( array_merge( $cached, $missing ) ),
396                self::GUID_CACHE_EXPIRATION
397            );
398        }
399    }
400
401    /**
402     * Collect VideoPress GUIDs from a chunk of post content: blocks (with synced pattern
403     * refs resolved recursively), VideoPress URLs, and legacy shortcodes.
404     *
405     * @param string $content      The post content to scan.
406     * @param array  $visited_refs Accumulator of wp_block ref ids already resolved, keyed by id.
407     * @return array Array of VideoPress GUIDs found.
408     */
409    private static function collect_guids_from_content( $content, &$visited_refs ) {
410        $guids = self::collect_guids_from_blocks( parse_blocks( $content ), $visited_refs );
411
412        // Scan for VideoPress URLs (oEmbed, core/embed, core/video sources).
413        if ( preg_match_all( '#https?://[^\s"\'<>)]+#i', $content, $matches ) ) {
414            foreach ( $matches[0] as $url ) {
415                $guid = Utils::extract_videopress_guid_from_url( $url );
416                if ( $guid ) {
417                    $guids[] = $guid;
418                }
419            }
420        }
421
422        // Scan for [videopress] and [wpvideo] shortcodes.
423        $pattern = get_shortcode_regex( array( 'videopress', 'wpvideo' ) );
424        $count   = preg_match_all( '/' . $pattern . '/', $content, $matches, PREG_SET_ORDER );
425        if ( false !== $count && $count > 0 ) {
426            foreach ( $matches as $match ) {
427                $atts = shortcode_parse_atts( $match[3] );
428                // Only the positional argument identifies the video; named attributes must not satisfy the binding check.
429                if ( is_array( $atts ) && isset( $atts[0] ) && is_string( $atts[0] ) ) {
430                    $guids[] = $atts[0];
431                }
432            }
433        }
434
435        return $guids;
436    }
437
438    /**
439     * Recursively collect VideoPress GUIDs from parsed blocks.
440     *
441     * Handles videopress/video blocks, videopress/playlist entries, and synced patterns:
442     * a core/block ref is resolved by loading the referenced wp_block post and scanning
443     * its content, mirroring render_block_core_block()'s constraints (published, unlocked
444     * wp_block posts only) with a visited guard against cycles.
445     *
446     * @param array $blocks       Array of parsed blocks.
447     * @param array $visited_refs Accumulator of wp_block ref ids already resolved, keyed by id.
448     * @return array Array of VideoPress GUIDs found.
449     */
450    private static function collect_guids_from_blocks( $blocks, &$visited_refs ) {
451        $guids = array();
452
453        foreach ( $blocks as $block ) {
454            $block_name  = $block['blockName'] ?? null;
455            $attrs       = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array();
456            $attr_guid   = $attrs['guid'] ?? null;
457            $attr_videos = $attrs['videos'] ?? null;
458            $attr_ref    = $attrs['ref'] ?? null;
459
460            // A VideoPress video block with a GUID.
461            if ( 'videopress/video' === $block_name && is_string( $attr_guid ) ) {
462                $guids[] = $attr_guid;
463            }
464
465            // A VideoPress playlist block: each entry carries its own GUID.
466            if ( 'videopress/playlist' === $block_name && is_array( $attr_videos ) ) {
467                foreach ( $attr_videos as $entry ) {
468                    if ( is_array( $entry ) && isset( $entry['guid'] ) && is_string( $entry['guid'] ) ) {
469                        $guids[] = $entry['guid'];
470                    }
471                }
472            }
473
474            // A synced pattern: resolve the wp_block ref, which parse_blocks() leaves unexpanded.
475            if ( 'core/block' === $block_name && ! empty( $attr_ref ) ) {
476                $ref = absint( $attr_ref );
477                if ( $ref && ! isset( $visited_refs[ $ref ] ) && count( $visited_refs ) < self::MAX_PATTERN_REFS ) {
478                    $visited_refs[ $ref ] = true;
479
480                    $pattern = get_post( $ref );
481                    if (
482                        $pattern instanceof WP_Post
483                        && 'wp_block' === $pattern->post_type
484                        && 'publish' === $pattern->post_status
485                        && empty( $pattern->post_password )
486                        && ! empty( $pattern->post_content )
487                    ) {
488                        $guids = array_merge( $guids, self::collect_guids_from_content( $pattern->post_content, $visited_refs ) );
489                    }
490                }
491            }
492
493            // Recursively check inner blocks.
494            if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) ) {
495                $guids = array_merge( $guids, self::collect_guids_from_blocks( $block['innerBlocks'], $visited_refs ) );
496            }
497        }
498
499        return $guids;
500    }
501
502    /**
503     * Read the plan ids gating a video guid from the Paid Content block that wraps it in the stored post.
504     *
505     * Playback is authorized outside any render, so the post's blocks are re-parsed here.
506     *
507     * @param int    $embedded_post_id The post the video is embedded in.
508     * @param string $guid             The video guid.
509     *
510     * @return int[]|null Plan ids that gate the guid, an empty array when it is wrapped in a premium-content
511     *                    block that configures no plan, or null when it is not wrapped in one at all.
512     */
513    private function get_required_plan_ids_for_guid( $embedded_post_id, $guid ) {
514        $embedded_post_id = (int) $embedded_post_id;
515        if ( ! $embedded_post_id ) {
516            return null;
517        }
518
519        $post = get_post( $embedded_post_id );
520        if ( ! $post || false === strpos( (string) $post->post_content, 'wp:premium-content/container' ) ) {
521            return null;
522        }
523
524        return $this->find_gating_plan_ids( parse_blocks( $post->post_content ), $guid );
525    }
526
527    /**
528     * Recursively locate the premium-content/container block that wraps the given guid and return its plan ids.
529     *
530     * @param array  $blocks Parsed blocks (parse_blocks() output or an innerBlocks array).
531     * @param string $guid   The video guid to match.
532     *
533     * @return int[]|null Plan ids of the wrapping premium-content block (possibly an empty array when it
534     *                    configures none), or null when no premium-content block wraps the guid.
535     */
536    private function find_gating_plan_ids( $blocks, $guid ) {
537        foreach ( $blocks as $block ) {
538            if ( empty( $block['blockName'] ) ) {
539                continue;
540            }
541
542            // Descend first so the innermost container, the one directly gating the video, wins.
543            if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) ) {
544                $found = $this->find_gating_plan_ids( $block['innerBlocks'], $guid );
545                if ( null !== $found ) {
546                    return $found;
547                }
548            }
549
550            if (
551                is_string( $block['blockName'] ) && 'premium-content/container' === $block['blockName']
552                && $this->container_gates_guid( $block, $guid )
553            ) {
554                return $this->extract_plan_ids( $block['attrs'] ?? array() );
555            }
556        }
557
558        return null;
559    }
560
561    /**
562     * Determine whether a premium-content/container block wraps the given guid.
563     *
564     * Uses the same scan as the per-post GUID cache, so every embed form it recognises counts.
565     *
566     * @param array  $block A parsed premium-content/container block.
567     * @param string $guid  The video guid to match.
568     *
569     * @return bool
570     */
571    private function container_gates_guid( $block, $guid ) {
572        $visited_refs = array();
573
574        return in_array( $guid, self::collect_guids_from_content( serialize_blocks( array( $block ) ), $visited_refs ), true );
575    }
576
577    /**
578     * Normalise a premium-content/container block's plan attributes into a list of plan ids.
579     *
580     * Mirrors the precedence used when rendering the block: the current `selectedPlanIds` array
581     * wins, falling back to the legacy single `selectedPlanId`.
582     *
583     * @param array $attrs The block attributes.
584     *
585     * @return int[] Plan ids, with zero/empty values removed.
586     */
587    private function extract_plan_ids( $attrs ) {
588        if ( isset( $attrs['selectedPlanIds'] ) && is_array( $attrs['selectedPlanIds'] ) ) {
589            return array_values( array_filter( array_map( 'intval', $attrs['selectedPlanIds'] ) ) );
590        }
591
592        if ( isset( $attrs['selectedPlanId'] ) ) {
593            $plan_id = (int) $attrs['selectedPlanId'];
594            return $plan_id ? array( $plan_id ) : array();
595        }
596
597        return array();
598    }
599
600    /**
601     * Check if a post contains a VideoPress GUID, using the cached GUID list for fast lookup.
602     *
603     * Used to prevent the embedded post id â€” which arrives from request input â€” from being
604     * treated as an authorization context when it has no relationship to the requested video.
605     * Matching the attachment id itself is not treated as proof of embedding: attachment ids
606     * are enumerable via the media REST route and would otherwise provide a second path around
607     * this check whenever the attachment has no parent and falls back to the `read` capability.
608     *
609     * @param int    $embedded_post_id The post id to check.
610     * @param string $guid             The video guid to find.
611     *
612     * @return bool
613     */
614    private function post_embeds_videopress_guid_cached( $embedded_post_id, $guid ) {
615        if ( empty( $embedded_post_id ) || empty( $guid ) ) {
616            return false;
617        }
618
619        // Try fast lookup from cache.
620        $transient_key = "videopress_guids_{$embedded_post_id}";
621        $cached_guids  = get_transient( $transient_key );
622
623        if ( false !== $cached_guids ) {
624            return in_array( $guid, (array) $cached_guids, true );
625        }
626
627        // Cache miss: build and cache the GUID list, then check.
628        $guids = self::build_and_cache_post_guids( $embedded_post_id );
629        return in_array( $guid, $guids, true );
630    }
631
632    /**
633     * Determines if the current user can view the provided video. Only ever gets fired if site-wide private videos are enabled.
634     *
635     * Filterable for 3rd party plugins.
636     *
637     * @param string $guid             The video id being checked.
638     * @param int    $embedded_post_id The post id the video is embedded in or 0.
639     * @param int    $selected_plan_id The plan id the earn block this video is embedded in has.
640     */
641    public function is_current_user_authed_for_video( $guid, $embedded_post_id, $selected_plan_id = 0 ) {
642        if ( current_user_can( 'upload_files' ) ) {
643            return $this->filter_is_current_user_authed_for_video( true, $guid, $embedded_post_id );
644        }
645
646        $attachment = false;
647        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
648            $video_info = video_get_info_by_guid( $guid );
649            if ( ! empty( $video_info ) ) {
650                $attachment = get_blog_post( $video_info->blog_id, $video_info->post_id );
651            }
652        } else {
653            $attachment = videopress_get_post_by_guid( $guid );
654        }
655
656        if ( ! $attachment ) {
657            return false;
658        }
659
660        $video_info = video_get_info_by_blogpostid( get_current_blog_id(), $attachment->ID );
661        if ( null === $video_info->guid ) {
662            return false;
663        }
664
665        /*
666         * Default missing privacy_setting to SITE_DEFAULT to avoid an
667         * undefined-property warning and make the site-level fallback explicit.
668         */
669        $privacy_setting = $video_info->privacy_setting ?? VIDEOPRESS_PRIVACY::SITE_DEFAULT;
670
671        $embedded_post_id = (int) $embedded_post_id;
672        if (
673            $embedded_post_id
674            && VIDEOPRESS_PRIVACY::IS_PUBLIC !== $privacy_setting
675            && ! $this->post_embeds_videopress_guid_cached( $embedded_post_id, $guid )
676        ) {
677            $embedded_post_id = 0;
678        }
679
680        $is_user_authed = false;
681
682        // Determine if video is public, private or use site default.
683        switch ( $privacy_setting ) {
684            case VIDEOPRESS_PRIVACY::IS_PUBLIC:
685                $is_user_authed = true;
686                break;
687            case VIDEOPRESS_PRIVACY::IS_PRIVATE:
688                $restriction_details = $this->build_restriction_details( $guid, $embedded_post_id, $selected_plan_id );
689                $is_user_authed      = $restriction_details['can_access'];
690                break;
691            case VIDEOPRESS_PRIVACY::SITE_DEFAULT:
692            default:
693                $is_videopress_private_for_site = Data::get_videopress_videos_private_for_site();
694                $is_user_authed                 = true;
695                if ( $is_videopress_private_for_site ) {
696                    $restriction_details = $this->build_restriction_details( $guid, $embedded_post_id, $selected_plan_id );
697                    $is_user_authed      = $restriction_details['can_access'];
698                }
699        }
700
701        /**
702         * Overrides video view authorization for current user.
703         *
704         * Example of making all videos public:
705         *
706         * function jp_example_override_video_auth( $is_user_authed, $guid ) {
707         *  return true
708         * };
709         * add_filter( 'videopress_is_current_user_authed_for_video', 'jp_example_override_video_auth', 10, 2 );
710         *
711         * @param bool     $is_user_authed   The current user authorization state.
712         * @param string   $guid             The video's unique identifier.
713         * @param int|null $embedded_post_id The post the video is embedded..
714         *
715         * @return bool
716         */
717        return $this->filter_is_current_user_authed_for_video( $is_user_authed, $guid, $embedded_post_id );
718    }
719
720        /**
721         * Overrides video view authorization for current user.
722         *
723         * @param bool     $is_user_authed   The current user authorization state.
724         * @param string   $guid             The video's unique identifier.
725         * @param int|null $embedded_post_id The post the video is embedded..
726         *
727         * @return bool
728         */
729    private function filter_is_current_user_authed_for_video( $is_user_authed, $guid, $embedded_post_id ) {
730        /**
731         * Overrides video view authorization for current user.
732         *
733         * Example of making all videos public:
734         *
735         * function jp_example_override_video_auth( $is_user_authed, $guid ) {
736         *  return true
737         * };
738         * add_filter( 'videopress_is_current_user_authed_for_video', 'jp_example_override_video_auth', 10, 2 );
739         *
740         * @param bool     $is_user_authed   The current user authorization state.
741         * @param string   $guid             The video's unique identifier.
742         * @param int|null $embedded_post_id The post the video is embedded..
743         *
744         * @return bool
745         */
746        return (bool) apply_filters( 'videopress_is_current_user_authed_for_video', $is_user_authed, $guid, $embedded_post_id );
747    }
748
749    /**
750     * Returns the proper blog id depending on Jetpack or WP.com
751     *
752     * @return int the blog id
753     */
754    public function get_videopress_blog_id() {
755        return \Jetpack_Options::get_option( 'id' );
756    }
757}