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