Completed
Push — renovate/react-monorepo ( 545e89...65a81e )
by
unknown
268:48 queued 253:47
created

youtube.php ➔ youtube_id()   F

Complexity

Conditions 53
Paths > 20000

Size

Total Lines 200

Duplication

Lines 12
Ratio 6 %

Importance

Changes 0
Metric Value
cc 53
nc 754974726
nop 1
dl 12
loc 200
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
17
/**
18
 * Replaces YouTube embeds with YouTube shortcodes.
19
 *
20
 * Covers the following formats:
21
 * 2008-07-15:
22
 * <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>
23
 * around 2008-06-06 youtube changed their old embed code to this:
24
 * <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>
25
 * old style was:
26
 * <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>
27
 * 12-2010:
28
 * <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>
29
 * 01-2011:
30
 * <iframe title="YouTube video player" class="youtube-player" width="640" height="390" src="http://www.youtube.com/embed/Qq9El3ki0_g" frameborder="0" allowFullScreen></iframe>
31
 * <iframe class="youtube-player" width="640" height="385" src="http://www.youtube.com/embed/VIDEO_ID" frameborder="0"></iframe>
32
 *
33
 * @param string $content HTML content.
34
 * @return string The content with YouTube embeds replaced with YouTube shortcodes.
35
 */
36
function youtube_embed_to_short_code( $content ) {
37
	if ( ! is_string( $content ) || false === strpos( $content, 'youtube.com' ) ) {
38
		return $content;
39
	}
40
41
	// older codes.
42
	$regexp         = '!<object(.*?)>.*?<param\s+name=[\'"]movie[\'"]\s+value=[\'"](https?:)?//www\.youtube\.com/v/([^\'"]+)[\'"].*?>.*?</object>!i';
43
	$regexp_ent     = htmlspecialchars( $regexp, ENT_NOQUOTES );
44
	$old_regexp     = '!<embed(?:\s+\w+="[^"]*")*\s+src="https?(?:\:|&#0*58;)//www\.youtube\.com/v/([^"]+)"(?:\s+\w+="[^"]*")*\s*(?:/>|>\s*</embed>)!';
45
	$old_regexp_ent = str_replace( '&amp;#0*58;', '&amp;#0*58;|&#0*58;', htmlspecialchars( $old_regexp, ENT_NOQUOTES ) );
46
47
	// new code.
48
	$ifr_regexp     = '!<iframe((?:\s+\w+="[^"]*")*?)\s+src="(https?:)?//(?:www\.)*youtube.com/embed/([^"]+)".*?</iframe>!i';
49
	$ifr_regexp_ent = str_replace( '&amp;#0*58;', '&amp;#0*58;|&#0*58;', htmlspecialchars( $ifr_regexp, ENT_NOQUOTES ) );
50
51
	foreach ( compact( 'regexp', 'regexp_ent', 'old_regexp', 'old_regexp_ent', 'ifr_regexp', 'ifr_regexp_ent' ) as $reg => $regexp ) {
52
		if ( ! preg_match_all( $regexp, $content, $matches, PREG_SET_ORDER ) ) {
53
			continue;
54
		}
55
56
		foreach ( $matches as $match ) {
57
			/*
58
			 * Hack, but '?' should only ever appear once, and
59
			 * it should be for the 1st field-value pair in query string,
60
			 * if it is present
61
			 * YouTube changed their embed code.
62
			 * Example of how it is now:
63
			 * <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>
64
			 * As shown at the start of function, previous YouTube didn't '?'
65
			 * the 1st field-value pair.
66
			 */
67
			if ( in_array( $reg, array( 'ifr_regexp', 'ifr_regexp_ent', 'regexp', 'regexp_ent' ), true ) ) {
68
				$params = $match[1];
69
70 View Code Duplication
				if ( in_array( $reg, array( 'ifr_regexp_ent', 'regexp_ent' ), true ) ) {
71
					$params = html_entity_decode( $params );
72
				}
73
74
				$params = wp_kses_hair( $params, array( 'http' ) );
75
76
				$width  = isset( $params['width'] ) ? (int) $params['width']['value'] : 0;
77
				$height = isset( $params['height'] ) ? (int) $params['height']['value'] : 0;
78
				$wh     = '';
79
80
				if ( $width && $height ) {
81
					$wh = "&w=$width&h=$height";
82
				}
83
84
				$url = esc_url_raw( "https://www.youtube.com/watch?v={$match[3]}{$wh}" );
85
			} else {
86
				$match[1] = str_replace( '?', '&', $match[1] );
87
88
				$url = esc_url_raw( 'https://www.youtube.com/watch?v=' . html_entity_decode( $match[1] ) );
89
			}
90
91
			$content = str_replace( $match[0], "[youtube $url]", $content );
92
93
			/**
94
			 * Fires before the YouTube embed is transformed into a shortcode.
95
			 *
96
			 * @module shortcodes
97
			 *
98
			 * @since 1.2.0
99
			 *
100
			 * @param string youtube Shortcode name.
101
			 * @param string $url YouTube video URL.
102
			 */
103
			do_action( 'jetpack_embed_to_shortcode', 'youtube', $url );
104
		}
105
	}
106
107
	return $content;
108
}
109
add_filter( 'pre_kses', 'youtube_embed_to_short_code' );
110
111
/**
112
 * Replaces plain-text links to YouTube videos with YouTube embeds.
113
 *
114
 * @param string $content HTML content.
115
 *
116
 * @return string The content with embeds instead of URLs
117
 */
