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