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