118
function youtube_link( $content ) {
119
	return jetpack_preg_replace_callback_outside_tags( '!(?:\n|\A)https?://(?:www\.)?(?:youtube.com/(?:v/|playlist|watch[/\#?])|youtu\.be/)[^\s]+?(?:\n|\Z)!i', 'youtube_link_callback', $content, 'youtube.com/' );
120
}
121
122
/**
123
 * Callback function for the regex that replaces YouTube URLs with
124
 * YouTube embeds.
125
 *
126
 * @param array $matches An array containing a YouTube URL.
127
 */
128
function youtube_link_callback( $matches ) {
129
	return "\n" . youtube_id( $matches[0] ) . "\n";
130
}
131
132
/**
133
 * Normalizes a YouTube URL to include a v= parameter and a query string free of encoded ampersands.
134
 *
135
 * @param string $url
136
 * @return string The normalized URL
137
 */
138 View Code Duplication
if ( ! function_exists( 'youtube_sanitize_url' ) ) :
139
	/**
140
	 * Clean up Youtube URL to match a single format.
141
	 *
142
	 * @param string $url Youtube URL.
143
	 */
144
	function youtube_sanitize_url( $url ) {
0 ignored issues
show
Best Practice introduced by
The function youtube_sanitize_url() has been defined more than once; this definition is ignored, only the first definition in projects/plugins/jetpack/functions.compat.php (L54-67) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
145
		$url = trim( $url, ' "' );
146
		$url = trim( $url );
147
		$url = str_replace( array( 'youtu.be/', '/v/', '#!v=', '&amp;', '&#038;', 'playlist' ), array( 'youtu.be/?v=', '/?v=', '?v=', '&', '&', 'videoseries' ), $url );
148
149
		// Replace any extra question marks with ampersands - the result of a URL like "http://www.youtube.com/v/9FhMMmqzbD8?fs=1&hl=en_US" being passed in.
150
		$query_string_start = strpos( $url, '?' );
151
152
		if ( false !== $query_string_start ) {
153
			$url = substr( $url, 0, $query_string_start + 1 ) . str_replace( '?', '&', substr( $url, $query_string_start + 1 ) );
154
		}
155
156
		return $url;
157
	}
