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