PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.3-a.3
Jetpack – WP Security, Backup, Speed, & Growth v16.3-a.3
16.3 16.3-beta 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 All 508 releases
jetpack / jetpack_vendor / automattic / jetpack-videopress / src / class-initializer.php

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

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