158
endif;
159
160
/**
161
 * Converts a YouTube URL into an embedded YouTube video.
162
 *
163
 * URL can be:
164
 *    http://www.youtube.com/embed/videoseries?list=PL94269DA08231042B&amp;hl=en_US
165
 *    http://www.youtube.com/watch#!v=H2Ncxw1xfck
166
 *    http://www.youtube.com/watch?v=H2Ncxw1xfck
167
 *    http://www.youtube.com/watch?v=H2Ncxw1xfck&w=320&h=240&fmt=1&rel=0&showsearch=1&hd=0
168
 *    http://www.youtube.com/v/jF-kELmmvgA
169
 *    http://www.youtube.com/v/9FhMMmqzbD8?fs=1&hl=en_US
170
 *    http://youtu.be/Rrohlqeir5E
171
 *    https://www.youtube.com/watch?v=GJNxoe-iSb4&list=PLAVZ4NFtZX0fE54mDSqNKym-o_rz-8xmk
172
 *
173
 * @param string $url Youtube URL.
174
 */
175
function youtube_id( $url ) {
176
	$id = jetpack_get_youtube_id( $url );
177
178
	if ( ! $id ) {
179
		return sprintf( '<!--%s-->', esc_html__( 'YouTube Error: bad URL entered', 'jetpack' ) );
180
	}
181
182
	$url = youtube_sanitize_url( $url );
183
	$url = wp_parse_url( $url );
184
185
	$args = jetpack_shortcode_youtube_args( $url );
0 ignored issues
show
Documentation introduced by
$url is of type string|false, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
186
	if ( empty( $args ) ) {
187
		return sprintf( '<!--%s-->', esc_html__( 'YouTube Error: empty URL args', 'jetpack' ) );
188
	}
189
190
	// Account for URL having both v and list, where jetpack_get_youtube_id() only accounts for one or the other.
191
	if ( isset( $args['list'] ) && $args['list'] === $id ) {
192
		$id = null;
193
	}
194
	if ( isset( $args['v'] ) ) {
195
		$id = $args['v'];
196
	}
197
	if ( ! $id && empty( $args['list'] ) ) {
198
		return sprintf( '<!--%s-->', esc_html__( 'YouTube Error: missing id and/or list', 'jetpack' ) );
199
	}
200
201
	list( $w, $h ) = jetpack_shortcode_youtube_dimensions( $args );
202
203
	$params = array(
204
		'rel'            => ( isset( $args['rel'] ) && '0' === $args['rel'] ) ? 0 : 1,
205
		'showsearch'     => ( isset( $args['showsearch'] ) && '1' === $args['showsearch'] ) ? 1 : 0, // Now deprecated. See https://developers.google.com/youtube/player_parameters#march-29,-2012.
206
		'showinfo'       => ( isset( $args['showinfo'] ) && '0' === $args['showinfo'] ) ? 0 : 1, // Now obsolete. See https://developers.google.com/youtube/player_parameters#showinfo.
207
		'iv_load_policy' => ( isset( $args['iv_load_policy'] ) && '3' === $args['iv_load_policy'] ) ? 3 : 1,
208
		'fs'             => 1,
209
		'hl'             => str_replace( '_', '-', get_locale() ),
210
	);
211 View Code Duplication
	if ( isset( $args['fmt'] ) && (int) $args['fmt'] ) {
212
		$params['fmt'] = (int) $args['fmt']; // Apparently an obsolete parameter. Not referenced on https://developers.google.com/youtube/player_parameters.
213
	}
214
215
	// The autohide parameter has been deprecated since 2015. See https://developers.google.com/youtube/player_parameters#august-19,-2015.
216
	if ( ! isset( $args['autohide'] ) || ( $args['autohide'] < 0 || 2 < $args['autohide'] ) ) {
217
		$params['autohide'] = 2;
218
	} else {
219
		$params['autohide'] = (int) $args['autohide'];
220
	}
221
222
	$start = 0;
223
	if ( isset( $args['start'] ) ) {
224
		$start = (int) $args['start'];
225
	} elseif ( isset( $args['t'] ) ) {
226
		$time_pieces = preg_split( '/(?<=\D)(?=\d+)/', $args['t'] );
227
228
		foreach ( $time_pieces as $time_piece ) {
229
			$int = (int) $time_piece;
230
			switch ( substr( $time_piece, -1 ) ) {
231
				case 'h':
232
					$start += $int * 3600;
233
					break;
234
				case 'm':
235
					$start += $int * 60;
236
					break;
237
				case 's':
238
					$start += $int;
239
					break;
240
			}
241
		}
242
	}
243
	if ( $start ) {
244
		$params['start'] = (int) $start;
245
	}
246
247 View Code Duplication
	if ( isset( $args['end'] ) && (int) $args['end'] ) {
248
		$params['end'] = (int) $args['end'];
249
	}
250 View Code Duplication
	if ( isset( $args['hd'] ) && (int) $args['hd'] ) {
251
		$params['hd'] = (int) $args['hd']; // Now obsolete per https://developers.google.com/youtube/player_parameters#march-29,-2012.
252
	}
253
	if ( isset( $args['vq'] ) && in_array( $args['vq'], array( 'hd720', 'hd1080' ), true ) ) {
254
		$params['vq'] = $args['vq']; // Note, this appears to be obsolete. Not referenced on https://developers.google.com/youtube/player_parameters.
255
	}
256
	if ( isset( $args['cc_load_policy'] ) ) {
257
		$params['cc_load_policy'] = 1;
258
	}
259
	if ( isset( $args['cc_lang_pref'] ) ) {
260
		$params['cc_lang_pref'] = preg_replace( '/[^_a-z0-9-]/i', '', $args['cc_lang_pref'] );
261
	}
262
263
	// The wmode parameter appears to be obsolete. Not referenced on https://developers.google.com/youtube/player_parameters.
264
	if ( isset( $args['wmode'] ) && in_array( strtolower( $args['wmode'] ), array( 'opaque', 'window', 'transparent' ), true ) ) {
265
		$params['wmode'] = $args['wmode'];
266
	} else {
267
		$params['wmode'] = 'transparent';
268
	}
269
270
	// The theme parameter is obsolete per https://developers.google.com/youtube/player_parameters#august-19,-2015.
271 View Code Duplication
	if ( isset( $args['theme'] ) && in_array( strtolower( $args['theme'] ), array( 'dark', 'light' ), true ) ) {
272
		$params['theme'] = $args['theme'];
273
	}
274
275
	if ( isset( $args['list'] ) ) {
276
		$params['listType'] = 'playlist';
277
		$params['list']     = preg_replace( '|[^_a-z0-9-]|i', '', $args['list'] );
278
	}
279
280
	/**
281
	 * Allow YouTube videos to start playing automatically.
282
	 *
283
	 * @module shortcodes
284
	 *
285
	 * @since 2.2.2
286
	 *
287
	 * @param bool false Enable autoplay for YouTube videos.
288
	 */
289
	if ( apply_filters( 'jetpack_youtube_allow_autoplay', false ) && isset( $args['autoplay'] ) ) {
290
		$params['autoplay'] = (int) $args['autoplay'];
291
	}
292
293
	$is_amp = class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request();
294
295
	if ( $is_amp && $id ) {
296
		// Note that <amp-youtube> currently is not well suited for playlists that don't have an individual video selected, hence the $id check above.
297
		$placeholder = sprintf(
298
			'<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>',
299
			esc_url( add_query_arg( 'v', $id, 'https://www.youtube.com/watch' ) ),
300
			esc_url( "https://i.ytimg.com/vi/$id/hqdefault.jpg" ),
301
			esc_attr__( 'YouTube Poster', 'jetpack' ) // Would be preferable to provide YouTube video title, but not available in this non-oEmbed context.
302
		);
303
304
		$html_attributes = array();
305
		foreach ( $params as $param_name => $param_value ) {
306
			$html_attributes[] = sprintf(
307
				'data-param-%s="%s"',
308
				sanitize_key( $param_name ),
309
				esc_attr( $param_value )
310
			);
311
		}
312
313
		$html = sprintf(
314
			'<amp-youtube data-videoid="%s" %s width="%d" height="%d" layout="responsive">%s</amp-youtube>',
315
			esc_attr( $id ),
316
			implode( ' ', $html_attributes ), // Note: Escaping done above.
317
			esc_attr( $w ),
318
			esc_attr( $h ),
319
			$placeholder
320
		);
321
	} else {
322
		// In AMP, the AMP_Iframe_Sanitizer will convert into <amp-iframe> as required.
323
		$src = 'https://www.youtube.com/embed';
324
		if ( $id ) {
325
			$src .= "/$id";
326
		}
327
		$src = add_query_arg(
328
			array_merge(
329
				array( 'version' => 3 ),
330
				$params
331
			),
332
			$src
333
		);
334
335
		$layout = $is_amp ? 'layout="responsive" ' : '';
336
337
		$html = "<iframe class='youtube-player' width='$w' height='$h' {$layout}src='" . esc_url( $src ) . "' allowfullscreen='true' style='border:0;' sandbox='allow-scripts allow-same-origin allow-popups allow-presentation'></iframe>";
338
	}
339
340
	// Let's do some alignment wonder in a span, unless we're producing a feed.
341
	if ( ! is_feed() ) {
342
		$alignmentcss = 'text-align:center;';
343
		if ( isset( $args['align'] ) ) {
344
			switch ( $args['align'] ) {
345
				case 'left':
346
					$alignmentcss = "float:left; width:{$w}px; height:{$h}px; margin-right:10px; margin-bottom: 10px;";
347
					break;
348
				case 'right':
349
					$alignmentcss = "float:right; width:{$w}px; height:{$h}px; margin-left:10px; margin-bottom: 10px;";
350
					break;
351
			}
352
		}
353
354
		$html = sprintf(
355
			'<span class="embed-youtube" style="%s display: block;">%s</span>',
356
			esc_attr( $alignmentcss ),
357
			$html
358
		);
359
360
	}
361
362
	/**
363
	 * Filter the YouTube video HTML output.
364
	 *
365
	 * @module shortcodes
366
	 *
367
	 * @since 1.2.3
368
	 *
369
	 * @param string $html YouTube video HTML output.
370
	 */
371
	$html = apply_filters( 'video_embed_html', $html );
372
373
	return $html;
374
}
375
376
/**
377
 * Gets the args present in the YouTube shortcode URL.
378
 *
379
 * @since 8.0.0
380
 *
381
 * @param array $url The parsed URL of the shortcode.
382
 *
383
 * @return array|false The query args of the URL, or false.
384
 */
