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