PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.2
Jetpack – WP Security, Backup, Speed, & Growth v16.2
16.3-a.5 16.3-a.7 16.3-a.3 16.3-a.1 16.2 16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 All 506 releases
jetpack / jetpack_vendor / automattic / jetpack-videopress / src / class-initializer.php

class-initializer.php in Jetpack – WP Security, Backup, Speed, & Growth 16.2, at jetpack_vendor/automattic/jetpack-videopress/src/class-initializer.php

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