385
function jetpack_shortcode_youtube_args( $url ) {
386
	$qargs = array();
387
	if ( ! empty( $url['query'] ) ) {
388
		wp_parse_str( $url['query'], $qargs );
389
	} else {
390
		return false;
391
	}
392
393
	$fargs = array();
394
	if ( ! empty( $url['fragment'] ) ) {
395
		wp_parse_str( $url['fragment'], $fargs );
396
	}
397
398
	return array_merge( $fargs, $qargs );
399
}
400
401
/**
402
 * Display the Youtube shortcode.
403
 *
404
 * @param array $atts Shortcode attributes.
405
 *
406
 * @return string The rendered shortcode.
407
 */
408
function youtube_shortcode( $atts ) {
409
	$url = ( isset( $atts[0] ) ) ? ltrim( $atts[0], '=' ) : shortcode_new_to_old_params( $atts );
410
	return youtube_id( $url );
411
}
412
add_shortcode( 'youtube', 'youtube_shortcode' );
413
414
/**
415
 * Renders the [youtube] shortcode as an AMP component.
416
 *
417
 * @since 8.0.0
418
 * @deprecated Use youtube_id() instead.
419
 *
420
 * @param string $url The YouTube URL.
421
 *
422
 * @return string The AMP-compatible rendered shortcode.
423
 */
