Completed
Push — fix/prevent-modules-overwrite ( c3826b...9882d9 )
by
unknown
96:00 queued 89:21
created

Jetpack_Slideshow_Shortcode   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 309
Duplicated Lines 4.53 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 33
lcom 1
cbo 2
dl 14
loc 309
rs 9.76
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 21 4
A post_gallery() 0 13 4
A add_gallery_type() 0 5 1
A register_settings() 7 7 1
B settings_select() 0 20 6
A slideshow_background_color_sanitize() 0 3 2
D shortcode_callback() 0 104 10
A slideshow_js() 0 44 2
A enqueue_scripts() 0 37 1
A init() 0 3 1
A slideshow_background_color_callback() 7 7 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * Slideshow shortcode usage: [gallery type="slideshow"] or the older [slideshow]
5
 */
6
class Jetpack_Slideshow_Shortcode {
7
	public $instance_count = 0;
8
9
	function __construct() {
10
		global $shortcode_tags;
11
12
		// Only if the slideshow shortcode has not already been defined.
13
		if ( ! array_key_exists( 'slideshow', $shortcode_tags ) ) {
14
			add_shortcode( 'slideshow', array( $this, 'shortcode_callback' ) );
15
		}
16
17
		// Only if the gallery shortcode has not been redefined.
18
		if ( isset( $shortcode_tags['gallery'] ) && 'gallery_shortcode' === $shortcode_tags['gallery'] ) {
19
			add_filter( 'post_gallery', array( $this, 'post_gallery' ), 1002, 2 );
20
			add_filter( 'jetpack_gallery_types', array( $this, 'add_gallery_type' ), 10 );
21
		}
22
23
		/**
24
		 * For the moment, comment out the setting for v2.8.
25
		 * The remainder should work as it always has.
26
		 * See: https://github.com/Automattic/jetpack/pull/85/files
27
		 */
28
		// add_action( 'admin_init', array( $this, 'register_settings' ), 5 );
29
	}
30
31
	/**
32
	 * Responds to the [gallery] shortcode, but not an actual shortcode callback.
33
	 *
34
	 * @param $value string An empty string if nothing has modified the gallery output, the output html otherwise
35
	 * @param $attr  array The shortcode attributes array
36
	 *
37
	 * @return string The (un)modified $value
38
	 */
39
	function post_gallery( $value, $attr ) {
40
		// Bail if somebody else has done something
41
		if ( ! empty( $value ) ) {
42
			return $value;
43
		}
44
45
		// If [gallery type="slideshow"] have it behave just like [slideshow]
46
		if ( ! empty( $attr['type'] ) && 'slideshow' == $attr['type'] ) {
47
			return $this->shortcode_callback( $attr );
48
		}
49
50
		return $value;
51
	}
52
53
	/**
54
	 * Add the Slideshow type to gallery settings
55
	 *
56
	 * @see Jetpack_Tiled_Gallery::media_ui_print_templates
57
	 *
58
	 * @param $types array An array of types where the key is the value, and the value is the caption.
59
	 *
60
	 * @return array
61
	 */
62
	function add_gallery_type( $types = array() ) {
63
		$types['slideshow'] = esc_html__( 'Slideshow', 'jetpack' );
64
65
		return $types;
66
	}
67
68 View Code Duplication
	function register_settings() {
69
		add_settings_section( 'slideshow_section', __( 'Image Gallery Slideshow', 'jetpack' ), '__return_empty_string', 'media' );
70
71
		add_settings_field( 'jetpack_slideshow_background_color', __( 'Background color', 'jetpack' ), array( $this, 'slideshow_background_color_callback' ), 'media', 'slideshow_section' );
72
73
		register_setting( 'media', 'jetpack_slideshow_background_color', array( $this, 'slideshow_background_color_sanitize' ) );
74
	}
75
76 View Code Duplication
	function slideshow_background_color_callback() {
77
		$options = array(
78
			'black' => __( 'Black', 'jetpack' ),
79
			'white' => __( 'White', 'jetpack' ),
80
		);
81
		$this->settings_select( 'jetpack_slideshow_background_color', $options );
82
	}
83
84
	function settings_select( $name, $values, $extra_text = '' ) {
85
		if ( empty( $name ) || empty( $values ) || ! is_array( $values ) ) {
86
			return;
87
		}
88
		$option = get_option( $name );
89
		?>
90
		<fieldset>
91
			<select name="<?php echo esc_attr( $name ); ?>" id="<?php echo esc_attr( $name ); ?>">
92
				<?php foreach ( $values as $key => $value ) : ?>
93
					<option value="<?php echo esc_attr( $key ); ?>" <?php selected( $key, $option ); ?>>
94
						<?php echo esc_html( $value ); ?>
95
					</option>
96
				<?php endforeach; ?>
97
			</select>
98
			<?php if ( ! empty( $extra_text ) ) : ?>
99
				<p class="description"><?php echo esc_html( $extra_text ); ?></p>
100
			<?php endif; ?>
101
		</fieldset>
102
		<?php
103
	}
104
105
	function slideshow_background_color_sanitize( $value ) {
106
		return ( 'white' == $value ) ? 'white' : 'black';
107
	}
108
109
	function shortcode_callback( $attr ) {
110
		$post_id = get_the_ID();
111
112
		$attr = shortcode_atts(
113
			array(
114
				'trans'     => 'fade',
115
				'order'     => 'ASC',
116
				'orderby'   => 'menu_order ID',
117
				'id'        => $post_id,
118
				'include'   => '',
119
				'exclude'   => '',
120
				'autostart' => true,
121
				'size'      => '',
122
			),
123
			$attr,
124
			'slideshow'
125
		);
126
127
		if ( 'rand' == strtolower( $attr['order'] ) ) {
128
			$attr['orderby'] = 'none';
129
		}
130
131
		$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
132
		if ( ! $attr['orderby'] ) {
133
			$attr['orderby'] = 'menu_order ID';
134
		}
135
136
		if ( ! $attr['size'] ) {
137
			$attr['size'] = 'full';
138
		}
139
140
		// Don't restrict to the current post if include
141
		$post_parent = ( empty( $attr['include'] ) ) ? intval( $attr['id'] ) : null;
142
143
		$attachments = get_posts(
144
			array(
145
				'post_status'      => 'inherit',
146
				'post_type'        => 'attachment',
147
				'post_mime_type'   => 'image',
148
				'posts_per_page'   => - 1,
149
				'post_parent'      => $post_parent,
150
				'order'            => $attr['order'],
151
				'orderby'          => $attr['orderby'],
152
				'include'          => $attr['include'],
153
				'exclude'          => $attr['exclude'],
154
				'suppress_filters' => false,
155
			)
156
		);
157
158
		if ( count( $attachments ) < 1 ) {
159
			return false;
160
		}
161
162
		$gallery_instance = sprintf( 'gallery-%d-%d', $attr['id'], ++$this->instance_count );
163
164
		$gallery = array();
165
		foreach ( $attachments as $attachment ) {
166
			$attachment_image_src   = wp_get_attachment_image_src( $attachment->ID, $attr['size'] );
167
			$attachment_image_src   = $attachment_image_src[0]; // [url, width, height]
168
			$attachment_image_title = get_the_title( $attachment->ID );
169
			$attachment_image_alt   = get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true );
170
			/**
171
			 * Filters the Slideshow slide caption.
172
			 *
173
			 * @module shortcodes
174
			 *
175
			 * @since 2.3.0
176
			 *
177
			 * @param string wptexturize( strip_tags( $attachment->post_excerpt ) ) Post excerpt.
178
			 * @param string $attachment ->ID Attachment ID.
179
			 */
180
			$caption = apply_filters( 'jetpack_slideshow_slide_caption', wptexturize( strip_tags( $attachment->post_excerpt ) ), $attachment->ID );
181
182
			$gallery[] = (object) array(
183
				'src'      => (string) esc_url_raw( $attachment_image_src ),
184
				'id'       => (string) $attachment->ID,
185
				'title'    => (string) esc_attr( $attachment_image_title ),
186
				'alt'      => (string) esc_attr( $attachment_image_alt ),
187
				'caption'  => (string) $caption,
188
				'itemprop' => 'image',
189
			);
190
		}
191
192
		$color = Jetpack_Options::get_option( 'slideshow_background_color', 'black' );
193
194
		$js_attr = array(
195
			'gallery'   => $gallery,
196
			'selector'  => $gallery_instance,
197
			'trans'     => $attr['trans'] ? $attr['trans'] : 'fade',
198
			'autostart' => $attr['autostart'] ? $attr['autostart'] : 'true',
199
			'color'     => $color,
200
		);
201
202
		// Show a link to the gallery in feeds.
203
		if ( is_feed() ) {
204
			return sprintf(
205
				'<a href="%s">%s</a>',
206
				esc_url( get_permalink( $post_id ) . '#' . $gallery_instance . '-slideshow' ),
207
				esc_html__( 'Click to view slideshow.', 'jetpack' )
208
			);
209
		}
210
211
		return $this->slideshow_js( $js_attr );
212
	}
