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

1,083 lines 38.7 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 )
434 );
435 } elseif ( $videopress_url ) {
436 $videopress_url = wp_kses_post( $videopress_url );
437
438 /*
439 * Provide a fallback iframe for when the oEmbed endpoint fails, e.g.
440 * when the VideoPress backend isn't ready for a freshly uploaded video.
441 * This prevents the published page from showing a bare link.
442 */
443 $fallback = function ( $output, $url ) use ( $videopress_url ) {
444 $decoded_url = html_entity_decode( $videopress_url, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 );
445 if ( $decoded_url !== $url ) {
446 return $output;
447 }
448
449 return sprintf(
450 '<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>',
451 esc_attr__( 'VideoPress Video Player', 'jetpack-videopress-pkg' ),
452 esc_url( preg_replace( '#/v/#', '/embed/', $url, 1 ) )
453 );
454 };
455
456 add_filter( 'embed_maybe_make_link', $fallback, 10, 2 );
457 $oembed_html = apply_filters( 'video_embed_html', $wp_embed->shortcode( array(), $videopress_url ) );
458 remove_filter( 'embed_maybe_make_link', $fallback );
459
460 $video_wrapper = sprintf(
461 '<div class="%s">%s %s</div>',
462 $video_wrapper_classes,
463 $preview_on_hover,
464 $oembed_html
465 );
466
467 /*
468 * Self-heal failed oEmbed cache for VideoPress URLs.
469 *
470 * When the VideoPress backend isn't ready for a freshly uploaded video,
471 * WordPress caches '{{unknown}}' in post meta with a TTL that is too long
472 * for this use case. Clear recent failures so the next page render retries
473 * oEmbed discovery, keeping the fallback iframe above temporary.
474 */
475 $post_id = $block->context['postId'] ?? get_the_ID();
476
477 if ( $post_id ) {
478 $key_suffix = md5( $videopress_url . serialize( wp_embed_defaults( $videopress_url ) ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Matching WP_Embed cache key format.
479 $oembed_value = get_post_meta( $post_id, '_oembed_' . $key_suffix, true );
480 $oembed_time = (int) get_post_meta( $post_id, '_oembed_time_' . $key_suffix, true );
481
482 /*
483 * Only clear the '{{unknown}}' cache entry when it is recent, to avoid
484 * disabling WordPress's oEmbed backoff for persistent provider failures.
485 */
486 if (
487 '{{unknown}}' === $oembed_value
488 && ( ! $oembed_time || ( time() - $oembed_time ) < MINUTE_IN_SECONDS )
489 ) {
490 delete_post_meta( $post_id, '_oembed_' . $key_suffix );
491 delete_post_meta( $post_id, '_oembed_time_' . $key_suffix );
492 }
493 }
494 }
495
496 // Get premium content from block context.
497 $premium_block_plan_id = isset( $block->context['premium-content/planId'] ) ? intval( $block->context['premium-content/planId'] ) : 0;
498 $is_premium_content_child = isset( $block->context['isPremiumContentChild'] ) ? (bool) $block->context['isPremiumContentChild'] : false;
499 $maybe_premium_script = '';
500 if ( $is_premium_content_child && is_string( $guid ) ) {
501 Access_Control::instance()->set_guid_subscription( $guid, $premium_block_plan_id );
502 $escaped_guid = wp_json_encode( $guid, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
503 $script_content = "if ( ! window.__guidsToPlanIds ) { window.__guidsToPlanIds = {}; }; window.__guidsToPlanIds[$escaped_guid] = $premium_block_plan_id;";
504 $maybe_premium_script = '<script>' . $script_content . '</script>';
505 }
506
507 // $id_attribute, $video_wrapper, $figcaption properly escaped earlier in the code.
508 return sprintf(
509 $figure_template,
510 esc_attr( $classes ),
511 esc_attr( $style ),
512 $id_attribute,
513 $video_wrapper,
514 $figcaption,
515 $maybe_premium_script
516 );
517 }
518
519 /**
520 * Register the VideoPress block editor block,
521 * AKA "VideoPress Block v6".
522 *
523 * @return void
524 */
525 public static function register_videopress_video_block() {
526 /*
527 * If only Jetpack is active, and if the VideoPress module is not active,
528 * we can register the block just to display a placeholder to turn on the module.
529 * That invitation is only useful for admins though.
530 */
531 if (
532 Status::is_jetpack_plugin_without_videopress_module_active()
533 && ! Status::is_standalone_plugin_active()
534 && ! current_user_can( 'jetpack_activate_modules' )
535 ) {
536 return;
537 }
538
539 $videopress_video_metadata_file = __DIR__ . '/../build/block-editor/blocks/video/block.json';
540 $videopress_video_metadata_file_exists = file_exists( $videopress_video_metadata_file );
541 if ( ! $videopress_video_metadata_file_exists ) {
542 return;
543 }
544
545 $videopress_video_metadata = json_decode(
546 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
547 file_get_contents( $videopress_video_metadata_file )
548 );
549
550 // Pick the block name straight from the block metadata .json file.
551 $videopress_video_block_name = $videopress_video_metadata->name;
552
553 // Is the block already registered?
554 $is_block_registered = \WP_Block_Type_Registry::get_instance()->is_registered( $videopress_video_block_name );
555
556 // Do not register if the block is already registered.
557 if ( $is_block_registered ) {
558 return;
559 }
560
561 $registration = register_block_type(
562 $videopress_video_metadata_file,
563 array(
564 'render_callback' => array( __CLASS__, 'render_videopress_video_block' ),
565 'render_email_callback' => array( Video_Block_Email_Renderer::class, 'render' ),
566 'uses_context' => array( 'premium-content/planId', 'isPremiumContentChild', 'selectedPlanId' ),
567 )
568 );
569
570 // Do not enqueue scripts if the block could not be registered.
571 if ( empty( $registration ) || empty( $registration->editor_script_handles ) ) {
572 return;
573 }
574
575 // Extensions use Connection_Initial_State::render_script with script handle as parameter.
576 if ( is_array( $registration->editor_script_handles ) ) {
577 $script_handle = $registration->editor_script_handles[0];
578 } else {
579 $script_handle = $registration->editor_script_handles;
580 }
581
582 // Register and enqueue scripts used by the VideoPress video block.
583 Block_Editor_Extensions::init( $script_handle );
584 }
585
586 /**
587 * Register the Video Playlist block.
588 *
589 * @param string|null $metadata_file Path to the block.json metadata file. Defaults to the
590 * package build output; tests can point it at a fixture.
591 *
592 * @return void
593 */
594 public static function register_videopress_playlist_block( $metadata_file = null ) {
595 /*
596 * Unlike the video block, the playlist block has no "activate the module"
597 * placeholder, so it is only registered where VideoPress can play videos.
598 */
599 if (
600 Status::is_jetpack_plugin_without_videopress_module_active()
601 && ! Status::is_standalone_plugin_active()
602 ) {
603 return;
604 }
605
606 if ( null === $metadata_file ) {
607 $metadata_file = __DIR__ . '/../build/block-editor/blocks/playlist/block.json';
608 }
609
610 if ( ! file_exists( $metadata_file ) ) {
611 return;
612 }
613
614 $metadata = json_decode(
615 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
616 file_get_contents( $metadata_file )
617 );
618
619 if ( empty( $metadata->name )
620 || \WP_Block_Type_Registry::get_instance()->is_registered( $metadata->name )
621 ) {
622 return;
623 }
624
625 register_block_type(
626 $metadata_file,
627 array(
628 'render_callback' => array( __CLASS__, 'render_videopress_playlist_block' ),
629 )
630 );
631 }
632
633 /**
634 * Sanitize the playlist block's videos attribute into rendering-ready entries.
635 *
636 * @param mixed $videos Raw attribute value.
637 *
638 * @return array Entries with guid, title, durationMs, height and poster keys.
639 */
640 private static function sanitize_playlist_entries( $videos ) {
641 if ( ! is_array( $videos ) ) {
642 return array();
643 }
644
645 $entries = array();
646 foreach ( $videos as $video ) {
647 if ( ! is_array( $video ) || empty( $video['guid'] ) || ! is_string( $video['guid'] ) ) {
648 continue;
649 }
650
651 // VideoPress GUIDs are 8 alphanumeric characters; drop anything else.
652 if ( ! preg_match( '/^[a-zA-Z0-9]{8}$/', $video['guid'] ) ) {
653 continue;
654 }
655
656 /*
657 * Only the video reference and numeric metadata are stored. Display
658 * metadata (title, poster) is always live: the view script reads it
659 * from the video data after the page loads.
660 */
661 $entries[] = array(
662 'guid' => $video['guid'],
663 'durationMs' => isset( $video['durationMs'] ) && is_numeric( $video['durationMs'] ) ? max( 0, (int) $video['durationMs'] ) : 0,
664 'height' => isset( $video['height'] ) && is_numeric( $video['height'] ) ? max( 0, (int) $video['height'] ) : 0,
665 );
666 }
667
668 return $entries;
669 }
670
671 /**
672 * Build the VideoPress embed URL for a playlist entry.
673 *
674 * @param string $guid Video GUID.
675 * @param bool $autoplay Whether the video should start playing once loaded.
676 * @param bool $muted Whether playback should start muted.
677 *
678 * @return string Embed URL.
679 */
680 private static function playlist_embed_url( $guid, $autoplay, $muted = false ) {
681 $args = array(
682 'cover' => 1,
683 'preloadContent' => Data::get_videopress_player_preload_disabled() ? 'none' : 'metadata',
684 'autoPlay' => $autoplay ? 1 : 0,
685 );
686 if ( $muted ) {
687 $args['muted'] = 1;
688 }
689
690 return add_query_arg(
691 $args,
692 'https://videopress.com/embed/' . rawurlencode( $guid )
693 );
694 }
695
696 /**
697 * Format a duration in milliseconds as a timecode, m:ss or h:mm:ss.
698 *
699 * @param int $duration_ms Duration in milliseconds.
700 *
701 * @return string Timecode, or an empty string when the duration is unknown.
702 */
703 private static function playlist_timecode( $duration_ms ) {
704 if ( $duration_ms <= 0 ) {
705 return '';
706 }
707
708 $total_seconds = (int) round( $duration_ms / 1000 );
709 $hours = intdiv( $total_seconds, 3600 );
710 $minutes = intdiv( $total_seconds % 3600, 60 );
711 $seconds = $total_seconds % 60;
712
713 if ( $hours > 0 ) {
714 return sprintf( '%d:%02d:%02d', $hours, $minutes, $seconds );
715 }
716
717 return sprintf( '%d:%02d', $minutes, $seconds );
718 }
719
720 /**
721 * Format a duration in milliseconds as a long runtime, e.g. "1 hr 13 min".
722 *
723 * @param int $duration_ms Duration in milliseconds.
724 *
725 * @return string Runtime label, or an empty string when the duration is unknown.
726 */
727 private static function playlist_runtime_label( $duration_ms ) {
728 if ( $duration_ms <= 0 ) {
729 return '';
730 }
731
732 $total_minutes = max( 1, (int) round( $duration_ms / 60000 ) );
733 $hours = intdiv( $total_minutes, 60 );
734 $minutes = $total_minutes % 60;
735
736 if ( $hours > 0 && $minutes > 0 ) {
737 /* translators: 1: number of hours. 2: number of minutes. */
738 return sprintf( __( '%1$d hr %2$d min', 'jetpack-videopress-pkg' ), $hours, $minutes );
739 }
740
741 if ( $hours > 0 ) {
742 /* translators: %d: number of hours. */
743 return sprintf( __( '%d hr', 'jetpack-videopress-pkg' ), $hours );
744 }
745
746 /* translators: %d: number of minutes. */
747 return sprintf( __( '%d min', 'jetpack-videopress-pkg' ), $minutes );
748 }
749
750 /**
751 * Map a video's pixel height to a resolution label, e.g. "1080p" or "4K".
752 *
753 * @param int $height Video height in pixels.
754 *
755 * @return string Resolution label, or an empty string when the height is unknown.
756 */
757 private static function playlist_resolution_label( $height ) {
758 if ( $height <= 0 ) {
759 return '';
760 }
761
762 return $height >= 2160 ? '4K' : $height . 'p';
763 }
764
765 /**
766 * Video Playlist block render callback.
767 *
768 * @param array $block_attributes Block attributes.
769 * @param string $content Current block markup.
770 * @param \WP_Block|null $block Current block.
771 *
772 * @return string Block markup, or an empty string when the playlist has no playable entries.
773 */
774 public static function render_videopress_playlist_block( $block_attributes, $content = '', $block = null ) {
775 $entries = self::sanitize_playlist_entries( $block_attributes['videos'] ?? null );
776
777 if ( ! $entries ) {
778 return '';
779 }
780
781 // Record the rendered GUIDs in the post's cached GUID list so private playlist
782 // entries pass the playback authorization check, including when the playlist
783 // sits inside a synced pattern, template, or template part.
784 $post_id = $block->context['postId'] ?? get_the_ID();
785 if ( ! empty( $post_id ) ) {
786 Access_Control::ensure_post_guids_cached( absint( $post_id ), array_column( $entries, 'guid' ) );
787 }
788
789 $enabled = function ( $key, $default_value = true ) use ( $block_attributes ) {
790 return isset( $block_attributes[ $key ] ) ? (bool) $block_attributes[ $key ] : $default_value;
791 };
792
793 $layout = isset( $block_attributes['layout'] ) && in_array( $block_attributes['layout'], array( 'side-rail', 'grid', 'strip' ), true )
794 ? $block_attributes['layout']
795 : 'side-rail';
796
797 $show_thumbnail = $enabled( 'showThumbnail' );
798 $show_title = $enabled( 'showTitle' );
799 $show_res = $enabled( 'showResolution' );
800 $show_duration = $enabled( 'showDuration' );
801 $show_number = $enabled( 'showPositionNumber', false );
802 $show_runtime = $enabled( 'showTotalRuntime' );
803 $muted = $enabled( 'muteByDefault', false );
804
805 $classes = array( 'videopress-playlist', 'is-layout-' . $layout );
806 if ( $enabled( 'darkPlayer', false ) ) {
807 $classes[] = 'is-dark';
808 }
809 if ( ! $show_thumbnail ) {
810 $classes[] = 'hide-thumbnails';
811 }
812 if ( ! $show_title ) {
813 $classes[] = 'hide-titles';
814 }
815 if ( ! $show_res ) {
816 $classes[] = 'hide-resolutions';
817 }
818 if ( ! $show_duration ) {
819 $classes[] = 'hide-durations';
820 }
821 if ( ! $show_runtime ) {
822 $classes[] = 'hide-runtime';
823 }
824
825 // Lets the embed play private videos for authorized viewers.
826 Jwt_Token_Bridge::enqueue_jwt_token_bridge();
827
828 $count = count( $entries );
829 $total_ms = 0;
830 foreach ( $entries as $entry ) {
831 $total_ms += $entry['durationMs'];
832 }
833
834 $total_timecode = self::playlist_timecode( $total_ms );
835 /* translators: %d: number of videos in the playlist. */
836 $count_label = sprintf( _n( '%d video', '%d videos', $count, 'jetpack-videopress-pkg' ), $count );
837
838 /*
839 * Hidden placeholder shown (via the button's is-locked class) when the view
840 * script cannot authorize a private video's thumbnail for the viewer.
841 */
842 $lock_markup = '<span class="videopress-playlist__entry-lock">'
843 . '<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>'
844 . '<span class="videopress-playlist__entry-lock-label">' . esc_html__( 'Private video', 'jetpack-videopress-pkg' ) . '</span>'
845 . '</span>';
846
847 $items = '';
848 foreach ( $entries as $index => $entry ) {
849 /*
850 * Positional fallback only: the view script replaces titles (and
851 * adds posters) with live video data once the page loads.
852 */
853 /* translators: %d: position of the video in the playlist. */
854 $title = sprintf( __( 'Video %d', 'jetpack-videopress-pkg' ), $index + 1 );
855
856 $timecode = self::playlist_timecode( $entry['durationMs'] );
857 $resolution = self::playlist_resolution_label( $entry['height'] );
858 /* translators: 1: position of the video in the playlist. 2: number of videos in the playlist. */
859 $position = sprintf( __( '%1$d of %2$d', 'jetpack-videopress-pkg' ), $index + 1, $count );
860 $details = implode( ' · ', array_filter( array( $resolution, $timecode ) ) );
861 $progress = '' !== $total_timecode
862 /* translators: 1: position of the video in the playlist. 2: number of videos. 3: total playlist timecode. */
863 ? sprintf( __( '%1$d / %2$d · %3$s total', 'jetpack-videopress-pkg' ), $index + 1, $count, $total_timecode )
864 /* translators: 1: position of the video in the playlist. 2: number of videos. */
865 : sprintf( __( '%1$d / %2$d', 'jetpack-videopress-pkg' ), $index + 1, $count );
866
867 $number_markup = $show_number
868 ? sprintf(
869 '<span class="videopress-playlist__entry-number">%s</span>',
870 esc_html( str_pad( (string) ( $index + 1 ), 2, '0', STR_PAD_LEFT ) )
871 )
872 : '';
873
874 $time_markup = '' !== $timecode
875 ? sprintf( '<span class="videopress-playlist__entry-time">%s</span>', esc_html( $timecode ) )
876 : '';
877
878 $resolution_markup = '' !== $resolution
879 ? sprintf( '<span class="videopress-playlist__entry-resolution">%s</span>', esc_html( $resolution ) )
880 : '';
881
882 $duration_markup = '' !== $timecode
883 ? sprintf( '<span class="videopress-playlist__entry-duration">%s</span>', esc_html( $timecode ) )
884 : '';
885
886 $items .= sprintf(
887 '<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">' .
888 '%9$s<span class="videopress-playlist__entry-thumb"><span class="videopress-playlist__entry-flag">%10$s</span>%15$s%11$s</span>' .
889 '<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>' .
890 '</button></li>',
891 0 === $index ? ' is-current' : '',
892 0 === $index ? ' aria-current="true"' : '',
893 esc_attr( $entry['guid'] ),
894 esc_url( self::playlist_embed_url( $entry['guid'], true, $muted ) ),
895 esc_attr( $title ),
896 esc_attr( $position ),
897 esc_attr( $details ),
898 esc_attr( $progress ),
899 $number_markup,
900 esc_html__( 'Playing', 'jetpack-videopress-pkg' ),
901 $time_markup,
902 esc_html( $title ),
903 $resolution_markup,
904 $duration_markup,
905 $lock_markup
906 );
907 }
908
909 $first = $entries[0];
910 $first_title = __( 'Video 1', 'jetpack-videopress-pkg' );
911 $runtime_label = self::playlist_runtime_label( $total_ms );
912 $runtime_markup = $show_runtime && '' !== $runtime_label
913 ? sprintf( '<span class="videopress-playlist__runtime">%s</span>', esc_html( $runtime_label ) )
914 : '';
915
916 // Count · runtime meta line, shown by the side-rail layout in the list header.
917 $list_meta_markup = sprintf(
918 '<span class="videopress-playlist__list-meta"><span class="videopress-playlist__count">%s</span>%s</span>',
919 esc_html( $count_label ),
920 $runtime_markup
921 );
922
923 /*
924 * The player renders its own title overlay, so the stage carries no
925 * duplicate now-playing text — only the grid layout's runtime line.
926 */
927 $now_markup = $show_runtime && '' !== $runtime_label
928 ? sprintf(
929 '<div class="videopress-playlist__now"><span class="videopress-playlist__now-runtime">%s</span></div>',
930 esc_html( $count_label . ' · ' . $runtime_label )
931 )
932 : '';
933
934 $stage_markup = sprintf(
935 '<div class="videopress-playlist__stage">' .
936 '<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>',
937 esc_attr( $first_title ),
938 esc_url( self::playlist_embed_url( $first['guid'], false, $muted ) ),
939 $now_markup
940 );
941
942 $progress_markup = '' !== $total_timecode
943 ? sprintf(
944 '<span class="videopress-playlist__list-progress">%s</span>',
945 /* translators: 1: position of the current video. 2: number of videos. 3: total playlist timecode. */
946 esc_html( sprintf( __( '%1$d / %2$d · %3$s total', 'jetpack-videopress-pkg' ), 1, $count, $total_timecode ) )
947 )
948 : '';
949
950 $list_markup = sprintf(
951 '<div class="videopress-playlist__list">' .
952 '<div class="videopress-playlist__list-header">' .
953 '<span class="videopress-playlist__list-label videopress-playlist__list-label--rail">%1$s</span>' .
954 '<span class="videopress-playlist__list-label videopress-playlist__list-label--strip">%2$s</span>%3$s%4$s</div>' .
955 '<ol class="videopress-playlist__entries">%5$s</ol></div>',
956 esc_html__( 'Up next', 'jetpack-videopress-pkg' ),
957 /* translators: %s: number of videos in the playlist, e.g. "5 videos". */
958 esc_html( sprintf( __( 'Playlist — %s', 'jetpack-videopress-pkg' ), $count_label ) ),
959 $list_meta_markup,
960 $progress_markup,
961 $items
962 );
963
964 /*
965 * User-selected theme font presets (theme.json slugs) for the
966 * customizable titles, exposed as CSS custom properties the
967 * stylesheet reads. Anything but a plain preset slug is dropped.
968 */
969 $font_style = '';
970 foreach ( array(
971 'entryTitleFontFamily' => '--vpp-entry-title-font',
972 ) as $font_attribute => $css_variable ) {
973 if ( ! empty( $block_attributes[ $font_attribute ] )
974 && is_string( $block_attributes[ $font_attribute ] )
975 && preg_match( '/^[a-zA-Z0-9-]+$/', $block_attributes[ $font_attribute ] )
976 ) {
977 $font_style .= $css_variable . ':var(--wp--preset--font-family--' . $block_attributes[ $font_attribute ] . ');';
978 }
979 }
980
981 // Looping implies auto-advancing, so it forces the autoplay-next flag on.
982 $loop_playlist = $enabled( 'loopPlaylist', false );
983
984 $wrapper_extra_attributes = array(
985 'class' => implode( ' ', $classes ),
986 'data-autoplay-next' => $enabled( 'autoplayNext', false ) || $loop_playlist ? '1' : '0',
987 'data-loop' => $loop_playlist ? '1' : '0',
988 );
989 if ( '' !== $font_style ) {
990 $wrapper_extra_attributes['style'] = $font_style;
991 }
992
993 $wrapper_attributes = get_block_wrapper_attributes( $wrapper_extra_attributes );
994
995 return sprintf(
996 '<figure %1$s><div class="videopress-playlist__body">%2$s%3$s</div></figure>',
997 $wrapper_attributes,
998 $stage_markup,
999 $list_markup
1000 );
1001 }
1002
1003 /**
1004 * Enqueue the VideoPress Iframe API script
1005 * when the URL of oEmbed HTML is a VideoPress URL.
1006 *
1007 * @param string|false $cache The cached HTML result, stored in post meta.
1008 * @param string $url The attempted embed URL.
1009 * @param array $attr An array of shortcode attributes.
1010 * @param int $post_ID Post ID.
1011 *
1012 * @return string|false
1013 */
1014 public static function enqueue_videopress_iframe_api_script( $cache, $url, $attr, $post_ID ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1015 if ( Utils::is_videopress_url( $url ) && ! Inline_Player::is_enabled() ) {
1016 // Enqueue the VideoPress IFrame API in the front-end.
1017 wp_enqueue_script(
1018 self::JETPACK_VIDEOPRESS_IFRAME_API_HANDLER,
1019 'https://s0.wp.com/wp-content/plugins/video/assets/js/videojs/videopress-iframe-api.js',
1020 array(),
1021 gmdate( 'YW' ),
1022 false
1023 );
1024 }
1025
1026 return $cache;
1027 }
1028
1029 /**
1030 * Short-circuit the oEmbed request for VideoPress URLs when the inline player is on.
1031 *
1032 * @param null|string $result The oEmbed result, null to let WordPress fetch it.
1033 * @param string $url The URL being embedded.
1034 * @return null|string Inline player markup, or the untouched result.
1035 */
1036 public static function maybe_pre_oembed_inline_player( $result, $url ) {
1037 $inline = self::render_inline_player_for_url( $url );
1038
1039 return null === $inline ? $result : $inline;
1040 }
1041
1042 /**
1043 * Replace a VideoPress oEmbed iframe (fresh or cached) with an inline player when the inline player is on.
1044 *
1045 * @param string|false $cache The oEmbed HTML.
1046 * @param string $url The URL being embedded.
1047 * @param array $attr Shortcode attributes.
1048 * @param int $post_ID Post ID.
1049 * @return string|false Inline player markup, or the untouched HTML.
1050 */
1051 public static function maybe_render_oembed_inline_player( $cache, $url, $attr, $post_ID = null ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1052 if ( ! is_string( $cache ) || false === strpos( $cache, '<iframe' ) ) {
1053 return $cache;
1054 }
1055
1056 $inline = self::render_inline_player_for_url( $url );
1057
1058 return null === $inline ? $cache : $inline;
1059 }
1060
1061 /**
1062 * Build inline player markup for a videopress.com URL, honoring the player parameters in its query string.
1063 *
1064 * @param string $url The URL being embedded.
1065 * @return string|null Markup, or null when the URL is not a VideoPress video or the inline player is off.
1066 */
1067 private static function render_inline_player_for_url( $url ) {
1068 if ( ! Inline_Player::is_enabled() ) {
1069 return null;
1070 }
1071
1072 $guid = Utils::extract_videopress_guid_from_url( $url );
1073 if ( null === $guid ) {
1074 return null;
1075 }
1076
1077 return Inline_Player::render(
1078 $guid,
1079 Inline_Player::get_player_options( Inline_Player::get_attributes_from_embed_url( $url ) )
1080 );
1081 }
1082 }
1083