424
function jetpack_amp_youtube_shortcode( $url ) {
425
	_deprecated_function( __FUNCTION__, 'jetpack-9.1.0', 'youtube_id' );
426
	$video_id = jetpack_get_youtube_id( $url );
427
	if ( empty( $video_id ) ) {
428
		return sprintf(
429
			'<a href="%1$s" class="amp-wp-embed-fallback">%1$s</a>',
430
			esc_url( $url )
431
		);
432
	}
433
434
	$sanitized_url          = youtube_sanitize_url( $url );
435
	$parsed_url             = wp_parse_url( $sanitized_url );
436
	$args                   = jetpack_shortcode_youtube_args( $parsed_url );
0 ignored issues
show
Documentation introduced by
$parsed_url is of type string|false, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
437
	list( $width, $height ) = jetpack_shortcode_youtube_dimensions( $args );
0 ignored issues
show
Security Bug introduced by
It seems like $args can also be of type false; however, jetpack_shortcode_youtube_dimensions() does only seem to accept array, did you maybe forget to handle an error condition?
Loading history...
438
	return sprintf(
439
		'<amp-youtube data-videoid="%s" layout="responsive" width="%d" height="%d"></amp-youtube>',
440
		esc_attr( $video_id ),
441
		absint( $width ),
442
		absint( $height )
443
	);
444
}
445
446
/**
447
 * Gets the dimensions of the [youtube] shortcode.
448
 *
449
 * Calculates the width and height, taking $content_width into consideration.
450
 *
451
 * @since 8.0.0
452
 *
453
 * @param array $query_args The query args of the URL.
454
 *
455
 * @return array The width and height of the shortcode.
456
 */
