Completed
Push — fix/space-twitter-4455 ( 859b70...d25e05 )
by Jeremy
20:31 queued 11:02
created

dailymotion.php ➔ dailymotion_shortcode()   F

Complexity

Conditions 39
Paths > 20000

Size

Total Lines 121
Code Lines 77

Duplication

Lines 12
Ratio 9.92 %

Importance

Changes 4
Bugs 3 Features 0
Metric Value
cc 39
eloc 77
c 4
b 3
f 0
nc 204802
nop 1
dl 12
loc 121
rs 2

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
/**
4
 * Dailymotion code
5
 * */
6
7
/**
8
 * Original codes:
9
 *
10
 * <embed height="270" type="application/x-shockwave-flash" width="480" src="http&#58;//www.dailymotion.com/swf/video/xekmrq?additionalInfos=0" wmode="opaque" pluginspage="http&#58;//www.macromedia.com/go/getflashplayer" allowscriptaccess="never" allownetworking="internal" />
11
 *
12
 * <object width="480" height="240"><param name="movie" value="http://www.dailymotion.com/swf/video/xen4ms_ghinzu-cold-love-mirror-mirror_music?additionalInfos=0"></param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param>
13
 * 	<embed type="application/x-shockwave-flash" src="http://www.dailymotion.com/swf/video/xen4ms_ghinzu-cold-love-mirror-mirror_music?additionalInfos=0" width="480" height="240" allowfullscreen="true" allowscriptaccess="always"></embed>
14
 * </object><br /><b><a href="http://www.dailymotion.com/video/xen4ms_ghinzu-cold-love-mirror-mirror_music">Ghinzu - Cold Love (Mirror Mirror)</a></b><br /><i>Uploaded by <a href="http://www.dailymotion.com/GhinzuTV">GhinzuTV</a>. - <a href="http://www.dailymotion.com/us/channel/music">Watch more music videos, in HD!</a></i>
15
 *
16
 * Code as of 01.01.11:
17
 * <object width="560" height="421"><param name="movie" value="http://www.dailymotion.com/swf/video/xaose5?width=560&theme=denim&foreground=%2392ADE0&highlight=%23A2ACBF&background=%23202226&start=&animatedTitle=&iframe=0&additionalInfos=0&autoPlay=0&hideInfos=0"></param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param><embed type="application/x-shockwave-flash" src="http://www.dailymotion.com/swf/video/xaose5?width=560&theme=denim&foreground=%2392ADE0&highlight=%23A2ACBF&background=%23202226&start=&animatedTitle=&iframe=0&additionalInfos=0&autoPlay=0&hideInfos=0" width="560" height="421" allowfullscreen="true" allowscriptaccess="always"></embed></object><br /><b><a href="http://www.dailymotion.com/video/x29zm17_funny-videos-of-cats-and-babies-compilation-2015_fun">Funny cats and babies!</a></b><br /><i>Uploaded by <a href="http://www.dailymotion.com/GilLavie">GilLavie</a>. - <a target="_self" href="http://www.dailymotion.com/channel/funny/featured/1">Find more funny videos.</a></i>
18
 * movie param enforces anti-xss protection
19
 *
20
 * Scroll down for the new <iframe> embed code handler.
21
 */