213
214
	/**
215
	 * Render the slideshow js
216
	 *
217
	 * Returns the necessary markup and js to fire a slideshow.
218
	 *
219
	 * @param $attr array Attributes for the slideshow.
220
	 *
221
	 * @uses $this->enqueue_scripts()
222
	 *
223
	 * @return string HTML output.
224
	 */
225
	function slideshow_js( $attr ) {
226
		// Enqueue scripts
227
		$this->enqueue_scripts();
228
229
		$output = '';
230
231
		if ( defined( 'JSON_HEX_AMP' ) ) {
232
			// This is nice to have, but not strictly necessary since we use _wp_specialchars() below
233
			$gallery = json_encode( $attr['gallery'], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ); // phpcs:ignore PHPCompatibility
234
		} else {
235
			$gallery = json_encode( $attr['gallery'] );
236
		}
237
238
		$output .= '<p class="jetpack-slideshow-noscript robots-nocontent">' . esc_html__( 'This slideshow requires JavaScript.', 'jetpack' ) . '</p>';
239
		$output .= sprintf(
240
			'<div id="%s" class="slideshow-window jetpack-slideshow slideshow-%s" data-trans="%s" data-autostart="%s" data-gallery="%s" itemscope itemtype="https://schema.org/ImageGallery"></div>',
241
			esc_attr( $attr['selector'] . '-slideshow' ),
242
			esc_attr( $attr['color'] ),
243
			esc_attr( $attr['trans'] ),
244
			esc_attr( $attr['autostart'] ),
245
			/*
246
			 * The input to json_encode() above can contain '&quot;'.
247
			 *
248
			 * For calls to json_encode() lacking the JSON_HEX_AMP option,
249
			 * that '&quot;' is left unaltered.  Running '&quot;' through esc_attr()
250
			 * also leaves it unaltered since esc_attr() does not double-encode.
251
			 *
252
			 * This means we end up with an attribute like
253
			 * `data-gallery="{&quot;foo&quot;:&quot;&quot;&quot;}"`,
254
			 * which is interpreted by the browser as `{"foo":"""}`,
255
			 * which cannot be JSON decoded.
256
			 *
257
			 * The preferred workaround is to include the JSON_HEX_AMP (and friends)
258
			 * options, but these are not available until 5.3.0.
259
			 * Alternatively, we can use _wp_specialchars( , , , true ) instead of
260
			 * esc_attr(), which will double-encode.
261
			 *
262
			 * Since we can't rely on JSON_HEX_AMP, we do both.
263
			 */
264
			_wp_specialchars( wp_check_invalid_utf8( $gallery ), ENT_QUOTES, false, true )
265
		);
266
267
		return $output;
268
	}