457
function jetpack_shortcode_youtube_dimensions( $query_args ) {
458
	global $content_width;
459
460
	$input_w = ( isset( $query_args['w'] ) && (int) $query_args['w'] ) ? (int) $query_args['w'] : 0;
461
	$input_h = ( isset( $query_args['h'] ) && (int) $query_args['h'] ) ? (int) $query_args['h'] : 0;
462
463
	// If we have $content_width, use it.
464
	if ( ! empty( $content_width ) ) {
465
		$default_width = $content_width;
466
	} else {
467
		// Otherwise get default width from the old, now deprecated embed_size_w option.
468
		$default_width = get_option( 'embed_size_w' );
469
	}
470
471
	// If we don't know those 2 values use a hardcoded width.
472
	if ( empty( $default_width ) ) {
473
		$default_width = 640;
474
	}
475
476
	if ( $input_w > 0 && $input_h > 0 ) {
477
		$w = $input_w;
478
		$h = $input_h;
479
	} elseif ( 0 === $input_w && 0 === $input_h ) {
480 View Code Duplication
		if ( isset( $query_args['fmt'] ) && (int) $query_args['fmt'] ) {
481
			$w = ( ! empty( $content_width ) ? min( $content_width, 480 ) : 480 );
482
		} else {
483
			$w = ( ! empty( $content_width ) ? min( $content_width, $default_width ) : $default_width );
484
			$h = ceil( ( $w / 16 ) * 9 );
485
		}
486
	} elseif ( $input_w > 0 ) {
487
		$w = $input_w;
488
		$h = ceil( ( $w / 16 ) * 9 );
489 View Code Duplication
	} else {
490
		if ( isset( $query_args['fmt'] ) && (int) $query_args['fmt'] ) {
491
			$w = ( ! empty( $content_width ) ? min( $content_width, 480 ) : 480 );
492
		} else {
493
			$w = ( ! empty( $content_width ) ? min( $content_width, $default_width ) : $default_width );
494
			$h = $input_h;
495
		}
496
	}
497
498
	/**
499
	 * Filter the YouTube player width.
500
	 *
501
	 * @module shortcodes
502
	 *
503
	 * @since 1.1.0
504
	 *
505
	 * @param int $w Width of the YouTube player in pixels.
506
	 */
507
	$w = (int) apply_filters( 'youtube_width', $w );
508
509
	/**
510
	 * Filter the YouTube player height.
511
	 *
512
	 * @module shortcodes
513
	 *
514
	 * @since 1.1.0
515
	 *
516
	 * @param int $h Height of the YouTube player in pixels.
517
	 */
518
	$h = (int) apply_filters( 'youtube_height', $h );
0 ignored issues
show
Bug introduced by
The variable $h does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
519
520
	return array( $w, $h );
521
}
522
523
/**
524
 * For bare URLs on their own line of the form
525
 * http://www.youtube.com/v/9FhMMmqzbD8?fs=1&hl=en_US
526
 *
527
 * @param array $matches Regex partial matches against the URL passed.
528
 * @param array $attr    Attributes received in embed response.
529
 * @param array $url     Requested URL to be embedded.
530
 */