22
23
function dailymotion_embed_to_shortcode( $content ) {
24
	if ( false === stripos( $content, 'www.dailymotion.com/swf/' ) ) {
25
		return $content;
26
	}
27
28
	$regexp     = '!<object.*>\s*(<param.*></param>\s*)*<embed((?:\s+\w+="[^"]*")*)\s+src="http(?:\:|&#0*58;)//(www\.dailymotion\.com/swf/[^"]*)"((?:\s+\w+="[^"]*")*)\s*(?:/>|>\s*</embed>)\s*</object><br /><b><a .*>.*</a></b><br /><i>.*</i>!';
29
	$regexp_ent = str_replace( '&amp;#0*58;', '&amp;#0*58;|&#0*58;', htmlspecialchars( $regexp, ENT_NOQUOTES ) );
30
31
	foreach ( array( 'regexp', 'regexp_ent' ) as $reg ) {
32
		if ( ! preg_match_all( $$reg, $content, $matches, PREG_SET_ORDER ) ) {
33
			continue;
34
		}
35
36
		foreach ( $matches as $match ) {
37
			$src    = html_entity_decode( $match[3] );
38
			$params = $match[2] . $match[4];
39
40
			if ( 'regexp_ent' == $reg ) {
41
				$src    = html_entity_decode( $src );
42
				$params = html_entity_decode( $params );
43
			}
44
45
			$params = wp_kses_hair( $params, array( 'http' ) );
46
47
			if ( ! isset( $params['type'] ) || 'application/x-shockwave-flash' != $params['type']['value'] ) {
48
				continue;
49
			}
50
51
			$id = basename( substr( $src, strlen( 'www.dailymotion.com/swf' ) ) );
52
			$id = preg_replace( '/[^a-z0-9].*$/i', '', $id );
53
54
			$content = str_replace( $match[0], "[dailymotion id=$id]", $content );
55
			/** This action is documented in modules/shortcodes/youtube.php */
56
			do_action( 'jetpack_embed_to_shortcode', 'dailymotion', $id );
57
		}
58
	}
59
	return $content;
60
}
61
add_filter( 'pre_kses', 'dailymotion_embed_to_shortcode' );
62
63
/**
64
 * DailyMotion shortcode
65
 *
66
 * The documented shortcode is:
67
 * [dailymotion id=x8oma9]
68
 *
69
 * Possibilities, according to the old parsing regexp:
70
 * [dailymotion x8oma9]
71
 * [dailymotion=x8oma9]
72
 *
73
 * Hypothetical option, according to the old shortcode function is
74
 * [dailymotion id=1&title=2&user=3&video=4]
75
 *
76
 * The new style is now:
77
 * [dailymotion id=x8oma9 title=2 user=3 video=4]
78
 *
79
 * Supported parameters for player customization: width, height,
80
 * autoplay, endscreen-enable, mute, sharing-enabled, start, subtitles-default,
81
 * ui-highlight, ui-logo, ui-start-screen-info, ui-theme
82
 * see https://developer.dailymotion.com/player#player-parameters
83
 * @todo: Update code to sniff for iframe embeds and convert those to shortcodes.
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
84
 *
85
 * @param array $atts
86
 * @return string html
87
 *
88
 */
