Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
98.60% covered (success)
98.60%
212 / 215
84.62% covered (warning)
84.62%
11 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
Inline_Player
98.60% covered (success)
98.60%
212 / 215
84.62% covered (warning)
84.62%
11 / 13
79
0.00% covered (danger)
0.00%
0 / 1
 is_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_player_options
96.23% covered (success)
96.23%
51 / 53
0.00% covered (danger)
0.00%
0 / 1
12
 get_attributes_from_embed_url
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
11
 get_asset_config
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_assets
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
3
 should_use_facade
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_poster_url
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
12
 is_private
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 get_poster_from_attachment
93.33% covered (success)
93.33%
14 / 15
0.00% covered (danger)
0.00%
0 / 1
13.05
 facade_css
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
1
 render
100.00% covered (success)
100.00%
47 / 47
100.00% covered (success)
100.00%
1 / 1
16
 reset
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 to_bool
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * Inline (non-iframe) VideoPress player rendering.
4 *
5 * @package automattic/jetpack-videopress
6 */
7
8namespace Automattic\Jetpack\VideoPress;
9
10/**
11 * Renders VideoPress players in the page from one shared player script.
12 *
13 * Every `videopress.com/embed/` iframe downloads and runs its own copy of the
14 * player, so a page pays for it once per video. In inline mode the player
15 * bundle and stylesheet load once from v0.wordpress.com and a small boot
16 * script mounts a player on each placeholder.
17 */
18class Inline_Player {
19
20    const PLAYER_SCRIPT_URL = 'https://v0.wordpress.com/js/videojs/videopress.js';
21    const PLAYER_STYLE_URL  = 'https://v0.wordpress.com/js/videojs/videopress.css';
22
23    // The Jetpack plugin's legacy in-page embed used this handle; keep it so existing dequeue hooks still apply.
24    const PLAYER_HANDLE = 'videopress-videojs';
25    const BOOT_HANDLE   = 'videopress-inline-player';
26
27    const PLACEHOLDER_CLASS = 'jetpack-videopress-player__inline';
28    const FACADE_CLASS      = 'jetpack-videopress-player__facade';
29
30    /**
31     * How many placeholders this request has rendered; the first poster stays eager, later ones lazy-load.
32     *
33     * @var int
34     */
35    private static $rendered = 0;
36
37    /**
38     * Whether the boot script's config has been printed for this request.
39     *
40     * @var bool
41     */
42    private static $config_printed = false;
43
44    /**
45     * Whether embeds rendered by this site should mount an inline player instead of an iframe.
46     *
47     * @return bool
48     */
49    public static function is_enabled() {
50        /**
51         * Filter whether VideoPress videos are embedded with an iframe.
52         *
53         * Return false to render the player directly in the page from one shared
54         * player script. Defaults to the inverse of the site's inline player setting.
55         *
56         * @module videopress
57         *
58         * @since 3.7.0
59         *
60         * @param bool $use_iframe Whether to embed with an iframe.
61         */
62        return ! apply_filters( 'jetpack_videopress_player_use_iframe', ! Data::get_videopress_inline_player_enabled() );
63    }
64
65    /**
66     * Map block or shortcode attributes to player options.
67     *
68     * Accepts the video block's attribute names (`autoplay`, `preload`, ...);
69     * anything missing falls back to the player's defaults.
70     *
71     * @param array $attributes Attributes to map.
72     * @return array Player options, ready to pass to `videopress()`.
73     */
74    public static function get_player_options( array $attributes = array() ) {
75        $attributes = wp_parse_args(
76            $attributes,
77            array(
78                'autoplay'            => false,
79                'controls'            => true,
80                'loop'                => false,
81                'muted'               => false,
82                // On by default, as in Utils::get_video_press_url().
83                'playsinline'         => true,
84                'poster'              => '',
85                'preload'             => 'metadata',
86                'seekbarColor'        => '',
87                'seekbarPlayedColor'  => '',
88                'seekbarLoadingColor' => '',
89                'useAverageColor'     => true,
90                'cover'               => true,
91                'hd'                  => false,
92                'at'                  => 0,
93                'defaultLangCode'     => '',
94            )
95        );
96
97        $preload = is_string( $attributes['preload'] ) ? strtolower( $attributes['preload'] ) : 'metadata';
98        if ( ! in_array( $preload, array( 'auto', 'metadata', 'none' ), true ) ) {
99            $preload = 'metadata';
100        }
101        // The site-wide opt-out wins over the embed's own preload attribute.
102        if ( Data::get_videopress_player_preload_disabled() ) {
103            $preload = 'none';
104        }
105
106        $options = array(
107            'autoPlay'        => self::to_bool( $attributes['autoplay'] ),
108            'controls'        => self::to_bool( $attributes['controls'] ),
109            'loop'            => self::to_bool( $attributes['loop'] ),
110            'muted'           => self::to_bool( $attributes['muted'] ),
111            'persistVolume'   => ! self::to_bool( $attributes['muted'] ),
112            'playsinline'     => self::to_bool( $attributes['playsinline'] ),
113            'cover'           => self::to_bool( $attributes['cover'] ),
114            'hd'              => self::to_bool( $attributes['hd'] ),
115            'useAverageColor' => self::to_bool( $attributes['useAverageColor'] ),
116            'preloadContent'  => $preload,
117            // Embed pages default to the current player skin; match them.
118            'chrome'          => 'v2',
119        );
120
121        if ( (int) $attributes['at'] > 0 ) {
122            $options['at'] = (int) $attributes['at'];
123        }
124
125        if ( ! empty( $attributes['poster'] ) && is_string( $attributes['poster'] ) ) {
126            $options['poster'] = esc_url_raw( $attributes['poster'] );
127        }
128
129        if ( ! empty( $attributes['defaultLangCode'] ) && is_string( $attributes['defaultLangCode'] ) ) {
130            $options['defaultLangCode'] = $attributes['defaultLangCode'];
131        }
132
133        $colors = array(
134            'seekbarColor'        => 'seekbarColor',
135            'seekbarPlayedColor'  => 'seekbarPlayedColor',
136            'seekbarLoadingColor' => 'seekbarLoadedColor',
137        );
138        foreach ( $colors as $attribute => $option ) {
139            if ( ! empty( $attributes[ $attribute ] ) && is_string( $attributes[ $attribute ] ) ) {
140                $options[ $option ] = $attributes[ $attribute ];
141            }
142        }
143
144        /**
145         * Filter the options passed to an inline VideoPress player.
146         *
147         * @since 0.50.2
148         *
149         * @param array $options    Player options.
150         * @param array $attributes The block or shortcode attributes they were built from.
151         */
152        return apply_filters( 'jetpack_videopress_inline_player_options', $options, $attributes );
153    }
154
155    /**
156     * Read the player attributes an embed URL carries in its query string.
157     *
158     * Used to render inline players for videopress.com URLs that reach the
159     * page through oEmbed. Only parameters present in the URL are returned.
160     *
161     * @param string $url A videopress.com/v or /embed URL.
162     * @return array Attributes in the shape `get_player_options()` accepts.
163     */
164    public static function get_attributes_from_embed_url( $url ) {
165        $query = wp_parse_url( $url, PHP_URL_QUERY );
166        if ( ! is_string( $query ) || '' === $query ) {
167            return array();
168        }
169
170        $params = array();
171        parse_str( html_entity_decode( $query, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 ), $params );
172
173        $booleans = array(
174            'autoPlay'        => 'autoplay',
175            'autoplay'        => 'autoplay',
176            'controls'        => 'controls',
177            'loop'            => 'loop',
178            'muted'           => 'muted',
179            'playsinline'     => 'playsinline',
180            'useAverageColor' => 'useAverageColor',
181            'cover'           => 'cover',
182            'hd'              => 'hd',
183        );
184        $strings  = array(
185            'posterUrl'       => 'poster',
186            'preloadContent'  => 'preload',
187            'sbc'             => 'seekbarColor',
188            'sbpc'            => 'seekbarPlayedColor',
189            'sblc'            => 'seekbarLoadingColor',
190            'defaultLangCode' => 'defaultLangCode',
191        );
192
193        $attributes = array();
194        foreach ( $booleans as $param => $attribute ) {
195            if ( isset( $params[ $param ] ) && is_string( $params[ $param ] ) ) {
196                $attributes[ $attribute ] = self::to_bool( $params[ $param ] );
197            }
198        }
199        foreach ( $strings as $param => $attribute ) {
200            if ( ! empty( $params[ $param ] ) && is_string( $params[ $param ] ) ) {
201                $attributes[ $attribute ] = $params[ $param ];
202            }
203        }
204        if ( isset( $params['at'] ) && (int) $params['at'] > 0 ) {
205            $attributes['at'] = (int) $params['at'];
206        }
207
208        return $attributes;
209    }
210
211    /**
212     * Versioned URLs of the player bundle and its stylesheet, for anything that loads the player itself.
213     *
214     * @return array{script: string, style: string}
215     */
216    public static function get_asset_config() {
217        return array(
218            'script' => add_query_arg( 'ver', Package_Version::PACKAGE_VERSION, self::PLAYER_SCRIPT_URL ),
219            'style'  => add_query_arg( 'ver', Package_Version::PACKAGE_VERSION, self::PLAYER_STYLE_URL ),
220        );
221    }
222
223    /**
224     * Enqueue the boot script and, unless every player on the page sits behind a facade, the shared player assets.
225     *
226     * The boot script never depends on the player handle: behind a facade it fetches the
227     * bundle itself on the first click, from the URLs printed in its config.
228     *
229     * @param bool $defer_player True to leave the player bundle for the boot script to load on demand.
230     */
231    public static function enqueue_assets( $defer_player = false ) {
232        wp_enqueue_script(
233            self::BOOT_HANDLE,
234            plugins_url( '../build/lib/inline-player.js', __FILE__ ),
235            array(),
236            Package_Version::PACKAGE_VERSION,
237            true
238        );
239
240        if ( ! self::$config_printed ) {
241            self::$config_printed = true;
242            wp_add_inline_script(
243                self::BOOT_HANDLE,
244                'window.jetpackVideoPressInlinePlayer = ' . wp_json_encode( self::get_asset_config(), JSON_UNESCAPED_SLASHES ) . ';',
245                'before'
246            );
247        }
248
249        if ( ! $defer_player ) {
250            wp_enqueue_style( self::PLAYER_HANDLE, self::PLAYER_STYLE_URL, array(), Package_Version::PACKAGE_VERSION );
251            wp_enqueue_script( self::PLAYER_HANDLE, self::PLAYER_SCRIPT_URL, array(), Package_Version::PACKAGE_VERSION, true );
252        }
253
254        // Private videos ask the page for a playback token, same as iframes do.
255        Jwt_Token_Bridge::enqueue_jwt_token_bridge();
256    }
257
258    /**
259     * Whether a placeholder should start as a poster facade instead of a mounted player.
260     *
261     * Autoplaying videos need the player at once; everything else can wait for a click.
262     *
263     * @param array $options Player options, see `get_player_options()`.
264     * @return bool
265     */
266    public static function should_use_facade( array $options = array() ) {
267        $use_facade = empty( $options['autoPlay'] );
268
269        /**
270         * Filter whether inline VideoPress players start as a poster facade and load the player on click.
271         *
272         * @since 0.51.0
273         *
274         * @param bool  $use_facade Whether to render the facade.
275         * @param array $options    The player options for this video.
276         */
277        return (bool) apply_filters( 'jetpack_videopress_inline_player_facade', $use_facade, $options );
278    }
279
280    /**
281     * Resolve the poster to show in a facade, without ever exposing a private video's frame.
282     *
283     * Order: the block's own poster attribute, the attachment's VideoPress metadata
284     * ( by `id`, else by GUID ), then the transient-cached video details lookup.
285     *
286     * @param string $guid       Video GUID.
287     * @param array  $attributes Block or shortcode attributes ( `poster`, `id`, `isPrivate`, `privacySetting` ).
288     * @return string|null Poster URL, or null when none is usable.
289     */
290    public static function get_poster_url( $guid, array $attributes = array() ) {
291        $poster = null;
292
293        if ( ! empty( $attributes['poster'] ) && is_string( $attributes['poster'] ) ) {
294            $poster = esc_url_raw( $attributes['poster'] );
295        } elseif ( ! self::is_private( $attributes ) ) {
296            $poster = self::get_poster_from_attachment( $guid, $attributes['id'] ?? 0 );
297
298            if ( null === $poster && function_exists( 'videopress_get_video_details' ) ) {
299                $details = videopress_get_video_details( $guid );
300                if ( is_object( $details ) && empty( $details->is_private ) && ! empty( $details->poster ) && is_string( $details->poster ) ) {
301                    $poster = esc_url_raw( $details->poster );
302                }
303            }
304        }
305
306        /**
307         * Filter the poster shown by an inline VideoPress player's facade.
308         *
309         * @since 0.51.0
310         *
311         * @param string|null $poster     Poster URL, or null for a plain dark facade.
312         * @param string      $guid       Video GUID.
313         * @param array       $attributes The block or shortcode attributes.
314         */
315        $poster = apply_filters( 'jetpack_videopress_inline_player_poster', $poster, $guid, $attributes );
316
317        return is_string( $poster ) && '' !== $poster ? $poster : null;
318    }
319
320    /**
321     * Whether the attributes describe a private video, treating "site default" as the site's own setting.
322     *
323     * @param array $attributes Block attributes.
324     * @return bool
325     */
326    private static function is_private( array $attributes ) {
327        if ( ! empty( $attributes['isPrivate'] ) ) {
328            return true;
329        }
330
331        // A privacy setting of one is private and two follows the site default; anything else is public.
332        $privacy = isset( $attributes['privacySetting'] ) ? (int) $attributes['privacySetting'] : 2;
333        if ( 1 === $privacy ) {
334            return true;
335        }
336
337        return 2 === $privacy && Data::get_videopress_videos_private_for_site();
338    }
339
340    /**
341     * Poster from the local attachment's VideoPress metadata, when the attachment belongs to this GUID.
342     *
343     * @param string $guid          Video GUID.
344     * @param int    $attachment_id Attachment ID from the block, 0 to look the post up by GUID.
345     * @return string|null
346     */
347    private static function get_poster_from_attachment( $guid, $attachment_id = 0 ) {
348        $attachment_id = (int) $attachment_id;
349
350        if ( $attachment_id <= 0 && function_exists( 'videopress_get_post_by_guid' ) ) {
351            $post          = videopress_get_post_by_guid( $guid );
352            $attachment_id = ( $post instanceof \WP_Post ) ? $post->ID : 0;
353        }
354
355        if ( $attachment_id <= 0 ) {
356            return null;
357        }
358
359        $meta       = wp_get_attachment_metadata( $attachment_id );
360        $videopress = is_array( $meta ) && isset( $meta['videopress'] ) && is_array( $meta['videopress'] ) ? $meta['videopress'] : array();
361        $poster     = $videopress['poster'] ?? '';
362        $meta_guid  = $videopress['guid'] ?? '';
363
364        if ( ! is_string( $poster ) || '' === $poster ) {
365            return null;
366        }
367
368        // A block can point at another video than its attachment does; trust the GUID.
369        if ( is_string( $meta_guid ) && '' !== $meta_guid && $meta_guid !== $guid ) {
370            return null;
371        }
372
373        return esc_url_raw( $poster );
374    }
375
376    /**
377     * Stylesheet for the facade, printed inline so no extra request stands between the HTML and the poster.
378     *
379     * The play button, pre-play scrim and loading spinner copy the player's own chrome, so
380     * nothing visibly changes when the player takes the facade's place.
381     *
382     * @return string CSS.
383     */
384    private static function facade_css() {
385        $p = '.' . self::PLACEHOLDER_CLASS;
386        $f = '.' . self::FACADE_CLASS;
387        return $p . '.is-facade{background:#000;container-type:inline-size;--jetpack-videopress-play-size:min(max(calc(100vw / 8),60px),90px)}'
388            . $f . '{position:absolute;inset:0;width:100%;height:100%;margin:0;padding:0;border:0;background:transparent;cursor:pointer;display:block;line-height:0}'
389            . $f . '-poster{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}'
390            . $f . '-scrim{position:absolute;inset:0;pointer-events:none;background:radial-gradient(50% 50% at 50% 50%,rgba(0,0,0,.14) 0%,rgba(0,0,0,.3) 100%)}'
391            . $f . '-play{position:absolute;top:50%;left:50%;width:var(--jetpack-videopress-play-size);height:var(--jetpack-videopress-play-size);transform:translate(-50%,-50%);display:block;transition:transform .25s cubic-bezier(.4,0,.6,1) .04s;will-change:transform}'
392            . $f . '-play svg{display:block;width:100%;height:100%;fill:#fff}'
393            . $p . '.is-facade:hover ' . $f . '-play{transform:translate(-50%,-50%) scale(1.08)}'
394            . $f . ':focus-visible{outline:2px solid #fff;outline-offset:-4px}'
395            . $f . '-spinner{position:absolute;inset:0;z-index:2;display:none;align-items:center;justify-content:center;pointer-events:none}'
396            . $f . '-spinner span{display:flex;align-items:center;justify-content:center;width:48px;height:48px;border-radius:999px;background:rgba(18,18,18,.55);-webkit-backdrop-filter:blur(12px) saturate(1.2);backdrop-filter:blur(12px) saturate(1.2);box-shadow:0 4px 16px rgba(0,0,0,.35)}'
397            . $f . '-spinner span::after{content:"";box-sizing:border-box;width:24px;height:24px;border:2px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:jetpack-videopress-spin 750ms linear infinite}'
398            . $p . '.is-loading ' . $f . '-play{display:none}'
399            . $p . '.is-loading ' . $f . '-spinner{display:flex}'
400            . '@keyframes jetpack-videopress-spin{to{transform:rotate(360deg)}}'
401            . '@container (max-width:250px){' . $f . '-spinner span{width:40px;height:40px}}'
402            . '@media screen and (max-width:200px){' . $p . '.is-facade{--jetpack-videopress-play-size:40px}' . $f . '-play{opacity:.75}}'
403            . '@media (prefers-reduced-motion:reduce){' . $f . '-play{transition:none}}';
404    }
405
406    /**
407     * Render the placeholder the boot script mounts a player on.
408     *
409     * @param string     $guid    Video GUID.
410     * @param array      $options Player options, see `get_player_options()`.
411     * @param float|null $ratio   Height as a percentage of width (the block's `videoRatio`); 16:9 when unknown.
412     * @param array      $args    Optional `poster` ( URL ), `title` ( for the play button's label ) and `facade` ( bool, default `should_use_facade()` ).
413     * @return string Placeholder markup, or an empty string for an invalid GUID.
414     */
415    public static function render( $guid, array $options = array(), $ratio = null, array $args = array() ) {
416        if ( ! is_string( $guid ) || ! ctype_alnum( $guid ) ) {
417            return '';
418        }
419
420        $facade = isset( $args['facade'] ) ? (bool) $args['facade'] : self::should_use_facade( $options );
421
422        self::enqueue_assets( $facade );
423
424        $ratio = is_numeric( $ratio ) && (float) $ratio > 0 ? (float) $ratio : 56.25;
425        $style = sprintf(
426            'position:relative;width:100%%;aspect-ratio:100 / %s;',
427            rtrim( rtrim( number_format( $ratio, 4, '.', '' ), '0' ), '.' )
428        );
429
430        $inner = '';
431        if ( $facade ) {
432            wp_register_style( self::BOOT_HANDLE, false, array(), Package_Version::PACKAGE_VERSION );
433            wp_enqueue_style( self::BOOT_HANDLE );
434            if ( 0 === self::$rendered ) {
435                wp_add_inline_style( self::BOOT_HANDLE, self::facade_css() );
436            }
437
438            $title = isset( $args['title'] ) && is_string( $args['title'] ) ? trim( $args['title'] ) : '';
439            $label = '' !== $title
440                /* translators: %s is the video title */
441                ? sprintf( __( 'Play video: %s', 'jetpack-videopress-pkg' ), $title )
442                : __( 'Play video', 'jetpack-videopress-pkg' );
443
444            $poster = '';
445            if ( ! empty( $args['poster'] ) && is_string( $args['poster'] ) ) {
446                // The first poster on the page is a likely LCP candidate; later ones can wait for the viewport.
447                $poster = sprintf(
448                    '<img class="%1$s-poster" src="%2$s" alt="" decoding="async"%3$s>',
449                    esc_attr( self::FACADE_CLASS ),
450                    esc_url( $args['poster'] ),
451                    self::$rendered > 0 ? ' loading="lazy"' : ' fetchpriority="high"'
452                );
453            }
454
455            // The glyph is the player's own large play icon.
456            $inner = sprintf(
457                '<button type="button" class="%1$s" aria-label="%2$s">%3$s<span class="%1$s-scrim" aria-hidden="true"></span><span class="%1$s-play" aria-hidden="true"><svg viewBox="0 0 22 22" xmlns="http://www.w3.org/2000/svg"><path d="M6.25725 1.075C6.10279 0.977449 5.91041 0.974889 5.75365 1.06832C5.59689 1.16174 5.5 1.3367 5.5 1.52632V20.4737C5.5 20.6633 5.59689 20.8383 5.75365 20.9317C5.91041 21.0251 6.10279 21.0226 6.25725 20.925L21.2573 11.4513C21.4079 11.3562 21.5 11.1849 21.5 11C21.5 10.8151 21.4079 10.6438 21.2573 10.5487L6.25725 1.075Z"/></svg></span></button>'
458                . '<span class="%1$s-spinner" role="status" aria-live="polite" aria-label="%4$s"><span></span></span>',
459                esc_attr( self::FACADE_CLASS ),
460                esc_attr( $label ),
461                $poster,
462                esc_attr__( 'Loading…', 'jetpack-videopress-pkg' )
463            );
464        }
465
466        ++self::$rendered;
467
468        return sprintf(
469            '<div class="%1$s%5$s" data-videopress-guid="%2$s" data-videopress-options="%3$s"%6$s style="%4$s">%7$s</div>',
470            esc_attr( self::PLACEHOLDER_CLASS ),
471            esc_attr( $guid ),
472            esc_attr( wp_json_encode( (object) $options, JSON_UNESCAPED_SLASHES ) ),
473            esc_attr( $style ),
474            $facade ? ' is-facade' : '',
475            $facade ? ' data-videopress-facade="1"' : '',
476            $inner
477        );
478    }
479
480    /**
481     * Forget per-request state ( tests ).
482     */
483    public static function reset() {
484        self::$rendered       = 0;
485        self::$config_printed = false;
486    }
487
488    /**
489     * Interpret the boolean spellings that reach us from attributes and query strings.
490     *
491     * @param mixed $value Raw value.
492     * @return bool
493     */
494    private static function to_bool( $value ) {
495        if ( is_string( $value ) ) {
496            return ! in_array( strtolower( $value ), array( '', '0', 'false', 'no', 'off' ), true );
497        }
498        return (bool) $value;
499    }
500}