Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.41% covered (success)
91.41%
628 / 687
64.29% covered (warning)
64.29%
18 / 28
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initializer
91.41% covered (success)
91.41%
628 / 687
64.29% covered (warning)
64.29%
18 / 28
257.07
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 update_init_options
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 should_initialize_admin_ui
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 unconditional_initialization
92.00% covered (success)
92.00%
23 / 25
0.00% covered (danger)
0.00%
0 / 1
6.02
 should_include_utilities
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 prepare_poster_url_for_inline_style
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 active_initialization
96.00% covered (success)
96.00%
24 / 25
0.00% covered (danger)
0.00%
0 / 1
3
 register_oembed_providers
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 video_enqueue_bridge_when_oembed_present
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 register_videopress_blocks
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 register_videopress_all_playlists_block
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 render_videopress_video_block
92.74% covered (success)
92.74%
115 / 124
0.00% covered (danger)
0.00%
0 / 1
33.42
 register_videopress_video_block
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
90
 register_videopress_playlist_block
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
7
 register_videopress_latest_videos_playlist_block
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
6.01
 render_videopress_latest_videos_playlist_block
97.22% covered (success)
97.22%
35 / 36
0.00% covered (danger)
0.00%
0 / 1
19
 render_video_browser_controls
100.00% covered (success)
100.00%
63 / 63
100.00% covered (success)
100.00%
1 / 1
12
 render_video_browser_pagination
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
5
 sanitize_playlist_entries
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
14
 playlist_embed_url
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
4
 playlist_timecode
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 playlist_runtime_label
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
5
 playlist_resolution_label
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 render_videopress_playlist_block
100.00% covered (success)
100.00%
217 / 217
100.00% covered (success)
100.00%
1 / 1
63
 enqueue_videopress_iframe_api_script
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 maybe_pre_oembed_inline_player
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 maybe_render_oembed_inline_player
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 render_inline_player_for_url
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * The initializer class for the videopress package
4 *
5 * @package automattic/jetpack-videopress
6 */
7
8namespace Automattic\Jetpack\VideoPress;
9
10/**
11 * Initialized the VideoPress package
12 */
13class Initializer {
14
15    /**
16     * Bounds of the Latest Videos Playlist block's "Number of videos" setting;
17     * the editor control uses the same range.
18     */
19    const LATEST_VIDEOS_PLAYLIST_MIN_COUNT     = 1;
20    const LATEST_VIDEOS_PLAYLIST_MAX_COUNT     = 20;
21    const LATEST_VIDEOS_PLAYLIST_DEFAULT_COUNT = 5;
22    const LATEST_VIDEOS_PLAYLIST_MAX_PAGED     = 48;
23
24    const JETPACK_VIDEOPRESS_IFRAME_API_HANDLER = 'jetpack-videopress-iframe-api';
25
26    /**
27     * Initialization optinos
28     *
29     * @var array
30     */
31    protected static $init_options = array();
32
33    /**
34     * Initializes the VideoPress package
35     *
36     * This method is called by Config::ensure.
37     *
38     * @return void
39     */
40    public static function init() {
41        if ( ! did_action( 'videopress_init' ) ) {
42
43            self::unconditional_initialization();
44
45            if ( Status::is_active() ) {
46                self::active_initialization();
47            } elseif ( self::should_initialize_admin_ui() ) {
48                // Keep "Jetpack > VideoPress" in the menu when the module is not
49                // active, linking to the My Jetpack interstitial to activate it.
50                Admin_UI::init_inactive_menu();
51            }
52        }
53
54        /**
55         * Fires after the VideoPress package is initialized
56         *
57         * @since 0.1.1
58         */
59        do_action( 'videopress_init' );
60    }
61
62    /**
63     * Update the initialization options
64     *
65     * This method is called by the Config class
66     *
67     * @param array $options The initialization options.
68     * @return void
69     */
70    public static function update_init_options( array $options ) {
71        if ( empty( $options['admin_ui'] ) || self::should_initialize_admin_ui() ) { // do not overwrite if already set to true.
72            return;
73        }
74
75        self::$init_options['admin_ui'] = $options['admin_ui'];
76    }
77
78    /**
79     * Checks the initialization options and returns whether the admin_ui should be initialized or not
80     *
81     * @return boolean
82     */
83    public static function should_initialize_admin_ui() {
84        return isset( self::$init_options['admin_ui'] ) && true === self::$init_options['admin_ui'];
85    }
86
87    /**
88     * Initialize VideoPress features that should be initialized whenever VideoPress is present, even if the module is not active
89     *
90     * @return void
91     */
92    private static function unconditional_initialization() {
93        if ( self::should_include_utilities() ) {
94            require_once __DIR__ . '/utility-functions.php';
95        }
96
97        if ( ! ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) {
98            add_filter( 'rest_post_dispatch', array( Upload_Session::class, 'refresh_media_response' ), 10, 3 );
99        }
100
101        // Set up package version hook.
102        add_filter( 'jetpack_package_versions', __NAMESPACE__ . '\Package_Version::send_package_version_to_tracker' );
103
104        /*
105         * Keep the videopress_guid attachment meta out of reach of the
106         * user-facing meta write APIs (Custom Fields, XML-RPC set_custom_fields,
107         * the WordPress.com JSON API metadata op, REST). The post <-> guid
108         * mapping is what the VideoPress meta and poster endpoints authorize
109         * against, so a writable guid would let a caller point an object they
110         * can edit at somebody else's video and still pass the edit_post check.
111         *
112         * These auth_* filters are consulted by map_meta_cap() for the
113         * add/edit/delete_post_meta capabilities only, so unlike marking the key
114         * protected they leave is_protected_meta() false and meta_key queries
115         * against the WordPress.com JSON API keep working. VideoPress writes the
116         * mapping itself with update_post_meta(), which does not consult
117         * capabilities, so uploads and transcoding are unaffected.
118         *
119         * The subtype-specific filter covers attachments; the generic one covers
120         * calls made before a subtype can be resolved.
121         */
122        add_filter( 'auth_post_meta_videopress_guid_for_attachment', '__return_false' );
123        add_filter( 'auth_post_meta_videopress_guid', '__return_false' );
124
125        Module_Control::init();
126
127        /*
128         * The WPCOM REST API v2 endpoints only register routes/fields on REST
129         * init, so defer constructing them (and autoloading their classes) until
130         * a REST request is actually served. Registered on both REST init hooks
131         * so the routes remain available in every context they were before, and
132         * guarded so the endpoints are instantiated only once per request.
133         */
134        $register_rest_api_v2_endpoints = static function () {
135            static $registered = false;
136            if ( $registered ) {
137                return;
138            }
139            $registered = true;
140            new WPCOM_REST_API_V2_Endpoint_VideoPress();
141            new WPCOM_REST_API_V2_Endpoint_VideoPress_Caption_Tracks();
142            new WPCOM_REST_API_V2_Attachment_VideoPress_Field();
143            new WPCOM_REST_API_V2_Attachment_VideoPress_Data();
144            new WPCOM_REST_API_V2_Endpoint_VideoPress_Edits();
145        };
146        add_action( 'rest_api_init', $register_rest_api_v2_endpoints, 0 );
147        add_action( 'restapi_theme_init', $register_rest_api_v2_endpoints, 0 );
148
149        if ( is_admin() ) {
150            AJAX::init();
151        } else {
152            require_once __DIR__ . '/class-block-replacement.php';
153            Block_Replacement::init();
154        }
155    }
156
157    /**
158     * This avoids conflicts when running VideoPress plugin with older versions of the Jetpack plugin
159     *
160     * On version 11.3-a.7 utility functions include were removed from the plugin and it is safe to include it from the package
161     *
162     * @return boolean
163     */
164    private static function should_include_utilities() {
165        if ( ! class_exists( 'Jetpack' ) || ! defined( 'JETPACK__VERSION' ) ) {
166            return true;
167        }
168
169        return version_compare( JETPACK__VERSION, '11.3-a.7', '>=' );
170    }
171
172    /**
173     * Prepare a poster URL for a quoted CSS url() inside an HTML attribute.
174     *
175     * @param mixed $poster Poster URL.
176     * @return string Sanitized and HTML-encoded poster URL, or an empty string.
177     */
178    private static function prepare_poster_url_for_inline_style( $poster ) {
179        if ( ! is_string( $poster ) || '' === $poster ) {
180            return '';
181        }
182
183        /*
184         * Decode one layer so ordinarily encoded URLs retain their semantics. Any
185         * remaining entities are encoded again below and stay inert after the HTML
186         * parser performs its single decoding pass.
187         */
188        $poster_url = esc_url_raw( html_entity_decode( $poster, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) );
189        if ( '' === $poster_url ) {
190            return '';
191        }
192
193        /*
194         * Force existing character references to be encoded. esc_attr() preserves
195         * them, but this value crosses from an HTML attribute into a CSS string.
196         */
197        return htmlspecialchars( $poster_url, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8', true );
198    }
199
200    /**
201     * Initialize VideoPress features that should be initialized only when the module is active
202     *
203     * @return void
204     */
205    private static function active_initialization() {
206        Attachment_Handler::init();
207        Jwt_Token_Bridge::init();
208        Caption_Tracks::init();
209        Initial_State::init();
210        XMLRPC::init();
211        Block_Editor_Content::init();
212        Channel::init();
213        Playlist_Index::init();
214        Analytics_Dashboard::init();
215
216        /*
217         * These endpoints only add their routes on REST init, so defer calling
218         * init() (and autoloading the endpoint classes) until a REST request is
219         * served. Priority 0 ensures the routes still register before the
220         * default-priority rest_api_init handlers run. Class-name strings are
221         * used so the classes are not autoloaded on non-REST requests.
222         */
223        foreach (
224            array(
225                Uploader_Rest_Endpoints::class,
226                Rest_Controller::class,
227                VideoPress_Rest_Api_V1_Stats::class,
228                VideoPress_Rest_Api_V1_Site::class,
229                VideoPress_Rest_Api_V1_Settings::class,
230                VideoPress_Rest_Api_V1_Features::class,
231            ) as $rest_endpoint
232        ) {
233            add_action( 'rest_api_init', array( $rest_endpoint, 'init' ), 0 );
234        }
235        self::register_oembed_providers();
236
237        // In inline mode a VideoPress URL never needs the oEmbed round trip: skip
238        // the fetch, and swap iframes already cached in post meta for a placeholder.
239        add_filter( 'pre_oembed_result', array( __CLASS__, 'maybe_pre_oembed_inline_player' ), 10, 2 );
240        add_filter( 'embed_oembed_html', array( __CLASS__, 'maybe_render_oembed_inline_player' ), 5, 4 );
241
242        // Enqueuethe VideoPress Iframe API script in the front-end.
243        add_filter( 'embed_oembed_html', array( __CLASS__, 'enqueue_videopress_iframe_api_script' ), 10, 4 );
244
245        if ( self::should_initialize_admin_ui() ) {
246            Admin_UI::init();
247        }
248
249        Divi::init();
250    }
251
252    /**
253     * Explicitly register VideoPress oembed provider for patterns not supported by core
254     *
255     * @return void
256     */
257    public static function register_oembed_providers() {
258        $host = rawurlencode( home_url() );
259        // videopress.com/v is already registered in core.
260        // By explicitly declaring the provider here, we can speed things up by not relying on oEmbed discovery.
261        wp_oembed_add_provider( '#^https?://video.wordpress.com/v/.*#', 'https://public-api.wordpress.com/oembed/?for=' . $host, true );
262        // This is needed as it's not supported in oEmbed discovery.
263        wp_oembed_add_provider( '|^https?://v\.wordpress\.com/([a-zA-Z\d]{8})(.+)?$|i', 'https://public-api.wordpress.com/oembed/?for=' . $host, true ); // phpcs:ignore WordPress.WP.CapitalPDangit.MisspelledInText
264
265        add_filter( 'embed_oembed_html', array( __CLASS__, 'video_enqueue_bridge_when_oembed_present' ), 10, 4 );
266    }
267
268    /**
269     * Enqueues VideoPress token bridge when a VideoPress oembed is present on the current page.
270     *
271     * @param string|false $cache   The cached HTML result, stored in post meta.
272     * @param string       $url     The attempted embed URL.
273     * @param array        $attr    An array of shortcode attributes.
274     * @param int          $post_ID Post ID.
275     *
276     * @return string|false
277     */
278    public static function video_enqueue_bridge_when_oembed_present( $cache, $url, $attr, $post_ID = null ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
279        if ( Utils::is_videopress_url( $url ) ) {
280            Jwt_Token_Bridge::enqueue_jwt_token_bridge();
281        }
282
283        return $cache;
284    }
285
286    /**
287     * Register all VideoPress blocks
288     *
289     * @return void
290     */
291    public static function register_videopress_blocks() {
292        // Register VideoPress Video block.
293        self::register_videopress_video_block();
294
295        // Register Video Playlist block.
296        self::register_videopress_playlist_block();
297
298        // Register Latest Videos Playlist block.
299        self::register_videopress_latest_videos_playlist_block();
300
301        // Register All Playlists block.
302        self::register_videopress_all_playlists_block();
303
304        // Register the playlist block's `source` and, where the channel feature is enabled, the channel blocks.
305        Channel_Blocks::register();
306    }
307
308    /**
309     * Register the All Playlists block, which lists the site's Video Playlist
310     * blocks from the playlist index.
311     *
312     * @param string|null $metadata_file Path to the block.json metadata file. Defaults to the
313     *                                   package build output; tests can point it at a fixture.
314     *
315     * @return void
316     */
317    public static function register_videopress_all_playlists_block( $metadata_file = null ) {
318        All_Playlists_Block::register( $metadata_file );
319    }
320
321    /**
322     * VideoPress video block render method
323     *
324     * @global \WP_Embed $wp_embed WordPress embed handler.
325     *
326     * @param array     $block_attributes Block attributes.
327     * @param string    $content          Current block markup.
328     * @param \WP_Block $block            Current block.
329     *
330     * @return string Block markup.
331     */
332    public static function render_videopress_video_block( $block_attributes, $content, $block ) {
333        global $wp_embed;
334
335        // Pre-build and cache the GUID list for this post to optimize authorization checks,
336        // and record the GUID actually being rendered: by render time WordPress has expanded
337        // synced patterns, templates, and template parts, so this covers embedding contexts
338        // the static content scan cannot see.
339        $post_id = $block->context['postId'] ?? get_the_ID();
340        if ( ! empty( $post_id ) && isset( $block_attributes['guid'] ) && is_string( $block_attributes['guid'] ) ) {
341            Access_Control::ensure_post_guids_cached( absint( $post_id ), $block_attributes['guid'] );
342        } elseif ( ! empty( $post_id ) ) {
343            Access_Control::build_and_cache_post_guids( absint( $post_id ) );
344        }
345
346        // CSS classes.
347        $align        = $block_attributes['align'] ?? null;
348        $align_class  = $align ? ' align' . $align : '';
349        $custom_class = isset( $block_attributes['className'] ) ? ' ' . $block_attributes['className'] : '';
350        $classes      = 'wp-block-jetpack-videopress jetpack-videopress-player' . $custom_class . $align_class;
351
352        // Inline style.
353        $style     = '';
354        $max_width = isset( $block_attributes['maxWidth'] ) && is_string( $block_attributes['maxWidth'] )
355            ? trim( $block_attributes['maxWidth'] )
356            : '';
357
358        // maxWidth is rendered into an inline style. Accept only a plain CSS length
359        // or percentage so the value stays a single, well-formed declaration;
360        // anything else is dropped and the block renders at full width (as with the
361        // "100%" default).
362        if ( '' !== $max_width && '100%' !== $max_width
363            && preg_match( '/^\d+(\.\d+)?(px|%|em|rem|vw|vh|vmin|vmax|ch|ex|cm|mm|in|pt|pc|q)$/i', $max_width )
364        ) {
365            $style    = sprintf( 'max-width: %s;', $max_width );
366            $classes .= ' wp-block-jetpack-videopress--has-max-width';
367        }
368
369        /*
370         * <figcaption /> element
371         * Caption is stored into the block attributes,
372         * but also it was stored into the <figcaption /> element,
373         * meaning that it could be stored in two different places.
374         */
375        $figcaption = '';
376
377        // Caption from block attributes.
378        $caption = $block_attributes['caption'] ?? null;
379
380        /*
381         * If the caption is not stored into the block attributes,
382         * try to get it from the <figcaption /> element.
383         */
384        if ( null === $caption ) {
385            preg_match( '/<figcaption>(.*?)<\/figcaption>/', $content, $matches );
386            $caption = $matches[1] ?? null;
387        }
388
389        // If we have a caption, create the <figcaption /> element.
390        if ( null !== $caption ) {
391            $figcaption = sprintf( '<figcaption>%s</figcaption>', wp_kses_post( $caption ) );
392        }
393
394        // Custom anchor from block content.
395        $id_attribute = '';
396
397        // Try to get the custom anchor from the block attributes.
398        if ( isset( $block_attributes['anchor'] ) && $block_attributes['anchor'] ) {
399            $id_attribute = sprintf( 'id="%s"', esc_attr( $block_attributes['anchor'] ) );
400        } elseif ( preg_match( '/<figure[^>]*id="([^"]+)"/', $content, $matches ) ) {
401            // Otherwise, try to get the custom anchor from the <figure /> element.
402            $id_attribute = sprintf( 'id="%s"', esc_attr( $matches[1] ) );
403        }
404
405        // Preview On Hover data.
406        $is_poh_enabled =
407            isset( $block_attributes['posterData']['previewOnHover'] ) &&
408            $block_attributes['posterData']['previewOnHover'];
409
410        $autoplay = $block_attributes['autoplay'] ?? false;
411        $controls = $block_attributes['controls'] ?? false;
412        $poster   = $block_attributes['posterData']['url'] ?? null;
413
414        $preview_on_hover = '';
415
416        if ( $is_poh_enabled ) {
417            $preview_on_hover = array(
418                'previewAtTime'       => $block_attributes['posterData']['previewAtTime'],
419                'previewLoopDuration' => $block_attributes['posterData']['previewLoopDuration'],
420                'autoplay'            => $autoplay,
421                'showControls'        => $controls,
422            );
423
424            // Create inline style in case video has a custom poster.
425            $inline_style = '';
426            $poster_url   = self::prepare_poster_url_for_inline_style( $poster );
427            if ( $poster_url ) {
428                // Emit the poster URL as a double-quoted CSS string so it stays
429                // contained within url() and cannot affect the surrounding style.
430                $inline_style = sprintf(
431                    'style="background-image: url(&quot;%s&quot;); background-size: cover; background-position: center center;"',
432                    $poster_url
433                );
434            }
435
436            // Expose the preview on hover data to the client.
437            $preview_on_hover = sprintf(
438                '<div class="jetpack-videopress-player__overlay" %s></div><script type="application/json">%s</script>',
439                $inline_style,
440                wp_json_encode( $preview_on_hover, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP )
441            );
442
443            // Set `autoplay` and `muted` attributes to the video element.
444            $block_attributes['autoplay'] = true;
445            $block_attributes['muted']    = true;
446        }
447
448        $figure_template = '
449        <figure class="%1$s" style="%2$s" %3$s>
450            %4$s
451            %5$s
452            %6$s
453        </figure>
454        ';
455
456        // VideoPress URL.
457        $guid           = $block_attributes['guid'] ?? null;
458        $videopress_url = Utils::get_video_press_url( $guid, $block_attributes );
459
460        $video_wrapper         = '';
461        $video_wrapper_classes = 'jetpack-videopress-player__wrapper';
462
463        // Preview on hover drives the player through the iframe API, so it keeps the iframe.
464        if ( $guid && ! $is_poh_enabled && Inline_Player::is_enabled() ) {
465            $video_wrapper = sprintf(
466                '<div class="%s">%s</div>',
467                $video_wrapper_classes,
468                Inline_Player::render(
469                    $guid,
470                    Inline_Player::get_player_options( $block_attributes ),
471                    $block_attributes['videoRatio'] ?? null,
472                    array(
473                        'poster' => Inline_Player::get_poster_url( $guid, $block_attributes ),
474                        'title'  => $block_attributes['title'] ?? '',
475                    )
476                )
477            );
478        } elseif ( $videopress_url ) {
479            $videopress_url = wp_kses_post( $videopress_url );
480
481            /*
482             * Provide a fallback iframe for when the oEmbed endpoint fails, e.g.
483             * when the VideoPress backend isn't ready for a freshly uploaded video.
484             * This prevents the published page from showing a bare link.
485             */
486            $fallback = function ( $output, $url ) use ( $videopress_url ) {
487                $decoded_url = html_entity_decode( $videopress_url, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 );
488                if ( $decoded_url !== $url ) {
489                    return $output;
490                }
491
492                return sprintf(
493                    '<iframe title="%1$s" aria-label="%1$s" src="%2$s" width="640" height="360" allowfullscreen data-resize-to-parent="true" allow="clipboard-write; presentation"></iframe>',
494                    esc_attr__( 'VideoPress Video Player', 'jetpack-videopress-pkg' ),
495                    esc_url( preg_replace( '#/v/#', '/embed/', $url, 1 ) )
496                );
497            };
498
499            add_filter( 'embed_maybe_make_link', $fallback, 10, 2 );
500            $oembed_html = apply_filters( 'video_embed_html', $wp_embed->shortcode( array(), $videopress_url ) );
501            remove_filter( 'embed_maybe_make_link', $fallback );
502
503            $video_wrapper = sprintf(
504                '<div class="%s">%s %s</div>',
505                $video_wrapper_classes,
506                $preview_on_hover,
507                $oembed_html
508            );
509
510            /*
511             * Self-heal failed oEmbed cache for VideoPress URLs.
512             *
513             * When the VideoPress backend isn't ready for a freshly uploaded video,
514             * WordPress caches '{{unknown}}' in post meta with a TTL that is too long
515             * for this use case. Clear recent failures so the next page render retries
516             * oEmbed discovery, keeping the fallback iframe above temporary.
517             */
518            $post_id = $block->context['postId'] ?? get_the_ID();
519
520            if ( $post_id ) {
521                $key_suffix   = md5( $videopress_url . serialize( wp_embed_defaults( $videopress_url ) ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Matching WP_Embed cache key format.
522                $oembed_value = get_post_meta( $post_id, '_oembed_' . $key_suffix, true );
523                $oembed_time  = (int) get_post_meta( $post_id, '_oembed_time_' . $key_suffix, true );
524
525                /*
526                 * Only clear the '{{unknown}}' cache entry when it is recent, to avoid
527                 * disabling WordPress's oEmbed backoff for persistent provider failures.
528                 */
529                if (
530                    '{{unknown}}' === $oembed_value
531                    && ( ! $oembed_time || ( time() - $oembed_time ) < MINUTE_IN_SECONDS )
532                ) {
533                    delete_post_meta( $post_id, '_oembed_' . $key_suffix );
534                    delete_post_meta( $post_id, '_oembed_time_' . $key_suffix );
535                }
536            }
537        }
538
539        // Get premium content from block context.
540        $premium_block_plan_id    = isset( $block->context['premium-content/planId'] ) ? intval( $block->context['premium-content/planId'] ) : 0;
541        $is_premium_content_child = isset( $block->context['isPremiumContentChild'] ) ? (bool) $block->context['isPremiumContentChild'] : false;
542        $maybe_premium_script     = '';
543        if ( $is_premium_content_child && is_string( $guid ) ) {
544            Access_Control::instance()->set_guid_subscription( $guid, $premium_block_plan_id );
545            $escaped_guid         = wp_json_encode( $guid, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
546            $script_content       = "if ( ! window.__guidsToPlanIds ) { window.__guidsToPlanIds = {}; }; window.__guidsToPlanIds[$escaped_guid] = $premium_block_plan_id;";
547            $maybe_premium_script = '<script>' . $script_content . '</script>';
548        }
549
550        // $id_attribute, $video_wrapper, $figcaption properly escaped earlier in the code.
551        return sprintf(
552            $figure_template,
553            esc_attr( $classes ),
554            esc_attr( $style ),
555            $id_attribute,
556            $video_wrapper,
557            $figcaption,
558            $maybe_premium_script
559        );
560    }
561
562    /**
563     * Register the VideoPress block editor block,
564     * AKA "VideoPress Block v6".
565     *
566     * @return void
567     */
568    public static function register_videopress_video_block() {
569        /*
570         * If only Jetpack is active, and if the VideoPress module is not active,
571         * we can register the block just to display a placeholder to turn on the module.
572         * That invitation is only useful for admins though.
573         */
574        if (
575            Status::is_jetpack_plugin_without_videopress_module_active()
576            && ! Status::is_standalone_plugin_active()
577            && ! current_user_can( 'jetpack_activate_modules' )
578        ) {
579            return;
580        }
581
582        $videopress_video_metadata_file        = __DIR__ . '/../build/block-editor/blocks/video/block.json';
583        $videopress_video_metadata_file_exists = file_exists( $videopress_video_metadata_file );
584        if ( ! $videopress_video_metadata_file_exists ) {
585            return;
586        }
587
588        $videopress_video_metadata = json_decode(
589            // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
590            file_get_contents( $videopress_video_metadata_file )
591        );
592
593        // Pick the block name straight from the block metadata .json file.
594        $videopress_video_block_name = $videopress_video_metadata->name;
595
596        // Is the block already registered?
597        $is_block_registered = \WP_Block_Type_Registry::get_instance()->is_registered( $videopress_video_block_name );
598
599        // Do not register if the block is already registered.
600        if ( $is_block_registered ) {
601            return;
602        }
603
604        $registration = register_block_type(
605            $videopress_video_metadata_file,
606            array(
607                'render_callback'       => array( __CLASS__, 'render_videopress_video_block' ),
608                'render_email_callback' => array( Video_Block_Email_Renderer::class, 'render' ),
609                'uses_context'          => array( 'premium-content/planId', 'isPremiumContentChild', 'selectedPlanId' ),
610            )
611        );
612
613        // Do not enqueue scripts if the block could not be registered.
614        if ( empty( $registration ) || empty( $registration->editor_script_handles ) ) {
615            return;
616        }
617
618        // Extensions use Connection_Initial_State::render_script with script handle as parameter.
619        if ( is_array( $registration->editor_script_handles ) ) {
620            $script_handle = $registration->editor_script_handles[0];
621        } else {
622            $script_handle = $registration->editor_script_handles;
623        }
624
625        // Register and enqueue scripts used by the VideoPress video block.
626        Block_Editor_Extensions::init( $script_handle );
627    }
628
629    /**
630     * Register the Video Playlist block.
631     *
632     * @param string|null $metadata_file Path to the block.json metadata file. Defaults to the
633     *                                   package build output; tests can point it at a fixture.
634     *
635     * @return void
636     */
637    public static function register_videopress_playlist_block( $metadata_file = null ) {
638        /*
639         * Unlike the video block, the playlist block has no "activate the module"
640         * placeholder, so it is only registered where VideoPress can play videos.
641         */
642        if (
643            Status::is_jetpack_plugin_without_videopress_module_active()
644            && ! Status::is_standalone_plugin_active()
645        ) {
646            return;
647        }
648
649        if ( null === $metadata_file ) {
650            $metadata_file = __DIR__ . '/../build/block-editor/blocks/playlist/block.json';
651        }
652
653        if ( ! file_exists( $metadata_file ) ) {
654            return;
655        }
656
657        $metadata = json_decode(
658            // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
659            file_get_contents( $metadata_file )
660        );
661
662        if ( empty( $metadata->name )
663            || \WP_Block_Type_Registry::get_instance()->is_registered( $metadata->name )
664        ) {
665            return;
666        }
667
668        register_block_type(
669            $metadata_file,
670            array(
671                'render_callback' => array( __CLASS__, 'render_videopress_playlist_block' ),
672            )
673        );
674    }
675
676    /**
677     * Register the Latest Videos Playlist block.
678     *
679     * It reuses the Video Playlist block's registered view script and styles, so
680     * it is only registered once that block is. Its inner Video Playlist block is
681     * the editor canvas only: the front end renders the newest videos fresh.
682     *
683     * @param string|null $metadata_file Path to the block.json metadata file. Defaults to the
684     *                                   package build output; tests can point it at a fixture.
685     *
686     * @return void
687     */
688    public static function register_videopress_latest_videos_playlist_block( $metadata_file = null ) {
689        if ( ! \WP_Block_Type_Registry::get_instance()->is_registered( 'videopress/playlist' ) ) {
690            return;
691        }
692
693        if ( null === $metadata_file ) {
694            $metadata_file = __DIR__ . '/../build/block-editor/blocks/latest-videos-playlist/block.json';
695        }
696
697        if ( ! file_exists( $metadata_file ) ) {
698            return;
699        }
700
701        $metadata = json_decode(
702            // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
703            file_get_contents( $metadata_file )
704        );
705
706        if ( empty( $metadata->name )
707            || \WP_Block_Type_Registry::get_instance()->is_registered( $metadata->name )
708        ) {
709            return;
710        }
711
712        register_block_type(
713            $metadata_file,
714            array(
715                'render_callback'   => array( __CLASS__, 'render_videopress_latest_videos_playlist_block' ),
716                'skip_inner_blocks' => true,
717            )
718        );
719    }
720
721    /**
722     * Latest Videos Playlist block render callback: the newest VideoPress videos
723     * on the site, rendered by the Video Playlist block's callback.
724     *
725     * @param array          $block_attributes Block attributes.
726     * @param string         $content          Current block markup, unused: the inner block is never rendered.
727     * @param \WP_Block|null $block            Current block.
728     *
729     * @return string Block markup, or an empty string when the site has no VideoPress videos.
730     */
731    public static function render_videopress_latest_videos_playlist_block( $block_attributes, $content = '', $block = null ) {
732        $order      = isset( $block_attributes['orderBy'] ) && in_array( $block_attributes['orderBy'], Channel_Data::BROWSE_SORTS, true ) ? $block_attributes['orderBy'] : 'newest';
733        $controls   = ! empty( $block_attributes['showBrowseControls'] );
734        $paginated  = isset( $block_attributes['pagination'] ) && 'numbered' === $block_attributes['pagination'];
735        $exclude    = ! empty( $block_attributes['excludeCurrent'] ) ? array_filter( array( Channel::queried_guid() ) ) : array();
736        $show_meta  = ! empty( $block_attributes['showMeta'] );
737        $max_count  = $paginated ? self::LATEST_VIDEOS_PLAYLIST_MAX_PAGED : self::LATEST_VIDEOS_PLAYLIST_MAX_COUNT;
738        $count      = isset( $block_attributes['count'] ) && is_numeric( $block_attributes['count'] )
739            ? (int) $block_attributes['count']
740            : self::LATEST_VIDEOS_PLAYLIST_DEFAULT_COUNT;
741        $count      = max( self::LATEST_VIDEOS_PLAYLIST_MIN_COUNT, min( $max_count, $count ) );
742        $is_browsed = 'newest' !== $order || $controls || $paginated || $exclude || $show_meta;
743
744        // Dynamic playlists have no title of their own, so no heading either.
745        unset( $block_attributes['playlistTitle'], $block_attributes['showPlaylistTitle'] );
746
747        if ( ! $is_browsed ) {
748            $block_attributes['videos'] = Data::get_latest_videopress_playlist_entries( $count );
749            return self::render_videopress_playlist_block( $block_attributes, '', $block );
750        }
751
752        $state   = Channel_Data::browse_request( $controls, $paginated, $order );
753        $results = Channel_Data::browse( $state, $count, $exclude, $show_meta );
754
755        $block_attributes['videos'] = $show_meta
756            ? $results['entries']
757            : array_map(
758                function ( $entry ) {
759                    return array_diff_key( $entry, array_flip( array( 'views', 'publishedAt' ) ) );
760                },
761                $results['entries']
762            );
763        $before                     = $controls ? self::render_video_browser_controls( $state, $results, $count ) : '';
764        $after                      = $paginated && $results['pages'] > 1 ? self::render_video_browser_pagination( $results['page'], $results['pages'] ) : '';
765        $markup                     = self::render_videopress_playlist_block( $block_attributes, '', $block, $before, $after );
766
767        if ( '' === $markup && $controls ) {
768            // Keep the controls when nothing matches, so the filters can be changed back.
769            $markup = sprintf(
770                '<figure %1$s>%2$s<p class="videopress-video-browser__empty">%3$s</p></figure>',
771                get_block_wrapper_attributes( array( 'class' => 'videopress-playlist is-layout-' . esc_attr( $block_attributes['layout'] ?? 'grid' ) . ' is-empty' ) ),
772                $before,
773                esc_html__( 'No videos match these filters.', 'jetpack-videopress-pkg' )
774            );
775        }
776
777        return $markup;
778    }
779
780    /**
781     * The Videos page controls: search, sort and length, submitted as a GET form.
782     *
783     * @param array $state    Browsing state from Channel_Data::browse_request().
784     * @param array $results  Page from Channel_Data::browse().
785     * @param int   $per_page Page size.
786     *
787     * @return string Markup.
788     */
789    private static function render_video_browser_controls( array $state, array $results, $per_page ) {
790        $own_args = array( Channel_Data::QUERY_ARG_SEARCH, Channel_Data::QUERY_ARG_SORT, Channel_Data::QUERY_ARG_LENGTH, Channel_Data::QUERY_ARG_PAGE );
791        $action   = strtok( remove_query_arg( $own_args ), '?' );
792
793        // A GET form drops the action's query string, so the page's other arguments ride along as fields.
794        $hidden = '';
795        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only echoed back as hidden fields.
796        foreach ( $_GET as $name => $value ) {
797            if ( is_string( $name ) && is_string( $value ) && ! in_array( $name, $own_args, true ) ) {
798                $hidden .= sprintf( '<input type="hidden" name="%1$s" value="%2$s" />', esc_attr( $name ), esc_attr( sanitize_text_field( wp_unslash( $value ) ) ) );
799            }
800        }
801
802        $sorts        = array(
803            'newest'  => __( 'Latest', 'jetpack-videopress-pkg' ),
804            'popular' => __( 'Popular', 'jetpack-videopress-pkg' ),
805            'oldest'  => __( 'Oldest', 'jetpack-videopress-pkg' ),
806        );
807        $sort_buttons = '';
808        foreach ( $sorts as $value => $label ) {
809            $is_current    = $value === $state['sort'];
810            $sort_buttons .= sprintf(
811                '<button type="submit" class="videopress-video-browser__sort%1$s" name="%2$s" value="%3$s" aria-pressed="%4$s">%5$s</button>',
812                $is_current ? ' is-current' : '',
813                esc_attr( Channel_Data::QUERY_ARG_SORT ),
814                esc_attr( 'newest' === $value ? 'latest' : $value ),
815                $is_current ? 'true' : 'false',
816                esc_html( $label )
817            );
818        }
819
820        $lengths = array(
821            'any'   => __( 'Any length', 'jetpack-videopress-pkg' ),
822            'short' => __( 'Under 20 min', 'jetpack-videopress-pkg' ),
823            'mid'   => __( '20 to 45 min', 'jetpack-videopress-pkg' ),
824            'long'  => __( 'Over 45 min', 'jetpack-videopress-pkg' ),
825        );
826        $options = '';
827        foreach ( $lengths as $value => $label ) {
828            $options .= sprintf( '<option value="%1$s"%2$s>%3$s</option>', esc_attr( $value ), selected( $value, $state['length'], false ), esc_html( $label ) );
829        }
830
831        if ( $results['total'] > 0 ) {
832            $summary = sprintf(
833                /* translators: 1: first video shown. 2: last video shown. 3: number of matching videos. */
834                _n( 'Showing %1$s–%2$s of %3$s video', 'Showing %1$s–%2$s of %3$s videos', $results['total'], 'jetpack-videopress-pkg' ),
835                number_format_i18n( $results['start'] + 1 ),
836                number_format_i18n( min( $results['start'] + $per_page, $results['total'] ) ),
837                number_format_i18n( $results['total'] )
838            );
839        } else {
840            $summary = __( '0 videos', 'jetpack-videopress-pkg' );
841        }
842
843        return sprintf(
844            '<form class="videopress-video-browser" method="get" action="%1$s" role="search">%2$s' .
845                '<input type="hidden" name="%3$s" value="%4$s" />' .
846                '<input type="search" class="videopress-video-browser__search" name="%5$s" value="%6$s" placeholder="%7$s" aria-label="%7$s" />' .
847                '<button type="submit" class="videopress-video-browser__submit">%8$s</button>' .
848                '<div class="videopress-video-browser__sorts" role="group" aria-label="%9$s">%10$s</div>' .
849                '<select class="videopress-video-browser__length" name="%11$s" aria-label="%12$s">%13$s</select>' .
850            '</form>' .
851            '<p class="videopress-video-browser__summary">%14$s</p>',
852            esc_url( $action ),
853            $hidden,
854            esc_attr( Channel_Data::QUERY_ARG_SORT ),
855            esc_attr( 'newest' === $state['sort'] ? 'latest' : $state['sort'] ),
856            esc_attr( Channel_Data::QUERY_ARG_SEARCH ),
857            esc_attr( $state['search'] ),
858            esc_attr__( 'Search this channel', 'jetpack-videopress-pkg' ),
859            esc_html__( 'Search', 'jetpack-videopress-pkg' ),
860            esc_attr__( 'Sort videos', 'jetpack-videopress-pkg' ),
861            $sort_buttons,
862            esc_attr( Channel_Data::QUERY_ARG_LENGTH ),
863            esc_attr__( 'Video length', 'jetpack-videopress-pkg' ),
864            $options,
865            esc_html( $summary )
866        );
867    }
868
869    /**
870     * The Videos page's numbered pagination.
871     *
872     * @param int $current Current page.
873     * @param int $pages   Number of pages.
874     *
875     * @return string Markup.
876     */
877    private static function render_video_browser_pagination( $current, $pages ) {
878        $url_for = function ( $page ) {
879            return 1 === $page ? remove_query_arg( Channel_Data::QUERY_ARG_PAGE ) : add_query_arg( Channel_Data::QUERY_ARG_PAGE, $page );
880        };
881        $step    = function ( $page, $enabled, $modifier, $label ) use ( $url_for ) {
882            return $enabled
883                ? sprintf( '<a class="videopress-video-browser__page videopress-video-browser__page--%1$s" href="%2$s">%3$s</a>', $modifier, esc_url( $url_for( $page ) ), esc_html( $label ) )
884                : sprintf( '<span class="videopress-video-browser__page videopress-video-browser__page--%1$s is-disabled" aria-disabled="true">%2$s</span>', $modifier, esc_html( $label ) );
885        };
886
887        $links = $step( $current - 1, $current > 1, 'prev', __( '← Previous', 'jetpack-videopress-pkg' ) );
888        for ( $page = 1; $page <= $pages; $page++ ) {
889            $links .= $page === $current
890                ? sprintf( '<span class="videopress-video-browser__page videopress-video-browser__page--number is-current" aria-current="page">%d</span>', $page )
891                : sprintf( '<a class="videopress-video-browser__page videopress-video-browser__page--number" href="%1$s">%2$d</a>', esc_url( $url_for( $page ) ), $page );
892        }
893        $links .= $step( $current + 1, $current < $pages, 'next', __( 'Next →', 'jetpack-videopress-pkg' ) );
894
895        return sprintf(
896            '<nav class="videopress-video-browser__pagination" aria-label="%1$s">%2$s</nav>',
897            esc_attr__( 'Videos pagination', 'jetpack-videopress-pkg' ),
898            $links
899        );
900    }
901
902    /**
903     * Sanitize the playlist block's videos attribute into rendering-ready entries.
904     *
905     * @param mixed $videos Raw attribute value.
906     *
907     * @return array Entries with guid, title, durationMs, height and poster keys.
908     */
909    public static function sanitize_playlist_entries( $videos ) {
910        if ( ! is_array( $videos ) ) {
911            return array();
912        }
913
914        $entries = array();
915        foreach ( $videos as $video ) {
916            if ( ! is_array( $video ) || empty( $video['guid'] ) || ! is_string( $video['guid'] ) ) {
917                continue;
918            }
919
920            // VideoPress GUIDs are 8 alphanumeric characters; drop anything else.
921            if ( ! preg_match( '/^[a-zA-Z0-9]{8}$/', $video['guid'] ) ) {
922                continue;
923            }
924
925            /*
926             * Only the video reference and numeric metadata are stored. Display
927             * metadata (title, poster) is always live: the view script reads it
928             * from the video data after the page loads.
929             */
930            $entry = array(
931                'guid'       => $video['guid'],
932                'durationMs' => isset( $video['durationMs'] ) && is_numeric( $video['durationMs'] ) ? max( 0, (int) $video['durationMs'] ) : 0,
933                'height'     => isset( $video['height'] ) && is_numeric( $video['height'] ) ? max( 0, (int) $video['height'] ) : 0,
934            );
935            // Render-time extras for the meta line; never saved with the block.
936            foreach ( array( 'views', 'publishedAt' ) as $extra ) {
937                if ( isset( $video[ $extra ] ) && is_numeric( $video[ $extra ] ) ) {
938                    $entry[ $extra ] = max( 0, (int) $video[ $extra ] );
939                }
940            }
941            $entries[] = $entry;
942        }
943
944        return $entries;
945    }
946
947    /**
948     * Build the VideoPress embed URL for a playlist entry.
949     *
950     * @param string $guid     Video GUID.
951     * @param bool   $autoplay Whether the video should start playing once loaded.
952     * @param bool   $muted    Whether playback should start muted.
953     *
954     * @return string Embed URL.
955     */
956    private static function playlist_embed_url( $guid, $autoplay, $muted = false ) {
957        $args = array(
958            'cover'          => 1,
959            'preloadContent' => Data::get_videopress_player_preload_disabled() ? 'none' : 'metadata',
960            'autoPlay'       => $autoplay ? 1 : 0,
961        );
962        if ( $muted ) {
963            $args['muted'] = 1;
964        }
965
966        return add_query_arg(
967            $args,
968            'https://videopress.com/embed/' . rawurlencode( $guid )
969        );
970    }
971
972    /**
973     * Format a duration in milliseconds as a timecode, m:ss or h:mm:ss.
974     *
975     * @param int $duration_ms Duration in milliseconds.
976     *
977     * @return string Timecode, or an empty string when the duration is unknown.
978     */
979    private static function playlist_timecode( $duration_ms ) {
980        if ( $duration_ms <= 0 ) {
981            return '';
982        }
983
984        $total_seconds = (int) round( $duration_ms / 1000 );
985        $hours         = intdiv( $total_seconds, 3600 );
986        $minutes       = intdiv( $total_seconds % 3600, 60 );
987        $seconds       = $total_seconds % 60;
988
989        if ( $hours > 0 ) {
990            return sprintf( '%d:%02d:%02d', $hours, $minutes, $seconds );
991        }
992
993        return sprintf( '%d:%02d', $minutes, $seconds );
994    }
995
996    /**
997     * Format a duration in milliseconds as a long runtime, e.g. "1 hr 13 min".
998     *
999     * @param int $duration_ms Duration in milliseconds.
1000     *
1001     * @return string Runtime label, or an empty string when the duration is unknown.
1002     */
1003    public static function playlist_runtime_label( $duration_ms ) {
1004        if ( $duration_ms <= 0 ) {
1005            return '';
1006        }
1007
1008        $total_minutes = max( 1, (int) round( $duration_ms / 60000 ) );
1009        $hours         = intdiv( $total_minutes, 60 );
1010        $minutes       = $total_minutes % 60;
1011
1012        if ( $hours > 0 && $minutes > 0 ) {
1013            /* translators: 1: number of hours. 2: number of minutes. */
1014            return sprintf( __( '%1$d hr %2$d min', 'jetpack-videopress-pkg' ), $hours, $minutes );
1015        }
1016
1017        if ( $hours > 0 ) {
1018            /* translators: %d: number of hours. */
1019            return sprintf( __( '%d hr', 'jetpack-videopress-pkg' ), $hours );
1020        }
1021
1022        /* translators: %d: number of minutes. */
1023        return sprintf( __( '%d min', 'jetpack-videopress-pkg' ), $minutes );
1024    }
1025
1026    /**
1027     * Map a video's pixel height to a resolution label, e.g. "1080p" or "4K".
1028     *
1029     * @param int $height Video height in pixels.
1030     *
1031     * @return string Resolution label, or an empty string when the height is unknown.
1032     */
1033    private static function playlist_resolution_label( $height ) {
1034        if ( $height <= 0 ) {
1035            return '';
1036        }
1037
1038        return $height >= 2160 ? '4K' : $height . 'p';
1039    }
1040
1041    /**
1042     * Video Playlist block render callback.
1043     *
1044     * @param array          $block_attributes Block attributes.
1045     * @param string         $content          Rendered inner blocks: the title heading, when there is one.
1046     * @param \WP_Block|null $block            Current block.
1047     * @param string         $before           Markup placed above the playlist body, e.g. browse controls.
1048     * @param string         $after            Markup placed below the playlist body, e.g. pagination.
1049     *
1050     * @return string Block markup, or an empty string when the playlist has no playable entries.
1051     */
1052    public static function render_videopress_playlist_block( $block_attributes, $content = '', $block = null, $before = '', $after = '' ) {
1053        $entries = self::sanitize_playlist_entries( $block_attributes['videos'] ?? null );
1054
1055        if ( ! $entries ) {
1056            return '';
1057        }
1058
1059        // Record the rendered GUIDs in the post's cached GUID list so private playlist
1060        // entries pass the playback authorization check, including when the playlist
1061        // sits inside a synced pattern, template, or template part.
1062        $post_id = $block->context['postId'] ?? get_the_ID();
1063        if ( ! empty( $post_id ) ) {
1064            Access_Control::ensure_post_guids_cached( absint( $post_id ), array_column( $entries, 'guid' ) );
1065        }
1066
1067        $enabled = function ( $key, $default_value = true ) use ( $block_attributes ) {
1068            return isset( $block_attributes[ $key ] ) ? (bool) $block_attributes[ $key ] : $default_value;
1069        };
1070
1071        $layout = isset( $block_attributes['layout'] ) && in_array( $block_attributes['layout'], array( 'side-rail', 'grid', 'strip' ), true )
1072            ? $block_attributes['layout']
1073            : 'side-rail';
1074
1075        $show_player = $enabled( 'showPlayer' );
1076        // A hidden player can still be revealed by the first click on an entry.
1077        $reveal_player  = ! $show_player
1078            && isset( $block_attributes['entryClickAction'] )
1079            && 'show-player' === $block_attributes['entryClickAction'];
1080        $has_player     = $show_player || $reveal_player;
1081        $show_thumbnail = $enabled( 'showThumbnail' );
1082        $show_title     = $enabled( 'showTitle' );
1083        $show_res       = $enabled( 'showResolution' );
1084        $show_duration  = $enabled( 'showDuration' );
1085        $show_number    = $enabled( 'showPositionNumber', false );
1086        $show_runtime   = $enabled( 'showTotalRuntime' );
1087        $muted          = $enabled( 'muteByDefault', false );
1088        $list_key       = isset( $block_attributes['videopressListKey'] ) && is_string( $block_attributes['videopressListKey'] ) ? sanitize_key( $block_attributes['videopressListKey'] ) : '';
1089        $current_guid   = Channel::is_enabled() ? Channel::queried_guid() : '';
1090
1091        $classes = array( 'videopress-playlist', 'is-layout-' . $layout );
1092        if ( $enabled( 'darkPlayer', false ) ) {
1093            $classes[] = 'is-dark';
1094        }
1095        if ( ! $show_player ) {
1096            $classes[] = 'hide-player';
1097        }
1098        if ( ! $show_thumbnail ) {
1099            $classes[] = 'hide-thumbnails';
1100        }
1101        if ( ! $show_title ) {
1102            $classes[] = 'hide-titles';
1103        }
1104        if ( ! $show_res ) {
1105            $classes[] = 'hide-resolutions';
1106        }
1107        if ( ! $show_duration ) {
1108            $classes[] = 'hide-durations';
1109        }
1110        if ( ! $show_runtime ) {
1111            $classes[] = 'hide-runtime';
1112        }
1113
1114        // Lets the embed play private videos for authorized viewers.
1115        Jwt_Token_Bridge::enqueue_jwt_token_bridge();
1116
1117        $count    = count( $entries );
1118        $total_ms = 0;
1119        foreach ( $entries as $entry ) {
1120            $total_ms += $entry['durationMs'];
1121        }
1122
1123        $total_timecode = self::playlist_timecode( $total_ms );
1124        /* translators: %d: number of videos in the playlist. */
1125        $count_label = sprintf( _n( '%d video', '%d videos', $count, 'jetpack-videopress-pkg' ), $count );
1126
1127        /*
1128         * Hidden placeholder shown (via the button's is-locked class) when the view
1129         * script cannot authorize a private video's thumbnail for the viewer.
1130         */
1131        $lock_markup = '<span class="videopress-playlist__entry-lock">'
1132            . '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M17 10h-1.2V7.3c0-2.1-1.7-3.8-3.8-3.8-2.1 0-3.8 1.7-3.8 3.8V10H7c-.6 0-1 .4-1 1v8c0 .6.4 1 1 1h10c.6 0 1-.4 1-1v-8c0-.6-.4-1-1-1Zm-2.7 0H9.7V7.3c0-1.3 1-2.3 2.3-2.3 1.3 0 2.3 1 2.3 2.3V10Z"/></svg>'
1133            . '<span class="videopress-playlist__entry-lock-label">' . esc_html__( 'Private video', 'jetpack-videopress-pkg' ) . '</span>'
1134            . '</span>';
1135
1136        $items = '';
1137        foreach ( $entries as $index => $entry ) {
1138            /*
1139             * Positional fallback only: the view script replaces titles (and
1140             * adds posters) with live video data once the page loads.
1141             */
1142            /* translators: %d: position of the video in the playlist. */
1143            $title = sprintf( __( 'Video %d', 'jetpack-videopress-pkg' ), $index + 1 );
1144
1145            $timecode   = self::playlist_timecode( $entry['durationMs'] );
1146            $resolution = self::playlist_resolution_label( $entry['height'] );
1147            /* translators: 1: position of the video in the playlist. 2: number of videos in the playlist. */
1148            $position = sprintf( __( '%1$d of %2$d', 'jetpack-videopress-pkg' ), $index + 1, $count );
1149            $details  = implode( ' · ', array_filter( array( $resolution, $timecode ) ) );
1150            $progress = '' !== $total_timecode
1151                /* translators: 1: position of the video in the playlist. 2: number of videos. 3: total playlist timecode. */
1152                ? sprintf( __( '%1$d / %2$d · %3$s total', 'jetpack-videopress-pkg' ), $index + 1, $count, $total_timecode )
1153                /* translators: 1: position of the video in the playlist. 2: number of videos. */
1154                : sprintf( __( '%1$d / %2$d', 'jetpack-videopress-pkg' ), $index + 1, $count );
1155
1156            $number_markup = $show_number
1157                ? sprintf(
1158                    '<span class="videopress-playlist__entry-number">%s</span>',
1159                    esc_html( str_pad( (string) ( $index + 1 ), 2, '0', STR_PAD_LEFT ) )
1160                )
1161                : '';
1162
1163            $time_markup = '' !== $timecode
1164                ? sprintf( '<span class="videopress-playlist__entry-time">%s</span>', esc_html( $timecode ) )
1165                : '';
1166
1167            $resolution_markup = '' !== $resolution
1168                ? sprintf( '<span class="videopress-playlist__entry-resolution">%s</span>', esc_html( $resolution ) )
1169                : '';
1170
1171            $duration_markup = '' !== $timecode
1172                ? sprintf( '<span class="videopress-playlist__entry-duration">%s</span>', esc_html( $timecode ) )
1173                : '';
1174
1175            $stats_label  = Channel_Data::views_and_age( array_intersect_key( $entry, array_flip( array( 'views', 'publishedAt' ) ) ) );
1176            $stats_markup = '' !== $stats_label
1177                ? sprintf( '<span class="videopress-playlist__entry-stats">%s</span>', esc_html( $stats_label ) )
1178                : '';
1179
1180            if ( $has_player ) {
1181                $is_current  = $show_player && 0 === $index;
1182                $entry_open  = sprintf(
1183                    '<button type="button" class="videopress-playlist__select%1$s"%2$s data-guid="%3$s" data-embed-url="%4$s" data-title="%5$s" data-position="%6$s" data-details="%7$s" data-progress="%8$s">',
1184                    $is_current ? ' is-current' : '',
1185                    $is_current ? ' aria-current="true"' : '',
1186                    esc_attr( $entry['guid'] ),
1187                    esc_url( self::playlist_embed_url( $entry['guid'], true, $muted ) ),
1188                    esc_attr( $title ),
1189                    esc_attr( $position ),
1190                    esc_attr( $details ),
1191                    esc_attr( $progress )
1192                );
1193                $entry_close = '</button>';
1194            } else {
1195                // No player to load the video into: the entry opens the video's page instead.
1196                /**
1197                 * Filters where a playlist entry opens when the block has no player.
1198                 *
1199                 * @since 0.55.0
1200                 *
1201                 * @param string $url  The video's page on videopress.com.
1202                 * @param string $guid The video GUID.
1203                 */
1204                $entry_url = apply_filters( 'videopress_playlist_entry_url', 'https://videopress.com/v/' . $entry['guid'], $entry['guid'] );
1205                $on_site   = Channel::is_site_url( $entry_url );
1206                if ( $on_site && '' !== $list_key ) {
1207                    $entry_url = add_query_arg( Channel::LIST_VAR, $list_key, $entry_url );
1208                }
1209                $is_current = '' !== $current_guid && $entry['guid'] === $current_guid;
1210                $entry_open = sprintf(
1211                    '<a class="videopress-playlist__select%1$s" href="%2$s"%3$s%4$s data-guid="%5$s" data-title="%6$s" data-position="%7$s" data-details="%8$s">',
1212                    $is_current ? ' is-current' : '',
1213                    esc_url( $entry_url ),
1214                    // Channel pages stay in the tab; videopress.com opens a new one.
1215                    $on_site ? '' : ' target="_blank" rel="noopener noreferrer"',
1216                    $is_current ? ' aria-current="true"' : '',
1217                    esc_attr( $entry['guid'] ),
1218                    esc_attr( $title ),
1219                    esc_attr( $position ),
1220                    esc_attr( $details )
1221                );
1222                $entry_close = '</a>';
1223            }
1224
1225            $items .= sprintf(
1226                '<li class="videopress-playlist__entry%10$s">%1$s' .
1227                    '%2$s<span class="videopress-playlist__entry-thumb"><span class="videopress-playlist__entry-flag">%3$s</span>%4$s%5$s</span>' .
1228                    '<span class="videopress-playlist__entry-body"><span class="videopress-playlist__entry-title">%6$s</span><span class="videopress-playlist__entry-meta">%7$s%8$s</span>%11$s</span>' .
1229                    '%9$s</li>',
1230                $entry_open,
1231                $number_markup,
1232                esc_html__( 'Playing', 'jetpack-videopress-pkg' ),
1233                $lock_markup,
1234                $time_markup,
1235                esc_html( $title ),
1236                $resolution_markup,
1237                $duration_markup,
1238                $entry_close,
1239                ! $has_player && '' !== $current_guid && $entry['guid'] === $current_guid ? ' is-current' : '',
1240                $stats_markup
1241            );
1242        }
1243
1244        $first          = $entries[0];
1245        $first_title    = __( 'Video 1', 'jetpack-videopress-pkg' );
1246        $runtime_label  = self::playlist_runtime_label( $total_ms );
1247        $runtime_markup = $show_runtime && '' !== $runtime_label
1248            ? sprintf( '<span class="videopress-playlist__runtime">%s</span>', esc_html( $runtime_label ) )
1249            : '';
1250
1251        // Count · runtime meta line, shown by the side-rail layout in the list header.
1252        $list_meta_markup = sprintf(
1253            '<span class="videopress-playlist__list-meta"><span class="videopress-playlist__count">%s</span>%s</span>',
1254            esc_html( $count_label ),
1255            $runtime_markup
1256        );
1257
1258        /*
1259         * The player renders its own title overlay, so the stage carries no
1260         * duplicate now-playing text — only the grid layout's runtime line.
1261         */
1262        $now_markup = $show_runtime && '' !== $runtime_label
1263            ? sprintf(
1264                '<div class="videopress-playlist__now"><span class="videopress-playlist__now-runtime">%s</span></div>',
1265                esc_html( $count_label . ' · ' . $runtime_label )
1266            )
1267            : '';
1268
1269        if ( $show_player ) {
1270            $stage_markup = sprintf(
1271                '<div class="videopress-playlist__stage">' .
1272                    '<div class="videopress-playlist__player"><iframe class="videopress-playlist__iframe" title="%1$s" src="%2$s" allowfullscreen allow="clipboard-write"></iframe></div>%3$s</div>',
1273                esc_attr( $first_title ),
1274                esc_url( self::playlist_embed_url( $first['guid'], false, $muted ) ),
1275                $now_markup
1276            );
1277        } elseif ( $reveal_player ) {
1278            // No src: nothing loads until the view script reveals the stage on a click.
1279            $stage_markup = sprintf(
1280                '<div class="videopress-playlist__stage" hidden>' .
1281                    '<div class="videopress-playlist__player"><iframe class="videopress-playlist__iframe" title="%1$s" allowfullscreen allow="clipboard-write"></iframe></div></div>%2$s',
1282                esc_attr( $first_title ),
1283                $now_markup
1284            );
1285        } else {
1286            // Without a player only the grid layout's runtime line remains of the stage.
1287            $stage_markup = $now_markup;
1288        }
1289
1290        $progress_markup = $has_player && '' !== $total_timecode
1291            ? sprintf(
1292                '<span class="videopress-playlist__list-progress">%s</span>',
1293                /* translators: 1: position of the current video. 2: number of videos. 3: total playlist timecode. */
1294                esc_html( sprintf( __( '%1$d / %2$d · %3$s total', 'jetpack-videopress-pkg' ), 1, $count, $total_timecode ) )
1295            )
1296            : '';
1297
1298        $list_markup = sprintf(
1299            '<div class="videopress-playlist__list">' .
1300                '<div class="videopress-playlist__list-header">' .
1301                '<span class="videopress-playlist__list-label videopress-playlist__list-label--rail">%1$s</span>' .
1302                '<span class="videopress-playlist__list-label videopress-playlist__list-label--strip">%2$s</span>%3$s%4$s</div>' .
1303                '<ol class="videopress-playlist__entries">%5$s</ol></div>',
1304            $show_player
1305                ? esc_html__( 'Up next', 'jetpack-videopress-pkg' )
1306                : esc_html__( 'Playlist', 'jetpack-videopress-pkg' ),
1307            /* translators: %s: number of videos in the playlist, e.g. "5 videos". */
1308            esc_html( sprintf( __( 'Playlist — %s', 'jetpack-videopress-pkg' ), $count_label ) ),
1309            $list_meta_markup,
1310            $progress_markup,
1311            $items
1312        );
1313
1314        /*
1315         * User-selected theme font presets (theme.json slugs) for the
1316         * customizable titles, exposed as CSS custom properties the
1317         * stylesheet reads. Anything but a plain preset slug is dropped.
1318         */
1319        $font_style = '';
1320        foreach ( array(
1321            'entryTitleFontFamily' => '--vpp-entry-title-font',
1322        ) as $font_attribute => $css_variable ) {
1323            if ( ! empty( $block_attributes[ $font_attribute ] )
1324                && is_string( $block_attributes[ $font_attribute ] )
1325                && preg_match( '/^[a-zA-Z0-9-]+$/', $block_attributes[ $font_attribute ] )
1326            ) {
1327                $font_style .= $css_variable . ':var(--wp--preset--font-family--' . $block_attributes[ $font_attribute ] . ');';
1328            }
1329        }
1330
1331        // Looping implies auto-advancing, so it forces the autoplay-next flag on.
1332        $loop_playlist = $enabled( 'loopPlaylist', false );
1333
1334        $wrapper_extra_attributes = array(
1335            'class'              => implode( ' ', $classes ),
1336            'data-autoplay-next' => $enabled( 'autoplayNext', false ) || $loop_playlist ? '1' : '0',
1337            'data-loop'          => $loop_playlist ? '1' : '0',
1338        );
1339        if ( '' !== $font_style ) {
1340            $wrapper_extra_attributes['style'] = $font_style;
1341        }
1342
1343        $wrapper_attributes = get_block_wrapper_attributes( $wrapper_extra_attributes );
1344
1345        // The Heading inner block saved with the post; an empty title renders none.
1346        $playlist_title = isset( $block_attributes['playlistTitle'] ) && is_string( $block_attributes['playlistTitle'] )
1347            ? trim( $block_attributes['playlistTitle'] )
1348            : '';
1349        $content        = is_string( $content ) ? trim( $content ) : '';
1350        $heading_markup = $enabled( 'showPlaylistTitle' ) && '' !== $playlist_title && '' !== $content
1351            ? '<div class="videopress-playlist__heading">' . $content . '</div>'
1352            : '';
1353
1354        return sprintf(
1355            '<figure %1$s>%2$s%5$s<div class="videopress-playlist__body">%3$s%4$s</div>%6$s</figure>',
1356            $wrapper_attributes,
1357            $heading_markup,
1358            $stage_markup,
1359            $list_markup,
1360            $before,
1361            $after
1362        );
1363    }
1364
1365    /**
1366     * Enqueue the VideoPress Iframe API script
1367     * when the URL of oEmbed HTML is a VideoPress URL.
1368     *
1369     * @param string|false $cache   The cached HTML result, stored in post meta.
1370     * @param string       $url     The attempted embed URL.
1371     * @param array        $attr    An array of shortcode attributes.
1372     * @param int          $post_ID Post ID.
1373     *
1374     * @return string|false
1375     */
1376    public static function enqueue_videopress_iframe_api_script( $cache, $url, $attr, $post_ID ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1377        if ( Utils::is_videopress_url( $url ) && ! Inline_Player::is_enabled() ) {
1378            // Enqueue the VideoPress IFrame API in the front-end.
1379            wp_enqueue_script(
1380                self::JETPACK_VIDEOPRESS_IFRAME_API_HANDLER,
1381                'https://s0.wp.com/wp-content/plugins/video/assets/js/videojs/videopress-iframe-api.js',
1382                array(),
1383                gmdate( 'YW' ),
1384                false
1385            );
1386        }
1387
1388        return $cache;
1389    }
1390
1391    /**
1392     * Short-circuit the oEmbed request for VideoPress URLs when the inline player is on.
1393     *
1394     * @param null|string $result The oEmbed result, null to let WordPress fetch it.
1395     * @param string      $url    The URL being embedded.
1396     * @return null|string Inline player markup, or the untouched result.
1397     */
1398    public static function maybe_pre_oembed_inline_player( $result, $url ) {
1399        $inline = self::render_inline_player_for_url( $url );
1400
1401        return null === $inline ? $result : $inline;
1402    }
1403
1404    /**
1405     * Replace a VideoPress oEmbed iframe (fresh or cached) with an inline player when the inline player is on.
1406     *
1407     * @param string|false $cache   The oEmbed HTML.
1408     * @param string       $url     The URL being embedded.
1409     * @param array        $attr    Shortcode attributes.
1410     * @param int          $post_ID Post ID.
1411     * @return string|false Inline player markup, or the untouched HTML.
1412     */
1413    public static function maybe_render_oembed_inline_player( $cache, $url, $attr, $post_ID = null ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1414        if ( ! is_string( $cache ) || false === strpos( $cache, '<iframe' ) ) {
1415            return $cache;
1416        }
1417
1418        $inline = self::render_inline_player_for_url( $url );
1419
1420        return null === $inline ? $cache : $inline;
1421    }
1422
1423    /**
1424     * Build inline player markup for a videopress.com URL, honoring the player parameters in its query string.
1425     *
1426     * @param string $url The URL being embedded.
1427     * @return string|null Markup, or null when the URL is not a VideoPress video or the inline player is off.
1428     */
1429    private static function render_inline_player_for_url( $url ) {
1430        if ( ! Inline_Player::is_enabled() ) {
1431            return null;
1432        }
1433
1434        $guid = Utils::extract_videopress_guid_from_url( $url );
1435        if ( null === $guid ) {
1436            return null;
1437        }
1438
1439        $attributes = Inline_Player::get_attributes_from_embed_url( $url );
1440
1441        return Inline_Player::render(
1442            $guid,
1443            Inline_Player::get_player_options( $attributes ),
1444            null,
1445            array( 'poster' => Inline_Player::get_poster_url( $guid, $attributes ) )
1446        );
1447    }
1448}