531
function wpcom_youtube_embed_crazy_url( $matches, $attr, $url ) {
532
	return youtube_id( $url );
0 ignored issues
show
Documentation introduced by
$url is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
533
}
534
535
/**
536
 * Add a new handler to automatically transform custom Youtube URLs (like playlists) into embeds.
537
 */
538
function wpcom_youtube_embed_crazy_url_init() {
539
	wp_embed_register_handler( 'wpcom_youtube_embed_crazy_url', '#https?://(?:www\.)?(?:youtube.com/(?:v/|playlist|watch[/\#?])|youtu\.be/).*#i', 'wpcom_youtube_embed_crazy_url' );
540
}
541
add_action( 'init', 'wpcom_youtube_embed_crazy_url_init' );
542
543 View Code Duplication
if (
544
	! is_admin()
545
	/**
546
	 * Allow oEmbeds in Jetpack's Comment form.
547
	 *
548
	 * @module shortcodes
549
	 *
550
	 * @since 2.8.0
551
	 *
552
	 * @param int $allow_oembed Option to automatically embed all plain text URLs.
553
	 */
554
	&& apply_filters( 'jetpack_comments_allow_oembed', true )
555
	// No need for this on WordPress.com, this is done for multiple shortcodes at a time there.
556
	&& ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM )
557
) {
558
	/*
559
	 * We attach wp_kses_post to comment_text in default-filters.php with priority of 10 anyway,
560
	 * so the iframe gets filtered out.
561
	 * Higher priority because we need it before auto-link and autop get to it.
562
	 */
563
	add_filter( 'comment_text', 'youtube_link', 1 );
564
}
565
566
/**
567
 * Core changes to do_shortcode (https://core.trac.wordpress.org/changeset/34747) broke "improper" shortcodes
568
 * with the format [shortcode=http://url.com].
569
 *
570
 * This removes the "=" from the shortcode so it can be parsed.
571
 *
572
 * @see https://github.com/Automattic/jetpack/issues/3121
573
 *
574
 * @param string $content HTML content.
575
 */
576
function jetpack_fix_youtube_shortcode_display_filter( $content ) {
577
	if ( strpos( $content, '[youtube=' ) !== false ) {
578
		$content = preg_replace( '@\[youtube=(.*?)\]@', '[youtube $1]', $content );
579
	}
580
581
	return $content;
582
}
583
add_filter( 'the_content', 'jetpack_fix_youtube_shortcode_display_filter', 7 );
584