Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
62.65% covered (warning)
62.65%
161 / 257
28.57% covered (danger)
28.57%
4 / 14
CRAP
n/a
0 / 0
jetpack_youtube_embed_to_short_code
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
156
jetpack_youtube_link
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
jetpack_youtube_link_callback
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
jetpack_youtube_sanitize_url
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
30
jetpack_youtube_id
77.86% covered (warning)
77.86%
109 / 140
0.00% covered (danger)
0.00%
0 / 1
94.52
jetpack_shortcode_youtube_args
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
jetpack_youtube_shortcode
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
jetpack_shortcode_youtube_dimensions
92.31% covered (success)
92.31%
24 / 26
0.00% covered (danger)
0.00%
0 / 1
20.18
wpcom_youtube_embed_crazy_url
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
wpcom_youtube_get_regex
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
wpcom_youtube_embed_crazy_url_init
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
wpcom_youtube_filter_pre_oembed_result
28.57% covered (danger)
28.57%
2 / 7
0.00% covered (danger)
0.00%
0 / 1
6.28
wpcom_youtube_oembed_fetch_url
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
jetpack_fix_youtube_shortcode_display_filter
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
1<?php
2/**
3 * Youtube shortcode
4 *
5 * Contains shortcode + some improvements over the Core Embeds syntax (see http://codex.wordpress.org/Embeds )
6 *
7 * Examples:
8 * [youtube https://www.youtube.com/watch?v=WVbQ-oro7FQ]
9 * [youtube=http://www.youtube.com/watch?v=wq0rXGLs0YM&fs=1&hl=bg_BG&autohide=1&rel=0]
10 * http://www.youtube.com/watch?v=H2Ncxw1xfck&w=320&h=240&fmt=1&rel=0&showsearch=1&hd=0
11 * http://www.youtube.com/v/9FhMMmqzbD8?fs=1&hl=en_US
12 * https://www.youtube.com/playlist?list=PLP7HaNDU4Cifov7C2fQM8Ij6Ew_uPHEXW
13 *
14 * @package automattic/jetpack
15 */
16
17if ( ! defined( 'ABSPATH' ) ) {
18    exit( 0 );
19}
20
21/**
22 * Replaces YouTube embeds with YouTube shortcodes.
23 *
24 * Covers the following formats:
25 * 2008-07-15:
26 * <object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/bZBHZT3a-FA&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><embed src="http://www.youtube.com/v/bZBHZT3a-FA&hl=en&fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="425" height="344"></embed></object>
27 * around 2008-06-06 youtube changed their old embed code to this:
28 * <object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/M1D30gS7Z8U&hl=en"></param><embed src="http://www.youtube.com/v/M1D30gS7Z8U&hl=en" type="application/x-shockwave-flash" width="425" height="344"></embed></object>
29 * old style was:
30 * <object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/dGY28Qbj76A&rel=0"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/dGY28Qbj76A&rel=0" type="application/x-shockwave-flash" wmode="transparent" width="425" height="344"></embed></object>
31 * 12-2010:
32 * <object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/3H8bnKdf654?fs=1&amp;hl=en_GB"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/3H8bnKdf654?fs=1&amp;hl=en_GB" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>
33 * 01-2011:
34 * <iframe title="YouTube video player" class="youtube-player" width="640" height="390" src="http://www.youtube.com/embed/Qq9El3ki0_g" frameborder="0" allowFullScreen></iframe>
35 * <iframe class="youtube-player" width="640" height="385" src="http://www.youtube.com/embed/VIDEO_ID" frameborder="0"></iframe>
36 *
37 * @param string $content HTML content.
38 * @return string The content with YouTube embeds replaced with YouTube shortcodes.
39 */
40function jetpack_youtube_embed_to_short_code( $content ) {
41    if ( ! is_string( $content ) || ! str_contains( $content, 'youtube.com' ) ) {
42        return $content;
43    }
44
45    // older codes.
46    $regexp         = '!<object(.*?)>.*?<param\s+name=[\'"]movie[\'"]\s+value=[\'"](https?:)?//www\.youtube\.com/v/([^\'"]+)[\'"].*?>.*?</object>!i';
47    $regexp_ent     = htmlspecialchars( $regexp, ENT_NOQUOTES );
48    $old_regexp     = '!<embed(?:\s+\w+="[^"]*")*\s+src="https?(?:\:|&#0*58;)//www\.youtube\.com/v/([^"]+)"(?:\s+\w+="[^"]*")*\s*(?:/>|>\s*</embed>)!';
49    $old_regexp_ent = str_replace( '&amp;#0*58;', '&amp;#0*58;|&#0*58;', htmlspecialchars( $old_regexp, ENT_NOQUOTES ) );
50
51    // new code.
52    $ifr_regexp     = '!<iframe((?:\s+\w+="[^"]*")*?)\s+src="(https?:)?//(?:www\.)*youtube.com/embed/([^"]+)".*?</iframe>!i';
53    $ifr_regexp_ent = str_replace( '&amp;#0*58;', '&amp;#0*58;|&#0*58;', htmlspecialchars( $ifr_regexp, ENT_NOQUOTES ) );
54
55    foreach ( compact( 'regexp', 'regexp_ent', 'old_regexp', 'old_regexp_ent', 'ifr_regexp', 'ifr_regexp_ent' ) as $reg => $regexp ) {
56        if ( ! preg_match_all( $regexp, $content, $matches, PREG_SET_ORDER ) ) {
57            continue;
58        }
59
60        foreach ( $matches as $match ) {
61            /*
62             * Hack, but '?' should only ever appear once, and
63             * it should be for the 1st field-value pair in query string,
64             * if it is present
65             * YouTube changed their embed code.
66             * Example of how it is now:
67             * <object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/aP9AaD4tgBY?fs=1&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/aP9AaD4tgBY?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>
68             * As shown at the start of function, previous YouTube didn't '?'
69             * the 1st field-value pair.
70             */
71            if ( in_array( $reg, array( 'ifr_regexp', 'ifr_regexp_ent', 'regexp', 'regexp_ent' ), true ) ) {
72                $params = $match[1];
73
74                if ( in_array( $reg, array( 'ifr_regexp_ent', 'regexp_ent' ), true ) ) {
75                    $params = html_entity_decode( $params, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 );
76                }
77
78                $params = wp_kses_hair( $params, array( 'http' ) );
79
80                $width  = isset( $params['width'] ) ? (int) $params['width']['value'] : 0;
81                $height = isset( $params['height'] ) ? (int) $params['height']['value'] : 0;
82                $wh     = '';
83
84                if ( $width && $height ) {
85                    $wh = "&w=$width&h=$height";
86                }
87
88                $url = esc_url_raw( "https://www.youtube.com/watch?v={$match[3]}{$wh}" );
89            } else {
90                $match[1] = str_replace( '?', '&', $match[1] );
91
92                $url = esc_url_raw( 'https://www.youtube.com/watch?v=' . html_entity_decode( $match[1], ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 ) );
93            }
94
95            $content = str_replace( $match[0], "[youtube $url]", $content );
96
97            /**
98             * Fires before the YouTube embed is transformed into a shortcode.
99             *
100             * @module shortcodes
101             *
102             * @since 1.2.0
103             *
104             * @param string youtube Shortcode name.
105             * @param string $url YouTube video URL.
106             */
107            do_action( 'jetpack_embed_to_shortcode', 'youtube', $url );
108        }
109    }
110
111    return $content;
112}
113
114if ( jetpack_shortcodes_should_hook_pre_kses() ) {
115    add_filter( 'pre_kses', 'jetpack_youtube_embed_to_short_code' );
116}
117
118/**
119 * Replaces plain-text links to YouTube videos with YouTube embeds.
120 *
121 * @param string $content HTML content.
122 *
123 * @return string The content with embeds instead of URLs
124 */
125function jetpack_youtube_link( $content ) {
126    return jetpack_preg_replace_callback_outside_tags( '!(?:\n|\A)https?://(?:www\.)?(?:youtube.com/(?:v/|playlist|watch[/\#?])|youtu\.be/)[^\s]+?(?:\n|\Z)!i', 'jetpack_youtube_link_callback', $content, 'youtube.com/' );
127}
128
129/**
130 * Callback function for the regex that replaces YouTube URLs with
131 * YouTube embeds.
132 *
133 * @param array $matches An array containing a YouTube URL.
134 */
135function jetpack_youtube_link_callback( $matches ) {
136    return "\n" . jetpack_youtube_id( $matches[0] ) . "\n";
137}
138
139/**
140 * Normalizes a YouTube URL to include a v= parameter and a query string free of encoded ampersands.
141 *
142 * @param string|array $url Youtube URL.
143 * @return string|false The normalized URL or false if input is invalid.
144 */
145if ( ! function_exists( 'jetpack_youtube_sanitize_url' ) ) :
146    /**
147     * Clean up Youtube URL to match a single format.
148     *
149     * @param string|array $url Youtube URL.
150     */
151    function jetpack_youtube_sanitize_url( $url ) {
152        if ( is_array( $url ) && isset( $url['url'] ) ) {
153            $url = $url['url'];
154        }
155        if ( ! is_string( $url ) ) {
156            return false;
157        }
158
159        $url = trim( $url, ' "' );
160        $url = trim( $url );
161        $url = str_replace( array( 'youtu.be/', '/v/', '/shorts/', '/live/', '#!v=', '&amp;', '&#038;', 'playlist' ), array( 'youtu.be/?v=', '/?v=', '/watch?v=', '/watch?v=', '?v=', '&', '&', 'videoseries' ), $url );
162
163        // Replace any extra question marks with ampersands - the result of a URL like "https://www.youtube.com/v/dQw4w9WgXcQ?fs=1&hl=en_US" being passed in.
164        $query_string_start = strpos( $url, '?' );
165
166        if ( false !== $query_string_start ) {
167            $url = substr( $url, 0, $query_string_start + 1 ) . str_replace( '?', '&', substr( $url, $query_string_start + 1 ) );
168        }
169
170        return $url;
171    }
172endif;
173
174/**
175 * Converts a YouTube URL into an embedded YouTube video.
176 *
177 * URL can be:
178 *    http://www.youtube.com/embed/videoseries?list=PL94269DA08231042B&amp;hl=en_US
179 *    http://www.youtube.com/watch#!v=H2Ncxw1xfck
180 *    http://www.youtube.com/watch?v=H2Ncxw1xfck
181 *    http://www.youtube.com/watch?v=H2Ncxw1xfck&w=320&h=240&fmt=1&rel=0&showsearch=1&hd=0
182 *    http://www.youtube.com/v/jF-kELmmvgA
183 *    http://www.youtube.com/v/9FhMMmqzbD8?fs=1&hl=en_US
184 *    http://youtu.be/Rrohlqeir5E
185 *    https://www.youtube.com/watch?v=GJNxoe-iSb4&list=PLAVZ4NFtZX0fE54mDSqNKym-o_rz-8xmk
186 *    https://www.youtube.com/shorts/VIDEO_ID
187 *    https://www.youtube.com/live/VIDEO_ID
188 *
189 * @param string $url Youtube URL.
190 */
191function jetpack_youtube_id( $url ) {
192    $id = jetpack_get_youtube_id( $url );
193
194    if ( ! $id ) {
195        return sprintf( '<!--%s-->', esc_html__( 'YouTube Error: bad URL entered', 'jetpack' ) );
196    }
197
198    $url = jetpack_youtube_sanitize_url( $url );
199    $url = wp_parse_url( $url );
200
201    $thumbnail = "https://i.ytimg.com/vi/$id/hqdefault.jpg";
202    $video_url = add_query_arg( 'v', $id, 'https://www.youtube.com/watch' );
203
204    $args = jetpack_shortcode_youtube_args( $url );
205    if ( empty( $args ) ) {
206        return sprintf( '<!--%s-->', esc_html__( 'YouTube Error: empty URL args', 'jetpack' ) );
207    }
208
209    // Account for URL having both v and list, where jetpack_get_youtube_id() only accounts for one or the other.
210    if ( isset( $args['list'] ) && $args['list'] === $id ) {
211        $id = null;
212    }
213    if ( isset( $args['v'] ) ) {
214        $id = $args['v'];
215    }
216    if ( ! $id && empty( $args['list'] ) ) {
217        return sprintf( '<!--%s-->', esc_html__( 'YouTube Error: missing id and/or list', 'jetpack' ) );
218    }
219
220    list( $w, $h ) = jetpack_shortcode_youtube_dimensions( $args );
221
222    $params = array(
223        'rel'            => ( isset( $args['rel'] ) && '0' === $args['rel'] ) ? 0 : 1,
224        'showsearch'     => ( isset( $args['showsearch'] ) && '1' === $args['showsearch'] ) ? 1 : 0, // Now deprecated. See https://developers.google.com/youtube/player_parameters#march-29,-2012.
225        'showinfo'       => ( isset( $args['showinfo'] ) && '0' === $args['showinfo'] ) ? 0 : 1, // Now obsolete. See https://developers.google.com/youtube/player_parameters#showinfo.
226        'iv_load_policy' => ( isset( $args['iv_load_policy'] ) && '3' === $args['iv_load_policy'] ) ? 3 : 1,
227        'fs'             => 1,
228        'hl'             => str_replace( '_', '-', get_locale() ),
229    );
230    if ( isset( $args['fmt'] ) && (int) $args['fmt'] ) {
231        $params['fmt'] = (int) $args['fmt']; // Apparently an obsolete parameter. Not referenced on https://developers.google.com/youtube/player_parameters.
232    }
233
234    // The autohide parameter has been deprecated since 2015. See https://developers.google.com/youtube/player_parameters#august-19,-2015.
235    if ( ! isset( $args['autohide'] ) || ( $args['autohide'] < 0 || 2 < $args['autohide'] ) ) {
236        $params['autohide'] = 2;
237    } else {
238        $params['autohide'] = (int) $args['autohide'];
239    }
240
241    $start = 0;
242    if ( isset( $args['start'] ) ) {
243        $start = (int) $args['start'];
244    } elseif ( isset( $args['t'] ) ) {
245        if ( is_numeric( $args['t'] ) ) {
246            $start = (int) $args['t'];
247        } elseif ( is_string( $args['t'] ) ) {
248            $time_pieces = preg_split( '/(?<=\D)(?=\d+)/', $args['t'] );
249
250            foreach ( $time_pieces as $time_piece ) {
251                $int = (int) $time_piece;
252                switch ( substr( $time_piece, - 1 ) ) {
253                    case 'h':
254                        $start += $int * 3600;
255                        break;
256                    case 'm':
257                        $start += $int * 60;
258                        break;
259                    case 's':
260                        $start += $int;
261                        break;
262                }
263            }
264        }
265    }
266    if ( $start ) {
267        $params['start'] = (int) $start;
268    }
269
270    if ( isset( $args['end'] ) && (int) $args['end'] ) {
271        $params['end'] = (int) $args['end'];
272    }
273    if ( isset( $args['hd'] ) && (int) $args['hd'] ) {
274        $params['hd'] = (int) $args['hd']; // Now obsolete per https://developers.google.com/youtube/player_parameters#march-29,-2012.
275    }
276    if ( isset( $args['vq'] ) && in_array( $args['vq'], array( 'hd720', 'hd1080' ), true ) ) {
277        $params['vq'] = $args['vq']; // Note, this appears to be obsolete. Not referenced on https://developers.google.com/youtube/player_parameters.
278    }
279    if ( isset( $args['cc_load_policy'] ) ) {
280        $params['cc_load_policy'] = 1;
281    }
282    if ( isset( $args['cc_lang_pref'] ) ) {
283        $params['cc_lang_pref'] = preg_replace( '/[^_a-z0-9-]/i', '', $args['cc_lang_pref'] );
284    }
285
286    // The wmode parameter appears to be obsolete. Not referenced on https://developers.google.com/youtube/player_parameters.
287    if ( isset( $args['wmode'] ) && in_array( strtolower( $args['wmode'] ), array( 'opaque', 'window', 'transparent' ), true ) ) {
288        $params['wmode'] = $args['wmode'];
289    } else {
290        $params['wmode'] = 'transparent';
291    }
292
293    // The theme parameter is obsolete per https://developers.google.com/youtube/player_parameters#august-19,-2015.
294    if ( isset( $args['theme'] ) && in_array( strtolower( $args['theme'] ), array( 'dark', 'light' ), true ) ) {
295        $params['theme'] = $args['theme'];
296    }
297
298    if ( isset( $args['list'] ) ) {
299        $params['listType'] = 'playlist';
300        $params['list']     = preg_replace( '|[^_a-z0-9-]|i', '', $args['list'] );
301    }
302
303    /**
304     * Allow YouTube videos to start playing automatically.
305     *
306     * @module shortcodes
307     *
308     * @since 2.2.2
309     *
310     * @param bool false Enable autoplay for YouTube videos.
311     */
312    if ( apply_filters( 'jetpack_youtube_allow_autoplay', false ) && isset( $args['autoplay'] ) ) {
313        $params['autoplay'] = (int) $args['autoplay'];
314    }
315
316    $is_amp = class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request();
317
318    if ( $is_amp && $id ) {
319        // Note that <amp-youtube> currently is not well suited for playlists that don't have an individual video selected, hence the $id check above.
320        $placeholder = sprintf(
321            '<a href="%1$s" placeholder><amp-img src="%2$s" alt="%3$s" layout="fill" object-fit="cover"><noscript><img src="%2$s" loading="lazy" decoding="async" alt="%3$s"></noscript></amp-img></a>',
322            esc_url( $video_url ),
323            esc_url( $thumbnail ),
324            esc_attr__( 'YouTube Poster', 'jetpack' ) // Would be preferable to provide YouTube video title, but not available in this non-oEmbed context.
325        );
326
327        $html_attributes = array();
328        foreach ( $params as $param_name => $param_value ) {
329            $html_attributes[] = sprintf(
330                'data-param-%s="%s"',
331                sanitize_key( $param_name ),
332                esc_attr( $param_value )
333            );
334        }
335
336        $html = sprintf(
337            '<amp-youtube data-videoid="%s" %s width="%d" height="%d" layout="responsive">%s</amp-youtube>',
338            esc_attr( $id ),
339            implode( ' ', $html_attributes ), // Note: Escaping done above.
340            esc_attr( $w ),
341            esc_attr( $h ),
342            $placeholder
343        );
344    } else {
345        // In AMP, the AMP_Iframe_Sanitizer will convert into <amp-iframe> as required.
346        $src = 'https://www.youtube.com/embed';
347        if ( $id ) {
348            $src .= "/$id";
349        }
350        $src = add_query_arg(
351            array_merge(
352                array( 'version' => 3 ),
353                $params
354            ),
355            $src
356        );
357
358        $layout = $is_amp ? 'layout="responsive" ' : '';
359
360        $html = sprintf(
361            '<iframe class="youtube-player" width="%s" height="%s" %ssrc="%s" allowfullscreen="true" style="border:0;" sandbox="allow-scripts allow-same-origin allow-popups allow-presentation allow-popups-to-escape-sandbox"></iframe>',
362            esc_attr( $w ),
363            esc_attr( $h ),
364            $layout,
365            esc_url( $src )
366        );
367    }
368
369    // Let's do some alignment wonder in a span, unless we're producing a feed.
370    if ( ! is_feed() ) {
371        $alignmentcss = 'text-align:center;';
372        if ( isset( $args['align'] ) ) {
373            switch ( $args['align'] ) {
374                case 'left':
375                    $alignmentcss = "float:left; width:{$w}px; height:{$h}px; margin-right:10px; margin-bottom: 10px;";
376                    break;
377                case 'right':
378                    $alignmentcss = "float:right; width:{$w}px; height:{$h}px; margin-left:10px; margin-bottom: 10px;";
379                    break;
380            }
381        }
382
383        $html = sprintf(
384            '<span class="embed-youtube" style="%s display: block;">%s</span>',
385            esc_attr( $alignmentcss ),
386            $html
387        );
388
389    }
390
391    /**
392     * Format output for Calypso Reader/Notifications/Comments
393     */
394    if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
395        require_once WP_CONTENT_DIR . '/lib/display-context.php';
396        $context = A8C\Display_Context\get_current_context();
397        if ( A8C\Display_Context\NOTIFICATIONS === $context ) {
398            return sprintf(
399                '<a href="%1$s" target="_blank" rel="noopener noreferrer"><img src="%2$s" alt="%3$s" /></a>',
400                esc_url( $video_url ),
401                esc_url( $thumbnail ),
402                esc_html__( 'YouTube video', 'jetpack' )
403            );
404        }
405    }
406
407    /**
408     * Filter the YouTube video HTML output.
409     *
410     * @module shortcodes
411     *
412     * @since 1.2.3
413     *
414     * @param string $html YouTube video HTML output.
415     */
416    $html = apply_filters( 'video_embed_html', $html );
417
418    return $html;
419}
420
421/**
422 * Gets the args present in the YouTube shortcode URL.
423 *
424 * @since 8.0.0
425 *
426 * @param array $url The parsed URL of the shortcode.
427 *
428 * @return array|false The query args of the URL, or false.
429 */
430function jetpack_shortcode_youtube_args( $url ) {
431    $qargs = array();
432    if ( ! empty( $url['query'] ) ) {
433        wp_parse_str( $url['query'], $qargs );
434    } else {
435        return false;
436    }
437
438    $fargs = array();
439    if ( ! empty( $url['fragment'] ) ) {
440        wp_parse_str( $url['fragment'], $fargs );
441    }
442
443    return array_merge( $fargs, $qargs );
444}
445
446/**
447 * Display the Youtube shortcode.
448 *
449 * @param array $atts Shortcode attributes.
450 *
451 * @return string The rendered shortcode.
452 */
453function jetpack_youtube_shortcode( $atts ) {
454    $url = ( isset( $atts[0] ) ) ? ltrim( $atts[0], '=' ) : shortcode_new_to_old_params( $atts );
455    return jetpack_youtube_id( $url );
456}
457add_shortcode( 'youtube', 'jetpack_youtube_shortcode' );
458
459/**
460 * Gets the dimensions of the [youtube] shortcode.
461 *
462 * Calculates the width and height, taking $content_width into consideration.
463 *
464 * @since 8.0.0
465 *
466 * @param array $query_args The query args of the URL.
467 *
468 * @return array The width and height of the shortcode.
469 */
470function jetpack_shortcode_youtube_dimensions( $query_args ) {
471    $h = null;
472    global $content_width;
473
474    $input_w = ( isset( $query_args['w'] ) && (int) $query_args['w'] ) ? (int) $query_args['w'] : 0;
475    $input_h = ( isset( $query_args['h'] ) && (int) $query_args['h'] ) ? (int) $query_args['h'] : 0;
476
477    // If we have $content_width, use it.
478    if ( ! empty( $content_width ) ) {
479        $default_width = (int) $content_width;
480    } else {
481        // Otherwise get default width from the old, now deprecated embed_size_w option.
482        $default_width = (int) get_option( 'embed_size_w' );
483    }
484
485    // If we don't know those 2 values use a hardcoded width.
486    if ( empty( $default_width ) ) {
487        $default_width = 640;
488    }
489
490    if ( $input_w > 0 && $input_h > 0 ) {
491        $w = $input_w;
492        $h = $input_h;
493    } elseif ( 0 === $input_w && 0 === $input_h ) {
494        if ( isset( $query_args['fmt'] ) && (int) $query_args['fmt'] ) {
495            $w = ( ! empty( $content_width ) ? min( $content_width, 480 ) : 480 );
496        } else {
497            $w = ( ! empty( $content_width ) ? min( $content_width, $default_width ) : $default_width );
498            $h = ceil( ( $w / 16 ) * 9 );
499        }
500    } elseif ( $input_w > 0 ) {
501        $w = $input_w;
502        $h = ceil( ( $w / 16 ) * 9 );
503    } elseif ( isset( $query_args['fmt'] ) && (int) $query_args['fmt'] ) {
504        $w = ( ! empty( $content_width ) ? min( $content_width, 480 ) : 480 );
505    } else {
506        $w = ( ! empty( $content_width ) ? min( $content_width, $default_width ) : $default_width );
507        $h = $input_h;
508    }
509
510    /**
511     * Filter the YouTube player width.
512     *
513     * @module shortcodes
514     *
515     * @since 1.1.0
516     *
517     * @param int $w Width of the YouTube player in pixels.
518     */
519    $w = (int) apply_filters( 'youtube_width', $w );
520
521    /**
522     * Filter the YouTube player height.
523     *
524     * @module shortcodes
525     *
526     * @since 1.1.0
527     *
528     * @param int $h Height of the YouTube player in pixels.
529     */
530    $h = (int) apply_filters( 'youtube_height', $h );
531
532    return array( $w, $h );
533}
534
535/**
536 * For bare URLs on their own line of the form
537 * http://www.youtube.com/v/9FhMMmqzbD8?fs=1&hl=en_US
538 *
539 * @param array  $matches Regex partial matches against the URL passed.
540 * @param array  $attr    Attributes received in embed response.
541 * @param string $url     Requested URL to be embedded.
542 */
543function wpcom_youtube_embed_crazy_url( $matches, $attr, $url ) {
544    return jetpack_youtube_id( $url );
545}
546
547/**
548 * Get the regex for Youtube URLs.
549 */
550function wpcom_youtube_get_regex() {
551    return '#https?://(?:www\.)?(?:youtube.com/(?:v/|live/|playlist|watch[/\#?])|youtu\.be/).*#i';
552}
553
554/**
555 * Add a new handler to automatically transform custom Youtube URLs (like playlists) into embeds.
556 */
557function wpcom_youtube_embed_crazy_url_init() {
558    // Register the custom handler to provide the better support for the private video.
559    wp_embed_register_handler( 'wpcom_youtube_embed_crazy_url', wpcom_youtube_get_regex(), 'wpcom_youtube_embed_crazy_url' );
560}
561add_action( 'init', 'wpcom_youtube_embed_crazy_url_init' );
562
563/**
564 * Filters the oEmbed result before any HTTP requests are made for YouTube.
565 *
566 * @since 13.9
567 *
568 * @param null|string $result The UNSANITIZED (and potentially unsafe) HTML that should be used to embed. Default null.
569 * @param string      $url    The URL that should be inspected for discovery `<link>` tags.
570 * @param array       $args   oEmbed remote get arguments.
571 * @return null|string The UNSANITIZED (and potentially unsafe) HTML that should be used to embed.
572 *                     Null if the URL does not belong to the current site.
573 */
574function wpcom_youtube_filter_pre_oembed_result( $result, $url, $args ) {
575    // Return early if it's not a YouTube URL.
576    if ( ! preg_match( wpcom_youtube_get_regex(), $url, $matches ) ) {
577        return $result;
578    }
579
580    // Try to get the oembed data by the Core's approach.
581    $wp_oembed = _wp_oembed_get_object();
582    $data      = $wp_oembed->get_data( $url, $args );
583    if ( $data ) {
584        /** This filter is documented in wp-includes/class-wp-oembed.php */
585        return apply_filters( 'oembed_result', $wp_oembed->data2html( $data, $url ), $url, $args );
586    }
587
588    // Fallback to the custom handler if the oembed result is not found, especially for the private video.
589    return jetpack_youtube_id( $url );
590}
591add_filter( 'pre_oembed_result', 'wpcom_youtube_filter_pre_oembed_result', 10, 3 );
592
593/**
594 * Remove the ending question mark from the video id of the YouTube URL.
595 *
596 * Example: https://www.youtube.com/watch?v=AVAWwXeOyyQ?
597 *
598 * @since 13.9
599 *
600 * @param string $provider URL of the oEmbed provider.
601 * @param string $url      URL of the content to be embedded.
602 *
603 * @return string
604 */
605function wpcom_youtube_oembed_fetch_url( $provider, $url ) {
606    if ( ! wp_startswith( $provider, 'https://www.youtube.com/oembed' ) ) {
607        return $provider;
608    }
609
610    $parsed = wp_parse_url( $url );
611    if ( ! isset( $parsed['query'] ) ) {
612        return $provider;
613    }
614
615    $query_vars = array();
616    wp_parse_str( $parsed['query'], $query_vars );
617    if ( isset( $query_vars['v'] ) && wp_endswith( $query_vars['v'], '?' ) ) {
618        $url = remove_query_arg( array( 'v' ), $url );
619        $url = add_query_arg( 'v', preg_replace( '/\?$/', '', $query_vars['v'] ), $url );
620    }
621
622    $provider = remove_query_arg( array( 'url' ), $provider );
623    $provider = add_query_arg( 'url', rawurlencode( $url ), $provider );
624
625    return $provider;
626}
627add_filter( 'oembed_fetch_url', 'wpcom_youtube_oembed_fetch_url', 10, 2 );
628
629if (
630    ! is_admin()
631    &&
632    /**
633     * Allow oEmbeds in Jetpack's Comment form.
634     *
635     * @module shortcodes
636     *
637     * @since 2.8.0
638     *
639     * @param int $allow_oembed Option to automatically embed all plain text URLs.
640     */
641    apply_filters( 'jetpack_comments_allow_oembed', true )
642    // No need for this on WordPress.com, this is done for multiple shortcodes at a time there.
643    && ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM )
644) {
645    /*
646     * We attach wp_kses_post to comment_text in default-filters.php with priority of 10 anyway,
647     * so the iframe gets filtered out.
648     * Higher priority because we need it before auto-link and autop get to it.
649     */
650    add_filter( 'comment_text', 'jetpack_youtube_link', 1 );
651}
652
653/**
654 * Core changes to do_shortcode (https://core.trac.wordpress.org/changeset/34747) broke "improper" shortcodes
655 * with the format [shortcode=http://url.com].
656 *
657 * This removes the "=" from the shortcode so it can be parsed.
658 *
659 * @see https://github.com/Automattic/jetpack/issues/3121
660 *
661 * @param string $content HTML content.
662 */
663function jetpack_fix_youtube_shortcode_display_filter( $content ) {
664    if ( strpos( $content, '[youtube=' ) !== false ) {
665        $content = preg_replace( '@\[youtube=(.*?)\]@', '[youtube $1]', $content );
666    }
667
668    return $content;
669}
670add_filter( 'the_content', 'jetpack_fix_youtube_shortcode_display_filter', 7 );