Completed
Push — add/sync-rest-2 ( dcf3c8...9df295 )
by
unknown
10:28
created

Jetpack_Gallery_Widget::get_attachments()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 22
rs 9.2
nc 2
cc 3
eloc 14
nop 1
1
<?php
2
3
/*
4
Plugin Name: Gallery
5
Description: Gallery widget
6
Author: Automattic, Inc.
7
Version: 1.0
8
Author URI: http://automattic.com
9
*/
10
11
class Jetpack_Gallery_Widget extends WP_Widget {
12
	const THUMB_SIZE 		= 45;
13
	const DEFAULT_WIDTH 	= 265;
14
15
	protected $_instance_width ;
16
17
	public function __construct() {
18
		$widget_ops 	= array(
19
			'classname'   => 'widget-gallery',
20
			'description' => __( 'Display a photo gallery or slideshow', 'jetpack' ),
21
			'customize_selective_refresh' => true,
22
		);
23
		$control_ops 	= array( 'width' => 250 );
24
25
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
26
27
		parent::__construct(
28
			'gallery',
29
			/** This filter is documented in modules/widgets/facebook-likebox.php */
30
			apply_filters( 'jetpack_widget_name', __( 'Gallery', 'jetpack' ) ),
31
			$widget_ops,
32
			$control_ops
33
		);
34
35
		if ( is_customize_preview() ) {
36
			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_scripts' ) );
37
38
			if ( class_exists( 'Jetpack_Tiled_Gallery' ) ) {
39
				$tiled_gallery = new Jetpack_Tiled_Gallery();
40
				add_action( 'wp_enqueue_scripts', array( $tiled_gallery, 'default_scripts_and_styles' ) );
41
			}
42
43
			if ( class_exists( 'Jetpack_Slideshow_Shortcode' ) ) {
44
				$slideshow = new Jetpack_Slideshow_Shortcode();
45
				add_action( 'wp_enqueue_scripts', array( $slideshow, 'enqueue_scripts' ) );
46
			}
47
48
			if ( class_exists( 'Jetpack_Carousel' ) ) {
49
				$carousel = new Jetpack_Carousel();
50
				add_action( 'wp_enqueue_scripts', array( $carousel, 'enqueue_assets' ) );
51
			}
52
		}
53
	}
54
55
	/**
56
	 * @param array $args Display arguments including before_title, after_title, before_widget, and after_widget.
57
	 * @param array $instance The settings for the particular instance of the widget.
58
	 */
59
	public function widget( $args, $instance ) {
60
		$instance = wp_parse_args( (array) $instance, $this->defaults() );
61
62
		$this->enqueue_frontend_scripts();
63
64
		extract( $args );
65
66
		$instance['attachments'] = $this->get_attachments( $instance );
67
68
		$classes = array();
69
70
		$classes[] = 'widget-gallery-' . $instance['type'];
71
72
		// Due to a bug in the carousel plugin, carousels will be triggered for all tiled galleries that exist on a page
73
		// with other tiled galleries, regardless of whether or not the widget was set to Carousel mode. The onClick selector
74
		// is simply too broad, since it was not written with widgets in mind. This special class prevents that behavior, via
75
		// an override handler in gallery.js
76
		if( 'carousel' != $instance['link'] && 'slideshow' != $instance['type'] )
77
			$classes[] = 'no-carousel';
78
		else
79
			$classes[] = 'carousel';
80
81
		$classes = implode( ' ', $classes );
82
83
		if ( 'carousel' == $instance['link'] ) {
84
			require_once plugin_dir_path( realpath( dirname( __FILE__ ) . '/../carousel/jetpack-carousel.php' ) ) . 'jetpack-carousel.php';
85
86
			if ( class_exists( 'Jetpack_Carousel' ) ) {
87
				// Create new carousel so we can use the enqueue_assets() method. Not ideal, but there is a decent amount
88
				// of logic in that method that shouldn't be duplicated.
89
				$carousel = new Jetpack_Carousel();
90
91
				// First parameter is $output, which comes from filters, and causes bypass of the asset enqueuing. Passing null is correct.
92
				$carousel->enqueue_assets( null );
93
			}
94
		}
95
96
		echo $before_widget . "\n";
97
98
		/** This filter is documented in core/src/wp-includes/default-widgets.php */
99
		$title = apply_filters( 'widget_title', $instance['title'] );
100
101
		if ( $title )
102
			echo $before_title . esc_html( $title ) . $after_title . "\n";
103
104
		echo '<div class="' . esc_attr( $classes ) . '">' . "\n";
105
106
		$method = $instance['type'] . '_widget';
107
108
		/**
109
		 * Allow the width of a gallery to be altered by themes or other code.
110
		 *
111
		 * @module widgets
112
		 *
113
		 * @since 2.5.0
114
		 *
115
		 * @param int self::DEFAULT_WIDTH Default gallery width. Default is 265.
116
		 * @param string $args Display arguments including before_title, after_title, before_widget, and after_widget.
117
		 * @param array $instance The settings for the particular instance of the widget.
118
		 */
119
		$this->_instance_width = apply_filters( 'gallery_widget_content_width', self::DEFAULT_WIDTH, $args, $instance );
120
121
		// Register a filter to modify the tiled_gallery_content_width, so Jetpack_Tiled_Gallery
122
		// can appropriately size the tiles.
123
		add_filter( 'tiled_gallery_content_width', array( $this, 'tiled_gallery_content_width' ) );
124
125
		if ( method_exists( $this, $method ) )
126
			echo $this->$method( $args, $instance );
127
128
		// Remove the stored $_instance_width, as it is no longer needed
129
		$this->_instance_width = null;
130
131
		// Remove the filter, so any Jetpack_Tiled_Gallery in a post is not affected
132
		remove_filter( 'tiled_gallery_content_width', array( $this, 'tiled_gallery_content_width' ) );
133
134
		echo "\n" . '</div>'; // .widget-gallery-$type
135
136
		echo "\n" . $after_widget;
137
	}
138
139
	/**
140
	 * Fetch the images attached to the gallery Widget
141
	 *
142
	 * @param array $instance The Widget instance for which you'd like attachments
143
	 * @return array Array of attachment objects for the Widget in $instance
144
	 */
145
	public function get_attachments( $instance ){
146
		$ids = explode( ',', $instance['ids'] );
147
148
		if ( isset( $instance['random'] ) && 'on' == $instance['random'] ) {
149
			shuffle( $ids );
150
		}
151
152
		$attachments_query = new WP_Query( array(
153
			'post__in'       => $ids,
154
			'post_status'    => 'inherit',
155
			'post_type'      => 'attachment',
156
			'post_mime_type' => 'image',
157
			'posts_per_page' => -1,
158
			'orderby'        => 'post__in',
159
		) );
160
161
		$attachments = $attachments_query->get_posts();
162
163
		wp_reset_postdata();
164
165
		return $attachments;
166
	}
167
168
	/**
169
	 * Generate HTML for a rectangular, tiled Widget
170
	 *
171
	 * @param array $args Display arguments including before_title, after_title, before_widget, and after_widget.
172
	 * @param array $instance The Widget instance to generate HTML for
173
	 * @return string String of HTML representing a rectangular gallery
174
	 */
175 View Code Duplication
	public function rectangular_widget( $args, $instance ) {
176
		if ( ! class_exists( 'Jetpack_Tiled_Gallery' )
177
			&& ! class_exists( 'Jetpack_Tiled_Gallery_Layout_Rectangular') ) {
178
			return;
179
		}
180
181
		$widget_tiled_gallery = new Jetpack_Tiled_Gallery();
182
		$widget_tiled_gallery->default_scripts_and_styles();
183
184
		$layout = new Jetpack_Tiled_Gallery_Layout_Rectangular( $instance['attachments'], $instance['link'], false, 3 );
185
		return $layout->HTML();
186
	}
187
188
	/**
189
	 * Generate HTML for a square (grid style) Widget
190
	 *
191
	 * @param array $args Display arguments including before_title, after_title, before_widget, and after_widget.
192
	 * @param array $instance The Widget instance to generate HTML for
193
	 * @return string String of HTML representing a square gallery
194
	 */
195 View Code Duplication
	public function square_widget( $args, $instance ) {
196
		if ( ! class_exists( 'Jetpack_Tiled_Gallery' )
197
			&& ! class_exists( 'Jetpack_Tiled_Gallery_Layout_Square') ) {
198
			return;
199
		}
200
201
		$widget_tiled_gallery = new Jetpack_Tiled_Gallery();
202
		$widget_tiled_gallery->default_scripts_and_styles();
203
204
		$layout = new Jetpack_Tiled_Gallery_Layout_Square( $instance['attachments'], $instance['link'], false, 3 );
205
		return $layout->HTML();
206
	}
207
208
	/**
209
	 * Generate HTML for a circular (grid style) Widget
210
	 *
211
	 * @param array $args Display arguments including before_title, after_title, before_widget, and after_widget.
212
	 * @param array $instance The Widget instance to generate HTML for
213
	 * @return string String of HTML representing a circular gallery
214
	 */
215 View Code Duplication
	public function circle_widget( $args, $instance ) {
216
		if ( ! class_exists( 'Jetpack_Tiled_Gallery' )
217
			&& ! class_exists( 'Jetpack_Tiled_Gallery_Layout_Circle') ) {
218
			return;
219
		}
220
221
		$widget_tiled_gallery = new Jetpack_Tiled_Gallery();
222
		$widget_tiled_gallery->default_scripts_and_styles();
223
224
		$layout = new Jetpack_Tiled_Gallery_Layout_Circle( $instance['attachments'], $instance['link'], false, 3 );
225
		return $layout->HTML();
226
	}
227
228
	/**
229
	 * Generate HTML for a slideshow Widget
230
	 *
231
	 * @param array $args Display arguments including before_title, after_title, before_widget, and after_widget.
232
	 * @param array $instance The Widget instance to generate HTML for
233
	 * @return string String of HTML representing a slideshow gallery
234
	 */
235
	public function slideshow_widget( $args, $instance ) {
236
		global $content_width;
237
238
		require_once plugin_dir_path( realpath( dirname( __FILE__ ) . '/../shortcodes/slideshow.php' ) ) . 'slideshow.php';
239
240
		if ( ! class_exists( 'Jetpack_Slideshow_Shortcode' ) )
241
			return;
242
243
		if ( count( $instance['attachments'] ) < 1 )
244
			return;
245
246
		$slideshow = new Jetpack_Slideshow_Shortcode();
247
248
		$slideshow->enqueue_scripts();
249
250
		$gallery_instance = "widget-" . $args['widget_id'];
251
252
		$gallery = array();
253
254
		foreach ( $instance['attachments'] as $attachment ) {
255
			$attachment_image_src = wp_get_attachment_image_src( $attachment->ID, 'full' );
256
			$attachment_image_src = $attachment_image_src[0]; // [url, width, height]
257
258
			$caption 	= wptexturize( strip_tags( $attachment->post_excerpt ) );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 2 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
259
260
			$gallery[] 	= (object) array(
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 2 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
261
				'src'     => (string) esc_url_raw( $attachment_image_src ),
262
				'id'      => (string) $attachment->ID,
263
				'caption' => (string) $caption,
264
			);
265
		}
266
267
		$max_width 	= intval( get_option( 'large_size_w' ) );
268
		$max_height = 175;
269
270
		if ( intval( $content_width ) > 0 )
271
			$max_width = min( intval( $content_width ), $max_width );
272
273
		$color = Jetpack_Options::get_option( 'slideshow_background_color', 'black' );
274
		$autostart = isset( $attr['autostart'] ) ? $attr['autostart'] : true;
0 ignored issues
show
Bug introduced by
The variable $attr seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
275
276
		$js_attr = array(
277
			'gallery'  => $gallery,
278
			'selector' => $gallery_instance,
279
			'width'    => $max_width,
280
			'height'   => $max_height,
281
			'trans'    => 'fade',
282
			'color'    => $color,
283
			'autostart' => $autostart,
284
		 );
285
286
		$html = $slideshow->slideshow_js( $js_attr );
287
288
		return $html;
289
	}
290
291
	/**
292
	 * tiled_gallery_content_width filter
293
	 *
294
	 * Used to adjust the content width of Jetpack_Tiled_Gallery's in sidebars
295
	 *
296
	 * $this->_instance_width is filtered in widget() and this filter is added then removed in widget()
297
	 *
298
	 * @param int $width int The original width value
299
	 * @return int The filtered width
300
	 */
301
	public function tiled_gallery_content_width( $width ) {
302
		return $this->_instance_width;
303
	}
304
305
	public function form( $instance ) {
306
		$defaults 		= $this->defaults();
307
		$allowed_values	= $this->allowed_values();
308
309
		$instance 		= wp_parse_args( (array) $instance, $defaults );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 3 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
310
311
		include dirname( __FILE__ ) . '/gallery/templates/form.php';
312
	}
313
314
	public function update( $new_instance, $old_instance ) {
315
		$instance = $this->sanitize( $new_instance );
316
317
		return $instance;
318
	}
319
320
	/**
321
	 * Sanitize the $instance's values to the set of allowed values. If a value is not acceptable,
322
	 * it is set to its default.
323
	 *
324
	 * Helps keep things nice and secure by whitelisting only allowed values
325
	 *
326
	 * @param array $instance The Widget instance to sanitize values for
327
	 * @return array $instance The Widget instance with values sanitized
328
	 */
329
	public function sanitize( $instance ) {
330
		$allowed_values = $this->allowed_values();
331
		$defaults 		= $this->defaults();
332
333
		foreach ( $instance as $key => $value ) {
334
			$value = trim( $value );
335
336
			if ( isset( $allowed_values[ $key ] ) && $allowed_values[ $key ] && ! array_key_exists( $value, $allowed_values[ $key ] ) ) {
337
				$instance[ $key ] = $defaults[ $key ];
338
			} else {
339
				$instance[ $key ] = sanitize_text_field( $value );
340
			}
341
		}
342
343
		return $instance;
344
	}
345
346
	/**
347
	 * Return a multi-dimensional array of allowed values (and their labels) for all widget form
348
	 * elements
349
	 *
350
	 * To allow all values on an input, omit it from the returned array
351
	 *
352
	 * @return array Array of allowed values for each option
353
	 */
354
	public function allowed_values() {
355
		$max_columns = 5;
356
357
		// Create an associative array of allowed column values. This just automates the generation of
358
		// column <option>s, from 1 to $max_columns
359
		$allowed_columns = array_combine( range( 1, $max_columns ), range( 1, $max_columns ) );
360
361
		return array(
362
			'type'	=> array(
363
				'rectangular'   => __( 'Tiles',        'jetpack' ),
364
				'square'        => __( 'Square Tiles', 'jetpack' ),
365
				'circle'        => __( 'Circles',      'jetpack' ),
366
				'slideshow'     => __( 'Slideshow',    'jetpack' ),
367
			),
368
			'columns'	=> $allowed_columns,
369
			'link'	=> array(
370
				'carousel'  => __( 'Carousel',         'jetpack' ),
371
				'post'      => __( 'Attachment Page',  'jetpack' ),
372
				'file'      => __( 'Media File',       'jetpack' ),
373
			)
374
		);
375
	}
376
377
	/**
378
	 * Return an associative array of default values
379
	 *
380
	 * These values are used in new widgets as well as when sanitizing input. If a given value is not allowed,
381
	 * as defined in allowed_values(), that input is set to the default value defined here.
382
	 *
383
	 * @return array Array of default values for the Widget's options
384
	 */
385
	public function defaults() {
386
		return array(
387
			'title'		=> '',
388
			'type'		=> 'rectangular',
389
			'ids'		=> '',
390
			'columns'	=> 3,
391
			'link'		=> 'carousel'
392
		);
393
	}
394
395
	public function enqueue_frontend_scripts() {
396
		wp_register_script( 'gallery-widget', plugins_url( '/gallery/js/gallery.js', __FILE__ ) );
397
398
		wp_enqueue_script( 'gallery-widget' );
399
	}
400
401
	public function enqueue_admin_scripts() {
402
		global $pagenow;
403
404
		if ( 'widgets.php' == $pagenow || 'customize.php' == $pagenow ) {
405
			wp_enqueue_media();
406
407
			wp_enqueue_script( 'gallery-widget-admin', plugins_url( '/gallery/js/admin.js', __FILE__ ), array(
408
					'media-models',
409
					'media-views'
410
				),
411
				'20150501'
412
			);
413
414
			$js_settings = array(
415
				'thumbSize' => self::THUMB_SIZE
416
			);
417
418
			wp_localize_script( 'gallery-widget-admin', '_wpGalleryWidgetAdminSettings', $js_settings );
419
			if( is_rtl() ) {
420
				wp_enqueue_style( 'gallery-widget-admin', plugins_url( '/gallery/css/rtl/admin-rtl.css', __FILE__ ) );
421
			} else {
422
				wp_enqueue_style( 'gallery-widget-admin', plugins_url( '/gallery/css/admin.css', __FILE__ ) );
423
			}
424
		}
425
	}
426
}
427
428
add_action( 'widgets_init', 'jetpack_gallery_widget_init' );
429
430
function jetpack_gallery_widget_init() {
431
	if ( ! method_exists( 'Jetpack', 'is_module_active' ) || Jetpack::is_module_active( 'tiled-gallery' ) )
432
		register_widget( 'Jetpack_Gallery_Widget' );
433
}
434