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