89
90
function dailymotion_shortcode( $atts ) {
91
	global $content_width;
92
93
	if ( isset( $atts[0] ) ) {
94
		$id = ltrim( $atts[0], '=' );
95
		$atts['id'] = $id;
96
97
	} else {
98
		$params = shortcode_new_to_old_params( $atts );
99
		parse_str( $params, $atts_new );
100
101
		foreach ( $atts_new as $k => $v ) {
0 ignored issues
show
Bug introduced by
The expression $atts_new of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
102
			$atts[ $k ] = $v;
103
		}
104
	}
105
106
	$atts = shortcode_atts(
107
		array(
108
			'id'                   => '', // string
109
			'width'                => '', // int
110
			'height'               => '', // int
111
			'title'                => '', // string
112
			'user'                 => '', // string
113
			'video'                => '', // string
114
			'autoplay'             => 0,  // int
115
			'endscreen-enable'     => 1,  // int
116
			'mute'                 => 0,  // int
117
			'sharing-enable'       => 1,  // int
118
			'start'                => '', // int
119
			'subtitles-default'    => '', // string
120
			'ui-highlight'         => '', // string
121
			'ui-logo'              => 1,  // int
122
			'ui-start-screen-info' => 0,  // int
123
			'ui-theme'             => '', // string
124
		), $atts, 'dailymotion'
125
	);
126
127
	if ( isset( $atts['id'] ) && ! empty( $atts['id'] ) ) {
128
		$id = urlencode( $atts['id'] );
129
	} else {
130
		return '<!--Dailymotion error: bad or missing ID-->';
131
	}
132
133
	/*set width and height using provided parameters if any */
134
	$width  = isset( $atts['width'] )  ? intval( $atts['width'] )  : 0 ;
135
	$height = isset( $atts['height'] ) ? intval( $atts['height'] ) : 0 ;
136
137
	if ( ! $width && ! $height ) {
138
		if ( ! empty( $content_width ) ) {
139
			$width = absint( $content_width );
140
		} else {
141
			$width = 425;
142
		}
143
		$height = $width / 425 * 334;
144
	} elseif ( ! $height ) {
145
		$height = $width / 425 * 334;
146
	} elseif ( ! $width ) {
147
		$width = $height / 334 * 425;
148
	}
149
150
	/**
151
	 * Let's add parameters if needed.
152
	 *
153
	 * @see https://developer.dailymotion.com/player
154
	 */
155
	$player_params = array();
156
157 View Code Duplication
	if ( isset( $atts['autoplay'] ) && '1' === $atts['autoplay'] ) {
158
		$player_params['autoplay'] = '1';
159
	}
160
	if ( isset( $atts['endscreen-enable'] ) && '0' === $atts['endscreen-enable'] ) {
161
		$player_params['endscreen-enable'] = '0';
162
	}
163 View Code Duplication
	if ( isset( $atts['mute'] ) && '1' === $atts['mute'] ) {
164
		$player_params['mute'] = '1';
165
	}
166
	if ( isset( $atts['sharing-enable'] ) && '0' === $atts['sharing-enable'] ) {
167
		$player_params['sharing-enable'] = '0';
168
	}
169
	if ( isset( $atts['start'] ) && ! empty( $atts['start'] ) ) {
170
		$player_params['start'] = abs( intval( $atts['start'] ) );
171
	}
172 View Code Duplication
	if ( isset( $atts['subtitles-default'] ) && ! empty( $atts['subtitles-default'] ) ) {
173
		$player_params['subtitles-default'] = esc_attr( $atts['subtitles-default'] );
174
	}
175 View Code Duplication
	if ( isset( $atts['ui-highlight'] ) && ! empty( $atts['ui-highlight'] ) ) {
176
		$player_params['ui-highlight'] = esc_attr( $atts['ui-highlight'] );
177
	}
178
	if ( isset( $atts['ui-logo'] ) && '0' === $atts['ui-logo'] ) {
179
		$player_params['ui-logo'] = '0';
180
	}
181
	if ( isset( $atts['ui-start-screen-info'] ) && '0' === $atts['ui-start-screen-info'] ) {
182
		$player_params['ui-start-screen-info'] = '0';
183
	}
184
	if ( isset( $atts['ui-theme'] ) && in_array( strtolower( $atts['ui-theme'] ), array( 'dark', 'light' ) ) ) {
185
		$player_params['ui-theme'] = esc_attr( $atts['ui-theme'] );
186
	}
187
188
	// Add those parameters to the Video URL.
189
	$video_url = add_query_arg(
190
		$player_params,
191
		'https://www.dailymotion.com/embed/video/' . $id
192
	);
193
194
	$output = '';
195
196
	if ( preg_match( '/^[A-Za-z0-9]+$/', $id ) ) {
197
		$output .= '<iframe width="' . esc_attr( $width ) . '" height="' . esc_attr( $height ) . '" src="' . esc_url( $video_url ) . '" style="border:0;" allowfullscreen></iframe>';
198
199
		if ( array_key_exists( 'video', $atts ) && $video = preg_replace( '/[^-a-z0-9_]/i', '', $atts['video'] ) && array_key_exists( 'title', $atts ) && $title = wp_kses( $atts['title'], array() ) ) {
0 ignored issues
show
Comprehensibility introduced by
Consider adding parentheses for clarity. Current Interpretation: $video = (preg_replace('...ts['title'], array()))), Probably Intended Meaning: ($video = preg_replace('...atts['title'], array())
Loading history...
200
			$output .= '<br /><strong><a href="' . esc_url( 'http://www.dailymotion.com/video/' . $video ) . '" target="_blank">' . esc_html( $title ) . '</a></strong>';
0 ignored issues
show
Bug introduced by
The variable $title 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...
201
		}
202
203
		if ( array_key_exists( 'user', $atts ) && $user = preg_replace( '/[^-a-z0-9_]/i', '', $atts['user'] ) ) {
204
			/* translators: %s is a Dailymotion user name */
205
			$output .= '<br /><em>' . wp_kses( sprintf( __( 'Uploaded by %s', 'jetpack' ), '<a href="' . esc_url( 'http://www.dailymotion.com/' . $user ) . '" target="_blank">' . esc_html( $user ) . '</a>' ), array( 'a' => array( 'href' => true, 'target' => true ) ) ) . '</em>';			
206
		}
207
	}
208
209
	return $output;
210
}
211
212
add_shortcode( 'dailymotion', 'dailymotion_shortcode' );
213
214
/**
215
 * DailyMotion Channel Shortcode
216
 *
217
 * Examples:
218
 * [dailymotion-channel user=MatthewDominick]
219
 * [dailymotion-channel user=MatthewDominick type=grid] (supports grid, carousel, badge/default)
220
 */
221
function dailymotion_channel_shortcode( $atts ) {
222
	$username = $atts['user'];
223
224
	switch( $atts['type'] ) {
225
		case 'grid':
226
			return '<iframe width="300px" height="264px" scrolling="no" style="border:0;" src="' . esc_url( '//www.dailymotion.com/badge/user/' . $username . '?type=grid' ) . '"></iframe>';
227
			break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
228
		case 'carousel':
229
			return '<iframe width="300px" height="360px" scrolling="no" style="border:0;" src="' . esc_url( '//www.dailymotion.com/badge/user/' . $username . '?type=carousel' ) . '"></iframe>';
230
			break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
231
		default:
232
			return '<iframe width="300px" height="78px" scrolling="no" style="border:0;" src="' . esc_url( '//www.dailymotion.com/badge/user/' . $username ) . '"></iframe>';
233
	}
234
}
235
236
add_shortcode( 'dailymotion-channel', 'dailymotion_channel_shortcode' );
237
238
/**
239
 * Embed Reversal for Badge/Channel
240
 */
241
function dailymotion_channel_reversal( $content ) {
242
	if ( false === stripos( $content, 'dailymotion.com/badge/' ) ) {
243
		return $content;
244
	}
245
246
	/* Sample embed code:
247
		<iframe width="300px" height="360px" scrolling="no" frameborder="0" src="http://www.dailymotion.com/badge/user/Dailymotion?type=carousel"></iframe>
248
	*/
249
250
	$regexes = array();
251
252
	$regexes[] = '#<iframe[^>]+?src=" (?:https?:)?//(?:www\.)?dailymotion\.com/badge/user/([^"\'/]++) "[^>]*+></iframe>#ix';
253
254
	// Let's play nice with the visual editor too.
255
	$regexes[] = '#&lt;iframe(?:[^&]|&(?!gt;))+?src=" (?:https?:)?//(?:www\.)?dailymotion\.com/badge/user/([^"\'/]++) "(?:[^&]|&(?!gt;))*+&gt;&lt;/iframe&gt;#ix';
256
257
	foreach ( $regexes as $regex ) {
258
		if ( ! preg_match_all( $regex, $content, $matches, PREG_SET_ORDER ) ) {
259
	 		continue;
260
		}
261
262
		foreach ( $matches as $match ) {
263
			$url_pieces = parse_url( $match[1] );
264
265
			if ( 'type=carousel' === $url_pieces['query'] ) {
266
				$type = 'carousel';
267
			} else if ( 'type=grid' === $url_pieces['query'] ) {
268
				$type = 'grid';
269
			} else {
270
				$type = 'badge';
271
			}
272
273
			$shortcode = '[dailymotion-channel user=' . esc_attr( $url_pieces['path'] ) . ' type=' . esc_attr( $type ) . ']';
274
			$replace_regex = sprintf( '#\s*%s\s*#', preg_quote( $match[0], '#' ) );
275
			$content       = preg_replace( $replace_regex, sprintf( "\n\n%s\n\n", $shortcode ), $content );
276
		}
277
	}
278
279
	return $content;
280
}
281
282
add_filter( 'pre_kses', 'dailymotion_channel_reversal' );
283
284
/**
285
 * Dailymotion Embed Reversal (with new iframe code as of 17.09.2014)
286
 *
287
 * Converts a generic HTML embed code from Dailymotion into an
288
 * oEmbeddable URL.
289
 */
290
291
function jetpack_dailymotion_embed_reversal( $content ) {
292
	if ( false === stripos( $content, 'dailymotion.com/embed' ) ) {
293
		return $content;
294
	}
295
296
	/* Sample embed code as of Sep 17th 2014:
297
298
		<iframe frameborder="0" width="480" height="270" src="//www.dailymotion.com/embed/video/x25x71x" allowfullscreen></iframe><br /><a href="http://www.dailymotion.com/video/x25x71x_dog-with-legs-in-casts-learns-how-to-enter-the-front-door_animals" target="_blank">Dog with legs in casts learns how to enter the...</a> <i>by <a href="http://www.dailymotion.com/videobash" target="_blank">videobash</a></i>
299
	*/
300
	$regexes = array();
301
302
	// I'm Konstantin and I love regex.
303
	$regexes[] = '#<iframe[^>]+?src=" (?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/([^"\'/]++) "[^>]*+>\s*+</iframe>\s*+(?:<br\s*+/>)?\s*+
304
	(?: <a[^>]+?href=" (?:https?:)?//(?:www\.)?dailymotion\.com/[^"\']++ "[^>]*+>.+?</a>\s*+ )?
305
	(?: <i>.*?<a[^>]+?href=" (?:https?:)?//(?:www\.)?dailymotion\.com/[^"\']++ "[^>]*+>.+?</a>\s*+</i> )?#ix';
306
307
	$regexes[] = '#&lt;iframe(?:[^&]|&(?!gt;))+?src=" (?:https?:)?//(?:www\.)?dailymotion\.com/embed/video/([^"\'/]++) "(?:[^&]|&(?!gt;))*+&gt;\s*+&lt;/iframe&gt;\s*+(?:&lt;br\s*+/&gt;)?\s*+
308
	(?: &lt;a(?:[^&]|&(?!gt;))+?href=" (?:https?:)?//(?:www\.)?dailymotion\.com/[^"\']++ "(?:[^&]|&(?!gt;))*+&gt;.+?&lt;/a&gt;\s*+ )?
309
	(?: &lt;i&gt;.*?&lt;a(?:[^&]|&(?!gt;))+?href=" (?:https?:)?//(?:www\.)?dailymotion\.com/[^"\']++ "(?:[^&]|&(?!gt;))*+&gt;.+?&lt;/a&gt;\s*+&lt;/i&gt; )?#ix';
310
311 View Code Duplication
	foreach ( $regexes as $regex ) {
312
		if ( ! preg_match_all( $regex, $content, $matches, PREG_SET_ORDER ) ) {
313
			continue;
314
		}
315
316
		foreach ( $matches as $match ) {
317
			$url           = esc_url( sprintf( 'https://dailymotion.com/video/%s', $match[1] ) );
318
			$replace_regex = sprintf( '#\s*%s\s*#', preg_quote( $match[0], '#' ) );
319
			$content       = preg_replace( $replace_regex, sprintf( "\n\n%s\n\n", $url ), $content );
320
321
			/** This action is documented in modules/shortcodes/youtube.php */
322
			do_action( 'jetpack_embed_to_shortcode', 'dailymotion', $url );
323
		}
324
	}
325
326
	return $content;
327
}
328
329
add_filter( 'pre_kses', 'jetpack_dailymotion_embed_reversal' );
330