Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
76.81% covered (warning)
76.81%
106 / 138
25.00% covered (danger)
25.00%
1 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
Block_Editor_Content
76.81% covered (warning)
76.81%
106 / 138
25.00% covered (danger)
25.00%
1 / 4
57.96
0.00% covered (danger)
0.00%
0 / 1
 init
77.78% covered (warning)
77.78%
7 / 9
0.00% covered (danger)
0.00%
0 / 1
4.18
 videopress_embed_shortcode
96.43% covered (success)
96.43%
81 / 84
0.00% covered (danger)
0.00%
0 / 1
14
 videopress_video_block_by_guid
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
7
 video_shortcode_override
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
210
1<?php
2/**
3 * VideoPress Block Editor Content
4 *
5 * @package automattic/jetpack-videopress
6 */
7
8namespace Automattic\Jetpack\VideoPress;
9
10use WP_Post;
11
12/**
13 * VideoPress block editor class for content generation
14 */
15class Block_Editor_Content {
16    /**
17     * Initializer
18     *
19     * This method should be called only once by the Initializer class. Do not call this method again.
20     */
21    public static function init() {
22        if ( Status::is_standalone_plugin_active() ) {
23            // Remove the videopress shortcodes added by the Jetpack plugin.
24            if ( shortcode_exists( 'videopress' ) ) {
25                remove_shortcode( 'videopress' );
26            }
27            if ( shortcode_exists( 'wpvideo' ) ) {
28                remove_shortcode( 'wpvideo' );
29            }
30
31            add_shortcode( 'videopress', array( static::class, 'videopress_embed_shortcode' ) );
32            add_shortcode( 'wpvideo', array( static::class, 'videopress_embed_shortcode' ) );
33
34            add_filter( 'wp_video_shortcode_override', array( static::class, 'video_shortcode_override' ), 10, 4 );
35        }
36
37        add_filter( 'default_content', array( static::class, 'videopress_video_block_by_guid' ), 10, 2 );
38    }
39
40    /**
41     * VideoPress embed shortcode
42     *
43     * Expected input format:
44     * [videopress tLvEwHYZ]
45     *
46     * @param array $atts Shortcode attributes.
47     *
48     * @return string html
49     */
50    public static function videopress_embed_shortcode( $atts ) {
51        /**
52         * We only accept GUIDs as a first unnamed argument.
53         */
54        $guid = $atts[0] ?? null;
55
56        /**
57         * Make sure the GUID passed in matches how actual GUIDs are formatted.
58         */
59        if ( ! videopress_is_valid_guid( $guid ) ) {
60            return '<!-- error: missing or invalid VideoPress video ID -->';
61        }
62
63        /**
64         * Set the defaults
65         */
66        $defaults = array(
67            'w'               => 640,   // Width of the video player, in pixels
68            'h'               => 0,     // Height of the video player, in pixels
69            'at'              => 0,     // How many seconds in to initially seek to
70            'loop'            => false, // Whether to loop the video repeatedly
71            'autoplay'        => false, // Whether to autoplay the video on load
72            'cover'           => true,  // Whether to scale the video to its container
73            'muted'           => false, // Whether the video should start without sound
74            'controls'        => true,  // Whether the video should display controls
75            'playsinline'     => false, // Whether the video should be allowed to play inline (for browsers that support this)
76            'useaveragecolor' => false, // Whether the video should use the seekbar automatic average color
77            'preloadcontent'  => 'metadata',
78        );
79
80        // Make sure "false" will be actually false.
81        foreach ( $atts as $key => $value ) {
82            if ( is_string( $value ) && 'false' === strtolower( $value ) ) {
83                $atts[ $key ] = 0;
84            }
85        }
86
87        if ( isset( $atts['preload'] ) && videopress_is_valid_preload( $atts['preload'] ) ) {
88            $atts['preloadcontent'] = $atts['preload'];
89        }
90
91        if ( isset( $atts['preloadcontent'] ) && ! videopress_is_valid_preload( $atts['preloadcontent'] ) ) {
92            unset( $atts['preloadcontent'] );
93        }
94
95        // The site-wide opt-out wins over the shortcode's own preload attribute.
96        if ( Data::get_videopress_player_preload_disabled() ) {
97            $atts['preloadcontent'] = 'none';
98        }
99
100        $atts = shortcode_atts( $defaults, $atts, 'videopress' );
101
102        $base_url     = 'https://videopress.com/embed/' . $guid;
103        $query_params = array(
104            'at'              => $atts['at'],
105            'loop'            => $atts['loop'],
106            'autoplay'        => $atts['autoplay'],
107            'muted'           => $atts['muted'],
108            'controls'        => $atts['controls'],
109            'playsinline'     => $atts['playsinline'],
110            'useAverageColor' => $atts['useaveragecolor'], // The casing is intentional, shortcode params are lowercase, but player expects useAverageColor
111            'preloadContent'  => $atts['preloadcontent'], // The casing is intentional, shortcode params are lowercase, but player expects preloadContent
112        );
113        $src          = esc_url( add_query_arg( $query_params, $base_url ) );
114
115        $width = absint( $atts['w'] );
116        if ( ! $atts['h'] ) {
117            $aspect_ratio = 16 / 9; // TODO: Get the correct aspect ratio for the video.
118            $height       = $width / $aspect_ratio;
119        } else {
120            $height = absint( $atts['h'] );
121        }
122
123        if ( Inline_Player::is_enabled() ) {
124            $player = Inline_Player::render(
125                $guid,
126                Inline_Player::get_player_options(
127                    array(
128                        'autoplay'        => $atts['autoplay'],
129                        'loop'            => $atts['loop'],
130                        'muted'           => $atts['muted'],
131                        'controls'        => $atts['controls'],
132                        'playsinline'     => $atts['playsinline'],
133                        'useAverageColor' => $atts['useaveragecolor'],
134                        'preload'         => $atts['preloadcontent'],
135                        'cover'           => $atts['cover'],
136                        'at'              => $atts['at'],
137                    )
138                ),
139                $width > 0 ? ( $height / $width ) * 100 : null,
140                array( 'poster' => Inline_Player::get_poster_url( $guid ) )
141            );
142
143            return '<figure class="wp-block-videopress-video wp-block-jetpack-videopress jetpack-videopress-player">' .
144                '<div class="jetpack-videopress-player__wrapper">' . $player . '</div>' .
145            '</figure>';
146        }
147
148        $cover = $atts['cover'] ? ' data-resize-to-parent="true"' : '';
149
150        $block_template =
151        '<figure class="wp-block-videopress-video wp-block-jetpack-videopress jetpack-videopress-player">' .
152            '<div class="jetpack-videopress-player__wrapper">' .
153                '<iframe ' .
154                    'title="' . __( 'VideoPress Video Player', 'jetpack-videopress-pkg' ) . '" ' .
155                    'aria-label="' . __( 'VideoPress Video Player', 'jetpack-videopress-pkg' ) . '" ' .
156                    'src="%s" ' .
157                    'width="%s" ' .
158                    'height="%s" ' .
159                    'frameborder="0" ' .
160                    'allowfullscreen%s allow="clipboard-write; presentation">' .
161                '</iframe>' .
162            '</div>' .
163        '</figure>';
164
165        $version = Package_Version::PACKAGE_VERSION;
166        Jwt_Token_Bridge::enqueue_jwt_token_bridge();
167        wp_enqueue_script( 'videopress-iframe', 'https://videopress.com/videopress-iframe.js', array(), $version, true );
168
169        return sprintf( $block_template, $src, $width, $height, $cover );
170    }
171
172    /**
173     * Generates a VideoPress video block content with the given guid
174     *
175     * @param string  $content Post content.
176     * @param WP_Post $post Post.
177     * @return string
178     */
179    public static function videopress_video_block_by_guid( $content, $post ) {
180        if ( isset( $_GET['videopress_guid'] ) && isset( $_GET['_wpnonce'] )
181            && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'videopress-content-nonce' )
182            && current_user_can( 'edit_post', $post->ID )
183            && '' === $content
184        ) {
185            $guid = sanitize_text_field( wp_unslash( $_GET['videopress_guid'] ) );
186
187            $base_url     = 'https://videopress.com/v/' . $guid;
188            $query_params = array(
189                'resizeToParent'  => 'true',
190                'cover'           => 'true',
191                'preloadContent'  => 'metadata',
192                'useAverageColor' => 'true',
193            );
194            $url          = esc_url( add_query_arg( $query_params, $base_url ) );
195
196            if ( ! empty( $guid ) ) {
197                // ref /client/lib/url/index.ts
198                $content = '<!-- wp:videopress/video {"guid":"' . $guid . '"} -->
199                <figure class="wp-block-videopress-video wp-block-jetpack-videopress jetpack-videopress-player">
200                    <div class="jetpack-videopress-player__wrapper">' . $url . '</div>
201                </figure>
202                <!-- /wp:videopress/video -->';
203            }
204        }
205
206        return $content;
207    }
208
209    /**
210     * Override the standard video short tag to also process videopress files as well.
211     *
212     * This will parse the given src and, if it is a videopress file, parse as the
213     * VideoPress shortcode instead.
214     *
215     * @param string $html     Empty variable to be replaced with shortcode markup.
216     * @param array  $attr     Attributes of the video shortcode.
217     * @param string $content  Video shortcode content.
218     * @param int    $instance Unique numeric ID of this video shortcode instance.
219     *
220     * @return string
221     */
222    public static function video_shortcode_override( $html, $attr, $content, $instance ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
223        $videopress_guid = null;
224
225        if ( isset( $attr['videopress_guid'] ) ) {
226            $videopress_guid = $attr['videopress_guid'];
227        } else {
228            // Handle the different possible url attributes
229            $url_keys = array( 'src', 'mp4' );
230
231            foreach ( $url_keys as $key ) {
232                if ( isset( $attr[ $key ] ) ) {
233                    $url = $attr[ $key ];
234                    // phpcs:ignore WordPress.WP.CapitalPDangit
235                    if ( preg_match( '@videos.(videopress\.com|files\.wordpress\.com)/([a-z0-9]{8})/@i', $url, $matches ) ) {
236                        $videopress_guid = $matches[2];
237                    }
238
239                    // Also test for videopress oembed url, which is used by the Video Media Widget.
240                    if ( ! $videopress_guid && preg_match( '@https://videopress.com/v/([a-z0-9]{8})@i', $url, $matches ) ) {
241                        $videopress_guid = $matches[1];
242                    }
243
244                    // Also test for old v.wordpress.com oembed URL.
245                    if ( ! $videopress_guid && preg_match( '|^https?://v\.wordpress\.com/([a-zA-Z\d]{8})(.+)?$|i', $url, $matches ) ) { // phpcs:ignore WordPress.WP.CapitalPDangit.MisspelledInText
246                        $videopress_guid = $matches[1];
247                    }
248
249                    break;
250                }
251            }
252        }
253
254        if ( $videopress_guid ) {
255            $videopress_atts = array( $videopress_guid );
256
257            // height is ignored on jetpack video block, so we don't pass it for consistency.
258            if ( isset( $attr['width'] ) ) {
259                $videopress_atts['w'] = (int) $attr['width'];
260            }
261            if ( isset( $attr['muted'] ) ) {
262                $videopress_atts['muted'] = $attr['muted'];
263            }
264            if ( isset( $attr['autoplay'] ) ) {
265                $videopress_atts['autoplay'] = $attr['autoplay'];
266            }
267            if ( isset( $attr['loop'] ) ) {
268                $videopress_atts['loop'] = $attr['loop'];
269            }
270            // The core video block doesn't support the cover attribute, setting it to false for consistency.
271            $videopress_atts['cover'] = false;
272
273            // Then display the VideoPress version of the stored GUID!
274            return self::videopress_embed_shortcode( $videopress_atts );
275        }
276
277        return '';
278    }
279}