269
270
	/**
271
	 * Actually enqueues the scripts and styles.
272
	 */
273
	function enqueue_scripts() {
274
275
		wp_enqueue_script( 'jquery-cycle', plugins_url( '/js/jquery.cycle.min.js', __FILE__ ), array( 'jquery' ), '20161231', true );
276
		wp_enqueue_script(
277
			'jetpack-slideshow',
278
			Jetpack::get_file_url_for_environment( '_inc/build/shortcodes/js/slideshow-shortcode.min.js', 'modules/shortcodes/js/slideshow-shortcode.js' ),
279
			array( 'jquery-cycle' ),
280
			'20160119.1',
281
			true
282
		);
283
		wp_enqueue_style( 'jetpack-slideshow', plugins_url( '/css/slideshow-shortcode.css', __FILE__ ) );
284
		wp_style_add_data( 'jetpack-slideshow', 'rtl', 'replace' );
285
286
		wp_localize_script(
287
			'jetpack-slideshow',
288
			'jetpackSlideshowSettings',
289
			/**
290
			 * Filters the slideshow JavaScript spinner.
291
			 *
292
			 * @module shortcodes
293
			 *
294
			 * @since 2.1.0
295
			 * @since 4.7.0 Added the `speed` option to the array of options.
296
			 *
297
			 * @param array $args
298
			 * - string - spinner - URL of the spinner image.
299
			 * - string - speed   - Speed of the slideshow. Defaults to 4000.
300
			 */
301
			apply_filters(
302
				'jetpack_js_slideshow_settings',
303
				array(
304
					'spinner' => plugins_url( '/img/slideshow-loader.gif', __FILE__ ),
305
					'speed'   => '4000',
306
				)
307
			)
308
		);
309
	}
310
311
	public static function init() {
312
		new Jetpack_Slideshow_Shortcode();
313
	}
314
}
315
316
Jetpack_Slideshow_Shortcode::init();
317