Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
41.08% covered (danger)
41.08%
76 / 185
8.33% covered (danger)
8.33%
1 / 12
CRAP
0.00% covered (danger)
0.00%
0 / 1
Initializer
41.08% covered (danger)
41.08%
76 / 185
8.33% covered (danger)
8.33%
1 / 12
627.53
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 update_init_options
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 should_initialize_admin_ui
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 unconditional_initialization
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 should_include_utilities
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 active_initialization
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
6
 register_oembed_providers
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 video_enqueue_bridge_when_oembed_present
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 register_videopress_blocks
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 render_videopress_video_block
73.00% covered (warning)
73.00%
73 / 100
0.00% covered (danger)
0.00%
0 / 1
31.53
 register_videopress_video_block
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
90
 enqueue_videopress_iframe_api_script
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * The initializer class for the videopress package
4 *
5 * @package automattic/jetpack-videopress
6 */
7
8namespace Automattic\Jetpack\VideoPress;
9
10/**
11 * Initialized the VideoPress package
12 */
13class Initializer {
14
15    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            }
39        }
40
41        /**
42         * Fires after the VideoPress package is initialized
43         *
44         * @since 0.1.1
45         */
46        do_action( 'videopress_init' );
47    }
48
49    /**
50     * Update the initialization options
51     *
52     * This method is called by the Config class
53     *
54     * @param array $options The initialization options.
55     * @return void
56     */
57    public static function update_init_options( array $options ) {
58        if ( empty( $options['admin_ui'] ) || self::should_initialize_admin_ui() ) { // do not overwrite if already set to true.
59            return;
60        }
61
62        self::$init_options['admin_ui'] = $options['admin_ui'];
63    }
64
65    /**
66     * Checks the initialization options and returns whether the admin_ui should be initialized or not
67     *
68     * @return boolean
69     */
70    public static function should_initialize_admin_ui() {
71        return isset( self::$init_options['admin_ui'] ) && true === self::$init_options['admin_ui'];
72    }
73
74    /**
75     * Initialize VideoPress features that should be initialized whenever VideoPress is present, even if the module is not active
76     *
77     * @return void
78     */
79    private static function unconditional_initialization() {
80        if ( self::should_include_utilities() ) {
81            require_once __DIR__ . '/utility-functions.php';
82        }
83
84        // Set up package version hook.
85        add_filter( 'jetpack_package_versions', __NAMESPACE__ . '\Package_Version::send_package_version_to_tracker' );
86
87        Module_Control::init();
88
89        new WPCOM_REST_API_V2_Endpoint_VideoPress();
90        new WPCOM_REST_API_V2_Attachment_VideoPress_Field();
91        new WPCOM_REST_API_V2_Attachment_VideoPress_Data();
92
93        if ( is_admin() ) {
94            AJAX::init();
95        } else {
96            require_once __DIR__ . '/class-block-replacement.php';
97            Block_Replacement::init();
98        }
99    }
100
101    /**
102     * This avoids conflicts when running VideoPress plugin with older versions of the Jetpack plugin
103     *
104     * On version 11.3-a.7 utility functions include were removed from the plugin and it is safe to include it from the package
105     *
106     * @return boolean
107     */
108    private static function should_include_utilities() {
109        if ( ! class_exists( 'Jetpack' ) || ! defined( 'JETPACK__VERSION' ) ) {
110            return true;
111        }
112
113        return version_compare( JETPACK__VERSION, '11.3-a.7', '>=' );
114    }
115
116    /**
117     * Initialize VideoPress features that should be initialized only when the module is active
118     *
119     * @return void
120     */
121    private static function active_initialization() {
122        Attachment_Handler::init();
123        Jwt_Token_Bridge::init();
124        Uploader_Rest_Endpoints::init();
125        Rest_Controller::init();
126        Initial_State::init();
127        VideoPress_Rest_Api_V1_Stats::init();
128        VideoPress_Rest_Api_V1_Site::init();
129        VideoPress_Rest_Api_V1_Settings::init();
130        VideoPress_Rest_Api_V1_Features::init();
131        XMLRPC::init();
132        Block_Editor_Content::init();
133        self::register_oembed_providers();
134
135        // Enqueuethe VideoPress Iframe API script in the front-end.
136        add_filter( 'embed_oembed_html', array( __CLASS__, 'enqueue_videopress_iframe_api_script' ), 10, 4 );
137
138        if ( self::should_initialize_admin_ui() ) {
139            Admin_UI::init();
140        }
141
142        Divi::init();
143    }
144
145    /**
146     * Explicitly register VideoPress oembed provider for patterns not supported by core
147     *
148     * @return void
149     */
150    public static function register_oembed_providers() {
151        $host = rawurlencode( home_url() );
152        // videopress.com/v is already registered in core.
153        // By explicitly declaring the provider here, we can speed things up by not relying on oEmbed discovery.
154        wp_oembed_add_provider( '#^https?://video.wordpress.com/v/.*#', 'https://public-api.wordpress.com/oembed/?for=' . $host, true );
155        // This is needed as it's not supported in oEmbed discovery
156        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
157
158        add_filter( 'embed_oembed_html', array( __CLASS__, 'video_enqueue_bridge_when_oembed_present' ), 10, 4 );
159    }
160
161    /**
162     * Enqueues VideoPress token bridge when a VideoPress oembed is present on the current page.
163     *
164     * @param string|false $cache   The cached HTML result, stored in post meta.
165     * @param string       $url     The attempted embed URL.
166     * @param array        $attr    An array of shortcode attributes.
167     * @param int          $post_ID Post ID.
168     *
169     * @return string|false
170     */
171    public static function video_enqueue_bridge_when_oembed_present( $cache, $url, $attr, $post_ID = null ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
172        if ( Utils::is_videopress_url( $url ) ) {
173            Jwt_Token_Bridge::enqueue_jwt_token_bridge();
174        }
175
176        return $cache;
177    }
178
179    /**
180     * Register all VideoPress blocks
181     *
182     * @return void
183     */
184    public static function register_videopress_blocks() {
185        // Register VideoPress Video block.
186        self::register_videopress_video_block();
187    }
188
189    /**
190     * VideoPress video block render method
191     *
192     * @global \WP_Embed $wp_embed WordPress embed handler.
193     *
194     * @param array     $block_attributes Block attributes.
195     * @param string    $content          Current block markup.
196     * @param \WP_Block $block            Current block.
197     *
198     * @return string Block markup.
199     */
200    public static function render_videopress_video_block( $block_attributes, $content, $block ) {
201        global $wp_embed;
202
203        // CSS classes.
204        $align        = $block_attributes['align'] ?? null;
205        $align_class  = $align ? ' align' . $align : '';
206        $custom_class = isset( $block_attributes['className'] ) ? ' ' . $block_attributes['className'] : '';
207        $classes      = 'wp-block-jetpack-videopress jetpack-videopress-player' . $custom_class . $align_class;
208
209        // Inline style.
210        $style     = '';
211        $max_width = $block_attributes['maxWidth'] ?? null;
212
213        if ( $max_width && $max_width !== '100%' ) {
214            $style    = sprintf( 'max-width: %s;', $max_width );
215            $classes .= ' wp-block-jetpack-videopress--has-max-width';
216        }
217
218        /*
219         * <figcaption /> element
220         * Caption is stored into the block attributes,
221         * but also it was stored into the <figcaption /> element,
222         * meaning that it could be stored in two different places.
223         */
224        $figcaption = '';
225
226        // Caption from block attributes.
227        $caption = $block_attributes['caption'] ?? null;
228
229        /*
230         * If the caption is not stored into the block attributes,
231         * try to get it from the <figcaption /> element.
232         */
233        if ( $caption === null ) {
234            preg_match( '/<figcaption>(.*?)<\/figcaption>/', $content, $matches );
235            $caption = $matches[1] ?? null;
236        }
237
238        // If we have a caption, create the <figcaption /> element.
239        if ( $caption !== null ) {
240            $figcaption = sprintf( '<figcaption>%s</figcaption>', wp_kses_post( $caption ) );
241        }
242
243        // Custom anchor from block content.
244        $id_attribute = '';
245
246        // Try to get the custom anchor from the block attributes.
247        if ( isset( $block_attributes['anchor'] ) && $block_attributes['anchor'] ) {
248            $id_attribute = sprintf( 'id="%s"', esc_attr( $block_attributes['anchor'] ) );
249        } elseif ( preg_match( '/<figure[^>]*id="([^"]+)"/', $content, $matches ) ) {
250            // Otherwise, try to get the custom anchor from the <figure /> element.
251            $id_attribute = sprintf( 'id="%s"', esc_attr( $matches[1] ) );
252        }
253
254        // Preview On Hover data.
255        $is_poh_enabled =
256            isset( $block_attributes['posterData']['previewOnHover'] ) &&
257            $block_attributes['posterData']['previewOnHover'];
258
259        $autoplay = $block_attributes['autoplay'] ?? false;
260        $controls = $block_attributes['controls'] ?? false;
261        $poster   = $block_attributes['posterData']['url'] ?? null;
262
263        $preview_on_hover = '';
264
265        if ( $is_poh_enabled ) {
266            $preview_on_hover = array(
267                'previewAtTime'       => $block_attributes['posterData']['previewAtTime'],
268                'previewLoopDuration' => $block_attributes['posterData']['previewLoopDuration'],
269                'autoplay'            => $autoplay,
270                'showControls'        => $controls,
271            );
272
273            // Create inline style in case video has a custom poster.
274            $inline_style = '';
275            if ( $poster ) {
276                $inline_style = sprintf(
277                    'style="background-image: url(%s); background-size: cover; background-position: center center;"',
278                    esc_attr( $poster )
279                );
280            }
281
282            // Expose the preview on hover data to the client.
283            $preview_on_hover = sprintf(
284                '<div class="jetpack-videopress-player__overlay" %s></div><script type="application/json">%s</script>',
285                $inline_style,
286                wp_json_encode( $preview_on_hover, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP )
287            );
288
289            // Set `autoplay` and `muted` attributes to the video element.
290            $block_attributes['autoplay'] = true;
291            $block_attributes['muted']    = true;
292        }
293
294        $figure_template = '
295        <figure class="%1$s" style="%2$s" %3$s>
296            %4$s
297            %5$s
298            %6$s
299        </figure>
300        ';
301
302        // VideoPress URL.
303        $guid           = $block_attributes['guid'] ?? null;
304        $videopress_url = Utils::get_video_press_url( $guid, $block_attributes );
305
306        $video_wrapper         = '';
307        $video_wrapper_classes = 'jetpack-videopress-player__wrapper';
308
309        if ( $videopress_url ) {
310            $videopress_url = wp_kses_post( $videopress_url );
311
312            /*
313             * Provide a fallback iframe for when the oEmbed endpoint fails, e.g.
314             * when the VideoPress backend isn't ready for a freshly uploaded video.
315             * This prevents the published page from showing a bare link.
316             */
317            $fallback = function ( $output, $url ) use ( $videopress_url ) {
318                if ( $url !== html_entity_decode( $videopress_url, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 ) ) {
319                    return $output;
320                }
321
322                return sprintf(
323                    '<iframe title="%1$s" aria-label="%1$s" src="%2$s" width="640" height="360" allowfullscreen data-resize-to-parent="true" allow="clipboard-write"></iframe>',
324                    esc_attr__( 'VideoPress Video Player', 'jetpack-videopress-pkg' ),
325                    esc_url( preg_replace( '#/v/#', '/embed/', $url, 1 ) )
326                );
327            };
328
329            add_filter( 'embed_maybe_make_link', $fallback, 10, 2 );
330            $oembed_html = apply_filters( 'video_embed_html', $wp_embed->shortcode( array(), $videopress_url ) );
331            remove_filter( 'embed_maybe_make_link', $fallback );
332
333            $video_wrapper = sprintf(
334                '<div class="%s">%s %s</div>',
335                $video_wrapper_classes,
336                $preview_on_hover,
337                $oembed_html
338            );
339
340            /*
341             * Self-heal failed oEmbed cache for VideoPress URLs.
342             *
343             * When the VideoPress backend isn't ready for a freshly uploaded video,
344             * WordPress caches '{{unknown}}' in post meta with a TTL that is too long
345             * for this use case. Clear recent failures so the next page render retries
346             * oEmbed discovery, keeping the fallback iframe above temporary.
347             */
348            $post_id = $block->context['postId'] ?? get_the_ID();
349
350            if ( $post_id ) {
351                $key_suffix   = md5( $videopress_url . serialize( wp_embed_defaults( $videopress_url ) ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize -- Matching WP_Embed cache key format.
352                $oembed_value = get_post_meta( $post_id, '_oembed_' . $key_suffix, true );
353                $oembed_time  = (int) get_post_meta( $post_id, '_oembed_time_' . $key_suffix, true );
354
355                /*
356                 * Only clear the '{{unknown}}' cache entry when it is recent, to avoid
357                 * disabling WordPress's oEmbed backoff for persistent provider failures.
358                 */
359                if (
360                    '{{unknown}}' === $oembed_value
361                    && ( ! $oembed_time || ( time() - $oembed_time ) < MINUTE_IN_SECONDS )
362                ) {
363                    delete_post_meta( $post_id, '_oembed_' . $key_suffix );
364                    delete_post_meta( $post_id, '_oembed_time_' . $key_suffix );
365                }
366            }
367        }
368
369        // Get premium content from block context.
370        $premium_block_plan_id    = isset( $block->context['premium-content/planId'] ) ? intval( $block->context['premium-content/planId'] ) : 0;
371        $is_premium_content_child = isset( $block->context['isPremiumContentChild'] ) ? (bool) $block->context['isPremiumContentChild'] : false;
372        $maybe_premium_script     = '';
373        if ( $is_premium_content_child ) {
374            Access_Control::instance()->set_guid_subscription( $guid, $premium_block_plan_id );
375            $escaped_guid         = wp_json_encode( $guid, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
376            $script_content       = "if ( ! window.__guidsToPlanIds ) { window.__guidsToPlanIds = {}; }; window.__guidsToPlanIds[$escaped_guid] = $premium_block_plan_id;";
377            $maybe_premium_script = '<script>' . $script_content . '</script>';
378        }
379
380        // $id_attribute, $video_wrapper, $figcaption properly escaped earlier in the code.
381        return sprintf(
382            $figure_template,
383            esc_attr( $classes ),
384            esc_attr( $style ),
385            $id_attribute,
386            $video_wrapper,
387            $figcaption,
388            $maybe_premium_script
389        );
390    }
391
392    /**
393     * Register the VideoPress block editor block,
394     * AKA "VideoPress Block v6".
395     *
396     * @return void
397     */
398    public static function register_videopress_video_block() {
399        /*
400         * If only Jetpack is active, and if the VideoPress module is not active,
401         * we can register the block just to display a placeholder to turn on the module.
402         * That invitation is only useful for admins though.
403         */
404        if (
405            Status::is_jetpack_plugin_without_videopress_module_active()
406            && ! Status::is_standalone_plugin_active()
407            && ! current_user_can( 'jetpack_activate_modules' )
408        ) {
409            return;
410        }
411
412        $videopress_video_metadata_file        = __DIR__ . '/../build/block-editor/blocks/video/block.json';
413        $videopress_video_metadata_file_exists = file_exists( $videopress_video_metadata_file );
414        if ( ! $videopress_video_metadata_file_exists ) {
415            return;
416        }
417
418        $videopress_video_metadata = json_decode(
419            // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
420            file_get_contents( $videopress_video_metadata_file )
421        );
422
423        // Pick the block name straight from the block metadata .json file.
424        $videopress_video_block_name = $videopress_video_metadata->name;
425
426        // Is the block already registered?
427        $is_block_registered = \WP_Block_Type_Registry::get_instance()->is_registered( $videopress_video_block_name );
428
429        // Do not register if the block is already registered.
430        if ( $is_block_registered ) {
431            return;
432        }
433
434        $registration = register_block_type(
435            $videopress_video_metadata_file,
436            array(
437                'render_callback'       => array( __CLASS__, 'render_videopress_video_block' ),
438                'render_email_callback' => array( Video_Block_Email_Renderer::class, 'render' ),
439                'uses_context'          => array( 'premium-content/planId', 'isPremiumContentChild', 'selectedPlanId' ),
440            )
441        );
442
443        // Do not enqueue scripts if the block could not be registered.
444        if ( empty( $registration ) || empty( $registration->editor_script_handles ) ) {
445            return;
446        }
447
448        // Extensions use Connection_Initial_State::render_script with script handle as parameter.
449        if ( is_array( $registration->editor_script_handles ) ) {
450            $script_handle = $registration->editor_script_handles[0];
451        } else {
452            $script_handle = $registration->editor_script_handles;
453        }
454
455        // Register and enqueue scripts used by the VideoPress video block.
456        Block_Editor_Extensions::init( $script_handle );
457    }
458
459    /**
460     * Enqueue the VideoPress Iframe API script
461     * when the URL of oEmbed HTML is a VideoPress URL.
462     *
463     * @param string|false $cache   The cached HTML result, stored in post meta.
464     * @param string       $url     The attempted embed URL.
465     * @param array        $attr    An array of shortcode attributes.
466     * @param int          $post_ID Post ID.
467     *
468     * @return string|false
469     */
470    public static function enqueue_videopress_iframe_api_script( $cache, $url, $attr, $post_ID ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
471        if ( Utils::is_videopress_url( $url ) ) {
472            // Enqueue the VideoPress IFrame API in the front-end.
473            wp_enqueue_script(
474                self::JETPACK_VIDEOPRESS_IFRAME_API_HANDLER,
475                'https://s0.wp.com/wp-content/plugins/video/assets/js/videojs/videopress-iframe-api.js',
476                array(),
477                gmdate( 'YW' ),
478                false
479            );
480        }
481
482        return $cache;
483    }
484}