Completed
Push — add/crowdsignal-shortcode ( 65c42e...1b4a63 )
by Kuba
14:46 queued 06:22
created

Jetpack_Carousel::post_attachment_comment()   F

Complexity

Conditions 18
Paths 76

Size

Total Lines 110

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 18
nc 76
nop 0
dl 0
loc 110
rs 3.8933
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
/*
4
Plugin Name: Jetpack Carousel
5
Plugin URL: https://wordpress.com/
6
Description: Transform your standard image galleries into an immersive full-screen experience.
7
Version: 0.1
8
Author: Automattic
9
10
Released under the GPL v.2 license.
11
12
This program is distributed in the hope that it will be useful,
13
but WITHOUT ANY WARRANTY; without even the implied warranty of
14
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
GNU General Public License for more details.
16
*/
17
class Jetpack_Carousel {
18
19
	public $prebuilt_widths = array( 370, 700, 1000, 1200, 1400, 2000 );
20
21
	public $first_run = true;
22
23
	public $in_gallery = false;
24
25
	public $in_jetpack = true;
26
27
	public $single_image_gallery_enabled = false;
28
29
	public $single_image_gallery_enabled_media_file = false;
30
31
	function __construct() {
32
		add_action( 'init', array( $this, 'init' ) );
33
	}
34
35
	function init() {
36
		if ( $this->maybe_disable_jp_carousel() ) {
37
			return;
38
		}
39
40
		$this->in_jetpack = ( class_exists( 'Jetpack' ) && method_exists( 'Jetpack', 'enable_module_configurable' ) ) ? true : false;
41
42
		$this->single_image_gallery_enabled            = ! $this->maybe_disable_jp_carousel_single_images();
43
		$this->single_image_gallery_enabled_media_file = $this->maybe_enable_jp_carousel_single_images_media_file();
44
45
		if ( is_admin() ) {
46
			// Register the Carousel-related related settings
47
			add_action( 'admin_init', array( $this, 'register_settings' ), 5 );
48
			if ( ! $this->in_jetpack ) {
49
				if ( 0 == $this->test_1or0_option( get_option( 'carousel_enable_it' ), true ) ) {
50
					return; // Carousel disabled, abort early, but still register setting so user can switch it back on
51
				}
52
			}
53
			// If in admin, register the ajax endpoints.
54
			add_action( 'wp_ajax_get_attachment_comments', array( $this, 'get_attachment_comments' ) );
55
			add_action( 'wp_ajax_nopriv_get_attachment_comments', array( $this, 'get_attachment_comments' ) );
56
			add_action( 'wp_ajax_post_attachment_comment', array( $this, 'post_attachment_comment' ) );
57
			add_action( 'wp_ajax_nopriv_post_attachment_comment', array( $this, 'post_attachment_comment' ) );
58
		} else {
59
			if ( ! $this->in_jetpack ) {
60
				if ( 0 == $this->test_1or0_option( get_option( 'carousel_enable_it' ), true ) ) {
61
					return; // Carousel disabled, abort early
62
				}
63
			}
64
			// If on front-end, do the Carousel thang.
65
			/**
66
			 * Filter the array of default prebuilt widths used in Carousel.
67
			 *
68
			 * @module carousel
69
			 *
70
			 * @since 1.6.0
71
			 *
72
			 * @param array $this->prebuilt_widths Array of default widths.
73
			 */
74
			$this->prebuilt_widths = apply_filters( 'jp_carousel_widths', $this->prebuilt_widths );
75
			// below: load later than other callbacks hooked it (e.g. 3rd party plugins handling gallery shortcode)
76
			add_filter( 'post_gallery', array( $this, 'check_if_shortcode_processed_and_enqueue_assets' ), 1000, 2 );
77
			add_filter( 'post_gallery', array( $this, 'set_in_gallery' ), -1000 );
78
			add_filter( 'gallery_style', array( $this, 'add_data_to_container' ) );
79
			add_filter( 'wp_get_attachment_image_attributes', array( $this, 'add_data_to_images' ), 10, 2 );
80
			if ( $this->single_image_gallery_enabled ) {
81
				add_filter( 'the_content', array( $this, 'add_data_img_tags_and_enqueue_assets' ) );
82
			}
83
		}
84
85
		if ( $this->in_jetpack && method_exists( 'Jetpack', 'module_configuration_load' ) ) {
86
			Jetpack::enable_module_configurable( dirname( dirname( __FILE__ ) ) . '/carousel.php' );
87
			Jetpack::module_configuration_load( dirname( dirname( __FILE__ ) ) . '/carousel.php', array( $this, 'jetpack_configuration_load' ) );
88
		}
89
	}
90
91
	function maybe_disable_jp_carousel() {
92
		/**
93
		 * Allow third-party plugins or themes to disable Carousel.
94
		 *
95
		 * @module carousel
96
		 *
97
		 * @since 1.6.0
98
		 *
99
		 * @param bool false Should Carousel be disabled? Default to false.
100
		 */
101
		return apply_filters( 'jp_carousel_maybe_disable', false );
102
	}
103
104
	function maybe_disable_jp_carousel_single_images() {
105
		/**
106
		 * Allow third-party plugins or themes to disable Carousel for single images.
107
		 *
108
		 * @module carousel
109
		 *
110
		 * @since 4.5.0
111
		 *
112
		 * @param bool false Should Carousel be disabled for single images? Default to false.
113
		 */
114
		return apply_filters( 'jp_carousel_maybe_disable_single_images', false );
115
	}
116
117
	function maybe_enable_jp_carousel_single_images_media_file() {
118
		/**
119
		 * Allow third-party plugins or themes to enable Carousel
120
		 * for single images linking to 'Media File' (full size image).
121
		 *
122
		 * @module carousel
123
		 *
124
		 * @since 4.5.0
125
		 *
126
		 * @param bool false Should Carousel be enabled for single images linking to 'Media File'? Default to false.
127
		 */
128
		return apply_filters( 'jp_carousel_load_for_images_linked_to_file', false );
129
	}
130
131
	function jetpack_configuration_load() {
132
		wp_safe_redirect( admin_url( 'options-media.php#carousel_background_color' ) );
133
		exit;
134
	}
135
136
	function asset_version( $version ) {
137
		/**
138
		 * Filter the version string used when enqueuing Carousel assets.
139
		 *
140
		 * @module carousel
141
		 *
142
		 * @since 1.6.0
143
		 *
144
		 * @param string $version Asset version.
145
		 */
146
		return apply_filters( 'jp_carousel_asset_version', $version );
147
	}
148
149
	function display_bail_message( $output = '' ) {
150
		// Displays a message on top of gallery if carousel has bailed
151
		$message  = '<div class="jp-carousel-msg"><p>';
152
		$message .= __( 'Jetpack\'s Carousel has been disabled, because another plugin or your theme is overriding the [gallery] shortcode.', 'jetpack' );
153
		$message .= '</p></div>';
154
		// put before gallery output
155
		$output = $message . $output;
156
		return $output;
157
	}
158
159
	function check_if_shortcode_processed_and_enqueue_assets( $output ) {
160
		if (
161
			! empty( $output ) &&
162
			/**
163
			 * Allow third-party plugins or themes to force-enable Carousel.
164
			 *
165
			 * @module carousel
166
			 *
167
			 * @since 1.9.0
168
			 *
169
			 * @param bool false Should we force enable Carousel? Default to false.
170
			 */
171
			! apply_filters( 'jp_carousel_force_enable', false )
172
		) {
173
			// Bail because someone is overriding the [gallery] shortcode.
174
			remove_filter( 'gallery_style', array( $this, 'add_data_to_container' ) );
175
			remove_filter( 'wp_get_attachment_image_attributes', array( $this, 'add_data_to_images' ) );
176
			remove_filter( 'the_content', array( $this, 'add_data_img_tags_and_enqueue_assets' ) );
177
			// Display message that carousel has bailed, if user is super_admin, and if we're not on WordPress.com.
178
			if (
179
				is_super_admin() &&
180
				! ( defined( 'IS_WPCOM' ) && IS_WPCOM )
181
			) {
182
				add_filter( 'post_gallery', array( $this, 'display_bail_message' ) );
183
			}
184
			return $output;
185
		}
186
187
		/**
188
		 * Fires when thumbnails are shown in Carousel.
189
		 *
190
		 * @module carousel
191
		 *
192
		 * @since 1.6.0
193
		 **/
194
		do_action( 'jp_carousel_thumbnails_shown' );
195
196
		$this->enqueue_assets();
197
198
		return $output;
199
	}
200
201
	function enqueue_assets() {
202
		if ( $this->first_run ) {
203
			wp_enqueue_script(
204
				'jetpack-carousel',
205
				Jetpack::get_file_url_for_environment(
206
					'_inc/build/carousel/jetpack-carousel.min.js',
207
					'modules/carousel/jetpack-carousel.js'
208
				),
209
				array( 'jquery.spin' ),
210
				$this->asset_version( '20170209' ),
211
				true
212
			);
213
214
			// Note: using  home_url() instead of admin_url() for ajaxurl to be sure  to get same domain on wpcom when using mapped domains (also works on self-hosted)
215
			// Also: not hardcoding path since there is no guarantee site is running on site root in self-hosted context.
216
			$is_logged_in         = is_user_logged_in();
217
			$current_user         = wp_get_current_user();
218
			$comment_registration = intval( get_option( 'comment_registration' ) );
219
			$require_name_email   = intval( get_option( 'require_name_email' ) );
220
			$localize_strings     = array(
221
				'widths'                          => $this->prebuilt_widths,
222
				'is_logged_in'                    => $is_logged_in,
223
				'lang'                            => strtolower( substr( get_locale(), 0, 2 ) ),
224
				'ajaxurl'                         => set_url_scheme( admin_url( 'admin-ajax.php' ) ),
225
				'nonce'                           => wp_create_nonce( 'carousel_nonce' ),
226
				'display_exif'                    => $this->test_1or0_option( Jetpack_Options::get_option_and_ensure_autoload( 'carousel_display_exif', true ) ),
227
				'display_geo'                     => $this->test_1or0_option( Jetpack_Options::get_option_and_ensure_autoload( 'carousel_display_geo', true ) ),
228
				'single_image_gallery'            => $this->single_image_gallery_enabled,
229
				'single_image_gallery_media_file' => $this->single_image_gallery_enabled_media_file,
230
				'background_color'                => $this->carousel_background_color_sanitize( Jetpack_Options::get_option_and_ensure_autoload( 'carousel_background_color', '' ) ),
231
				'comment'                         => __( 'Comment', 'jetpack' ),
232
				'post_comment'                    => __( 'Post Comment', 'jetpack' ),
233
				'write_comment'                   => __( 'Write a Comment...', 'jetpack' ),
234
				'loading_comments'                => __( 'Loading Comments...', 'jetpack' ),
235
				'download_original'               => sprintf( __( 'View full size <span class="photo-size">%1$s<span class="photo-size-times">&times;</span>%2$s</span>', 'jetpack' ), '{0}', '{1}' ),
236
				'no_comment_text'                 => __( 'Please be sure to submit some text with your comment.', 'jetpack' ),
237
				'no_comment_email'                => __( 'Please provide an email address to comment.', 'jetpack' ),
238
				'no_comment_author'               => __( 'Please provide your name to comment.', 'jetpack' ),
239
				'comment_post_error'              => __( 'Sorry, but there was an error posting your comment. Please try again later.', 'jetpack' ),
240
				'comment_approved'                => __( 'Your comment was approved.', 'jetpack' ),
241
				'comment_unapproved'              => __( 'Your comment is in moderation.', 'jetpack' ),
242
				'camera'                          => __( 'Camera', 'jetpack' ),
243
				'aperture'                        => __( 'Aperture', 'jetpack' ),
244
				'shutter_speed'                   => __( 'Shutter Speed', 'jetpack' ),
245
				'focal_length'                    => __( 'Focal Length', 'jetpack' ),
246
				'copyright'                       => __( 'Copyright', 'jetpack' ),
247
				'comment_registration'            => $comment_registration,
248
				'require_name_email'              => $require_name_email,
249
				/** This action is documented in core/src/wp-includes/link-template.php */
250
				'login_url'                       => wp_login_url( apply_filters( 'the_permalink', get_permalink() ) ),
251
				'blog_id'                         => (int) get_current_blog_id(),
252
				'meta_data'                       => array( 'camera', 'aperture', 'shutter_speed', 'focal_length', 'copyright' ),
253
			);
254
255
			if ( ! isset( $localize_strings['jetpack_comments_iframe_src'] ) || empty( $localize_strings['jetpack_comments_iframe_src'] ) ) {
256
				// We're not using Comments after all, so fallback to standard local comments.
257
258
				if ( $is_logged_in ) {
259
					$localize_strings['local_comments_commenting_as'] = '<p id="jp-carousel-commenting-as">' . sprintf( __( 'Commenting as %s', 'jetpack' ), $current_user->data->display_name ) . '</p>';
260
				} else {
261
					if ( $comment_registration ) {
262
						$localize_strings['local_comments_commenting_as'] = '<p id="jp-carousel-commenting-as">' . __( 'You must be <a href="#" class="jp-carousel-comment-login">logged in</a> to post a comment.', 'jetpack' ) . '</p>';
263
					} else {
264
						$required = ( $require_name_email ) ? __( '%s (Required)', 'jetpack' ) : '%s';
265
						$localize_strings['local_comments_commenting_as'] = ''
266
							. '<fieldset><label for="email">' . sprintf( $required, __( 'Email', 'jetpack' ) ) . '</label> '
267
							. '<input type="text" name="email" class="jp-carousel-comment-form-field jp-carousel-comment-form-text-field" id="jp-carousel-comment-form-email-field" /></fieldset>'
268
							. '<fieldset><label for="author">' . sprintf( $required, __( 'Name', 'jetpack' ) ) . '</label> '
269
							. '<input type="text" name="author" class="jp-carousel-comment-form-field jp-carousel-comment-form-text-field" id="jp-carousel-comment-form-author-field" /></fieldset>'
270
							. '<fieldset><label for="url">' . __( 'Website', 'jetpack' ) . '</label> '
271
							. '<input type="text" name="url" class="jp-carousel-comment-form-field jp-carousel-comment-form-text-field" id="jp-carousel-comment-form-url-field" /></fieldset>';
272
					}
273
				}
274
			}
275
276
			/**
277
			 * Handle WP stats for images in full-screen.
278
			 * Build string with tracking info.
279
			 */
280
281
			/**
282
			 * Filter if Jetpack should enable stats collection on carousel views
283
			 *
284
			 * @module carousel
285
			 *
286
			 * @since 4.3.2
287
			 *
288
			 * @param bool Enable Jetpack Carousel stat collection. Default false.
289
			 */
290
			if ( apply_filters( 'jetpack_enable_carousel_stats', false ) && in_array( 'stats', Jetpack::get_active_modules() ) && ! Jetpack::is_development_mode() ) {
291
				$localize_strings['stats'] = 'blog=' . Jetpack_Options::get_option( 'id' ) . '&host=' . parse_url( get_option( 'home' ), PHP_URL_HOST ) . '&v=ext&j=' . JETPACK__API_VERSION . ':' . JETPACK__VERSION;
292
293
				// Set the stats as empty if user is logged in but logged-in users shouldn't be tracked.
294 View Code Duplication
				if ( is_user_logged_in() && function_exists( 'stats_get_options' ) ) {
295
					$stats_options        = stats_get_options();
296
					$track_loggedin_users = isset( $stats_options['reg_users'] ) ? (bool) $stats_options['reg_users'] : false;
297
298
					if ( ! $track_loggedin_users ) {
299
						$localize_strings['stats'] = '';
300
					}
301
				}
302
			}
303
304
			/**
305
			 * Filter the strings passed to the Carousel's js file.
306
			 *
307
			 * @module carousel
308
			 *
309
			 * @since 1.6.0
310
			 *
311
			 * @param array $localize_strings Array of strings passed to the Jetpack js file.
312
			 */
313
			$localize_strings = apply_filters( 'jp_carousel_localize_strings', $localize_strings );
314
			wp_localize_script( 'jetpack-carousel', 'jetpackCarouselStrings', $localize_strings );
315
			wp_enqueue_style( 'jetpack-carousel', plugins_url( 'jetpack-carousel.css', __FILE__ ), array(), $this->asset_version( '20120629' ) );
316
			wp_style_add_data( 'jetpack-carousel', 'rtl', 'replace' );
317
318
			wp_register_style( 'jetpack-carousel-ie8fix', plugins_url( 'jetpack-carousel-ie8fix.css', __FILE__ ), array(), $this->asset_version( '20121024' ) );
319
			$GLOBALS['wp_styles']->add_data( 'jetpack-carousel-ie8fix', 'conditional', 'lte IE 8' );
320
			wp_enqueue_style( 'jetpack-carousel-ie8fix' );
321
322
			/**
323
			 * Fires after carousel assets are enqueued for the first time.
324
			 * Allows for adding additional assets to the carousel page.
325
			 *
326
			 * @module carousel
327
			 *
328
			 * @since 1.6.0
329
			 *
330
			 * @param bool $first_run First load if Carousel on the page.
331
			 * @param array $localized_strings Array of strings passed to the Jetpack js file.
332
			 */
333
			do_action( 'jp_carousel_enqueue_assets', $this->first_run, $localize_strings );
334
335
			$this->first_run = false;
336
		}
337
	}
338
339
	function set_in_gallery( $output ) {
340
		$this->in_gallery = true;
341
		return $output;
342
	}
343
344
	/**
345
	 * Adds data-* attributes required by carousel to img tags in post HTML
346
	 * content. To be used by 'the_content' filter.
347
	 *
348
	 * @see add_data_to_images()
349
	 * @see wp_make_content_images_responsive() in wp-includes/media.php
350
	 *
351
	 * @param string $content HTML content of the post
352
	 * @return string Modified HTML content of the post
353
	 */
354
	function add_data_img_tags_and_enqueue_assets( $content ) {
355
		if ( ! preg_match_all( '/<img [^>]+>/', $content, $matches ) ) {
356
			return $content;
357
		}
358
		$selected_images = array();
359
360
		foreach ( $matches[0] as $image_html ) {
361
			if ( preg_match( '/wp-image-([0-9]+)/i', $image_html, $class_id ) &&
362
				( $attachment_id = absint( $class_id[1] ) ) ) {
363
				/*
364
				 * If exactly the same image tag is used more than once, overwrite it.
365
				 * All identical tags will be replaced later with 'str_replace()'.
366
				 */
367
				$selected_images[ $attachment_id  ] = $image_html;
368
			}
369
		}
370
371
		$find    = array();
372
		$replace = array();
373
		if ( empty( $selected_images ) ) {
374
			return $content;
375
		}
376
377
		$attachments = get_posts(
378
			array(
379
				'include'          => array_keys( $selected_images ),
380
				'post_type'        => 'any',
381
				'post_status'      => 'any',
382
				'suppress_filters' => false,
383
			)
384
		);
385
386
		foreach ( $attachments as $attachment ) {
387
			$image_html = $selected_images[ $attachment->ID ];
388
389
			$attributes      = $this->add_data_to_images( array(), $attachment );
390
			$attributes_html = '';
391
			foreach ( $attributes as $k => $v ) {
392
				$attributes_html .= esc_attr( $k ) . '="' . esc_attr( $v ) . '" ';
393
			}
394
395
			$find[]    = $image_html;
396
			$replace[] = str_replace( '<img ', "<img $attributes_html", $image_html );
397
		}
398
399
		$content = str_replace( $find, $replace, $content );
400
		$this->enqueue_assets();
401
		return $content;
402
	}
403
404
	function add_data_to_images( $attr, $attachment = null ) {
405
		$attachment_id = intval( $attachment->ID );
406
		if ( ! wp_attachment_is_image( $attachment_id ) ) {
407
			return $attr;
408
		}
409
410
		$orig_file       = wp_get_attachment_image_src( $attachment_id, 'full' );
411
		$orig_file       = isset( $orig_file[0] ) ? $orig_file[0] : wp_get_attachment_url( $attachment_id );
412
		$meta            = wp_get_attachment_metadata( $attachment_id );
413
		$size            = isset( $meta['width'] ) ? intval( $meta['width'] ) . ',' . intval( $meta['height'] ) : '';
414
		$img_meta        = ( ! empty( $meta['image_meta'] ) ) ? (array) $meta['image_meta'] : array();
415
		$comments_opened = intval( comments_open( $attachment_id ) );
416
417
		 /*
418
		 * Note: Cannot generate a filename from the width and height wp_get_attachment_image_src() returns because
419
		 * it takes the $content_width global variable themes can set in consideration, therefore returning sizes
420
		 * which when used to generate a filename will likely result in a 404 on the image.
421
		 * $content_width has no filter we could temporarily de-register, run wp_get_attachment_image_src(), then
422
		 * re-register. So using returned file URL instead, which we can define the sizes from through filename
423
		 * parsing in the JS, as this is a failsafe file reference.
424
		 *
425
		 * EG with Twenty Eleven activated:
426
		 * array(4) { [0]=> string(82) "http://vanillawpinstall.blah/wp-content/uploads/2012/06/IMG_3534-1024x764.jpg" [1]=> int(584) [2]=> int(435) [3]=> bool(true) }
427
		 *
428
		 * EG with Twenty Ten activated:
429
		 * array(4) { [0]=> string(82) "http://vanillawpinstall.blah/wp-content/uploads/2012/06/IMG_3534-1024x764.jpg" [1]=> int(640) [2]=> int(477) [3]=> bool(true) }
430
		 */
431
432
		$medium_file_info = wp_get_attachment_image_src( $attachment_id, 'medium' );
433
		$medium_file      = isset( $medium_file_info[0] ) ? $medium_file_info[0] : '';
434
435
		$large_file_info = wp_get_attachment_image_src( $attachment_id, 'large' );
436
		$large_file      = isset( $large_file_info[0] ) ? $large_file_info[0] : '';
437
438
		$attachment       = get_post( $attachment_id );
439
		$attachment_title = wptexturize( $attachment->post_title );
440
		$attachment_desc  = wpautop( wptexturize( $attachment->post_content ) );
441
		// Not yet providing geo-data, need to "fuzzify" for privacy
442 View Code Duplication
		if ( ! empty( $img_meta ) ) {
443
			foreach ( $img_meta as $k => $v ) {
444
				if ( 'latitude' == $k || 'longitude' == $k ) {
445
					unset( $img_meta[ $k ] );
446
				}
447
			}
448
		}
449
450
		// See https://github.com/Automattic/jetpack/issues/2765
451
		if ( isset( $img_meta['keywords'] ) ) {
452
			unset( $img_meta['keywords'] );
453
		}
454
455
		$img_meta = json_encode( array_map( 'strval', array_filter( $img_meta, 'is_scalar' ) ) );
456
457
		$attr['data-attachment-id']     = $attachment_id;
458
		$attr['data-permalink']         = esc_attr( get_permalink( $attachment->ID ) );
459
		$attr['data-orig-file']         = esc_attr( $orig_file );
460
		$attr['data-orig-size']         = $size;
461
		$attr['data-comments-opened']   = $comments_opened;
462
		$attr['data-image-meta']        = esc_attr( $img_meta );
463
		$attr['data-image-title']       = esc_attr( htmlspecialchars( $attachment_title ) );
464
		$attr['data-image-description'] = esc_attr( htmlspecialchars( $attachment_desc ) );
465
		$attr['data-medium-file']       = esc_attr( $medium_file );
466
		$attr['data-large-file']        = esc_attr( $large_file );
467
468
		return $attr;
469
	}
470
471
	function add_data_to_container( $html ) {
472
		global $post;
473
474
		if ( isset( $post ) ) {
475
			$blog_id = (int) get_current_blog_id();
476
477
			$extra_data = array(
478
				'data-carousel-extra' => array(
479
					'blog_id'   => $blog_id,
480
					'permalink' => get_permalink( $post->ID ),
481
				),
482
			);
483
484
			/**
485
			 * Filter the data added to the Gallery container.
486
			 *
487
			 * @module carousel
488
			 *
489
			 * @since 1.6.0
490
			 *
491
			 * @param array $extra_data Array of data about the site and the post.
492
			 */
493
			$extra_data = apply_filters( 'jp_carousel_add_data_to_container', $extra_data );
494
			foreach ( (array) $extra_data as $data_key => $data_values ) {
495
				$html = str_replace( '<div ', '<div ' . esc_attr( $data_key ) . "='" . json_encode( $data_values ) . "' ", $html );
496
			}
497
		}
498
499
		return $html;
500
	}
501
502
	function get_attachment_comments() {
503
		if ( ! headers_sent() ) {
504
			header( 'Content-type: text/javascript' );
505
		}
506
507
		/**
508
		 * Allows for the checking of privileges of the blog user before comments
509
		 * are packaged as JSON and sent back from the get_attachment_comments
510
		 * AJAX endpoint
511
		 *
512
		 * @module carousel
513
		 *
514
		 * @since 1.6.0
515
		 */
516
		do_action( 'jp_carousel_check_blog_user_privileges' );
517
518
		$attachment_id = ( isset( $_REQUEST['id'] ) ) ? (int) $_REQUEST['id'] : 0;
519
		$offset        = ( isset( $_REQUEST['offset'] ) ) ? (int) $_REQUEST['offset'] : 0;
520
521
		if ( ! $attachment_id ) {
522
			echo json_encode( __( 'Missing attachment ID.', 'jetpack' ) );
523
			die();
524
		}
525
526
		if ( $offset < 1 ) {
527
			$offset = 0;
528
		}
529
530
		$comments = get_comments(
531
			array(
532
				'status'  => 'approve',
533
				'order'   => ( 'asc' == get_option( 'comment_order' ) ) ? 'ASC' : 'DESC',
534
				'number'  => 10,
535
				'offset'  => $offset,
536
				'post_id' => $attachment_id,
537
			)
538
		);
539
540
		$out = array();
541
542
		// Can't just send the results, they contain the commenter's email address.
543
		foreach ( $comments as $comment ) {
544
			$avatar = get_avatar( $comment->comment_author_email, 64 );
545
			if ( ! $avatar ) {
546
				$avatar = '';
547
			}
548
			$out[] = array(
549
				'id'              => $comment->comment_ID,
550
				'parent_id'       => $comment->comment_parent,
551
				'author_markup'   => get_comment_author_link( $comment->comment_ID ),
552
				'gravatar_markup' => $avatar,
553
				'date_gmt'        => $comment->comment_date_gmt,
554
				'content'         => wpautop( $comment->comment_content ),
555
			);
556
		}
557
558
		die( json_encode( $out ) );
559
	}
560
561
	function post_attachment_comment() {
562
		if ( ! headers_sent() ) {
563
			header( 'Content-type: text/javascript' );
564
		}
565
566
		if ( empty( $_POST['nonce'] ) || ! wp_verify_nonce( $_POST['nonce'], 'carousel_nonce' ) ) {
567
			die( json_encode( array( 'error' => __( 'Nonce verification failed.', 'jetpack' ) ) ) );
568
		}
569
570
		$_blog_id = (int) $_POST['blog_id'];
571
		$_post_id = (int) $_POST['id'];
572
		$comment  = $_POST['comment'];
573
574
		if ( empty( $_blog_id ) ) {
575
			die( json_encode( array( 'error' => __( 'Missing target blog ID.', 'jetpack' ) ) ) );
576
		}
577
578
		if ( empty( $_post_id ) ) {
579
			die( json_encode( array( 'error' => __( 'Missing target post ID.', 'jetpack' ) ) ) );
580
		}
581
582
		if ( empty( $comment ) ) {
583
			die( json_encode( array( 'error' => __( 'No comment text was submitted.', 'jetpack' ) ) ) );
584
		}
585
586
		// Used in context like NewDash
587
		$switched = false;
588
		if ( is_multisite() && $_blog_id != get_current_blog_id() ) {
589
			switch_to_blog( $_blog_id );
590
			$switched = true;
591
		}
592
593
		/** This action is documented in modules/carousel/jetpack-carousel.php */
594
		do_action( 'jp_carousel_check_blog_user_privileges' );
595
596
		if ( ! comments_open( $_post_id ) ) {
597
			die( json_encode( array( 'error' => __( 'Comments on this post are closed.', 'jetpack' ) ) ) );
598
		}
599
600
		if ( is_user_logged_in() ) {
601
			$user         = wp_get_current_user();
602
			$user_id      = $user->ID;
603
			$display_name = $user->display_name;
604
			$email        = $user->user_email;
605
			$url          = $user->user_url;
606
607
			if ( empty( $user_id ) ) {
608
				die( json_encode( array( 'error' => __( 'Sorry, but we could not authenticate your request.', 'jetpack' ) ) ) );
609
			}
610
		} else {
611
			$user_id      = 0;
612
			$display_name = $_POST['author'];
613
			$email        = $_POST['email'];
614
			$url          = $_POST['url'];
615
616
			if ( get_option( 'require_name_email' ) ) {
617
				if ( empty( $display_name ) ) {
618
					die( json_encode( array( 'error' => __( 'Please provide your name.', 'jetpack' ) ) ) );
619
				}
620
621
				if ( empty( $email ) ) {
622
					die( json_encode( array( 'error' => __( 'Please provide an email address.', 'jetpack' ) ) ) );
623
				}
624
625
				if ( ! is_email( $email ) ) {
626
					die( json_encode( array( 'error' => __( 'Please provide a valid email address.', 'jetpack' ) ) ) );
627
				}
628
			}
629
		}
630
631
		$comment_data = array(
632
			'comment_content'      => $comment,
633
			'comment_post_ID'      => $_post_id,
634
			'comment_author'       => $display_name,
635
			'comment_author_email' => $email,
636
			'comment_author_url'   => $url,
637
			'comment_approved'     => 0,
638
			'comment_type'         => '',
639
		);
640
641
		if ( ! empty( $user_id ) ) {
642
			$comment_data['user_id'] = $user_id;
643
		}
644
645
		// Note: wp_new_comment() sanitizes and validates the values (too).
646
		$comment_id = wp_new_comment( $comment_data );
647
648
		/**
649
		 * Fires before adding a new comment to the database via the get_attachment_comments ajax endpoint.
650
		 *
651
		 * @module carousel
652
		 *
653
		 * @since 1.6.0
654
		 */
655
		do_action( 'jp_carousel_post_attachment_comment' );
656
		$comment_status = wp_get_comment_status( $comment_id );
657
658
		if ( true == $switched ) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
659
			restore_current_blog();
660
		}
661
662
		die(
663
			json_encode(
664
				array(
665
					'comment_id'     => $comment_id,
666
					'comment_status' => $comment_status,
667
				)
668
			)
669
		);
670
	}
671
672
	function register_settings() {
673
		add_settings_section( 'carousel_section', __( 'Image Gallery Carousel', 'jetpack' ), array( $this, 'carousel_section_callback' ), 'media' );
674
675
		if ( ! $this->in_jetpack ) {
676
			add_settings_field( 'carousel_enable_it', __( 'Enable carousel', 'jetpack' ), array( $this, 'carousel_enable_it_callback' ), 'media', 'carousel_section' );
677
			register_setting( 'media', 'carousel_enable_it', array( $this, 'carousel_enable_it_sanitize' ) );
678
		}
679
680
		add_settings_field( 'carousel_background_color', __( 'Background color', 'jetpack' ), array( $this, 'carousel_background_color_callback' ), 'media', 'carousel_section' );
681
		register_setting( 'media', 'carousel_background_color', array( $this, 'carousel_background_color_sanitize' ) );
682
683
		add_settings_field( 'carousel_display_exif', __( 'Metadata', 'jetpack' ), array( $this, 'carousel_display_exif_callback' ), 'media', 'carousel_section' );
684
		register_setting( 'media', 'carousel_display_exif', array( $this, 'carousel_display_exif_sanitize' ) );
685
686
		// No geo setting yet, need to "fuzzify" data first, for privacy
687
		// add_settings_field('carousel_display_geo', __( 'Geolocation', 'jetpack' ), array( $this, 'carousel_display_geo_callback' ), 'media', 'carousel_section' );
688
		// register_setting( 'media', 'carousel_display_geo', array( $this, 'carousel_display_geo_sanitize' ) );
689
	}
690
691
	// Fulfill the settings section callback requirement by returning nothing
692
	function carousel_section_callback() {
693
		return;
694
	}
695
696
	function test_1or0_option( $value, $default_to_1 = true ) {
697
		if ( true == $default_to_1 ) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
698
			// Binary false (===) of $value means it has not yet been set, in which case we do want to default sites to 1
699
			if ( false === $value ) {
700
				$value = 1;
701
			}
702
		}
703
		return ( 1 == $value ) ? 1 : 0;
704
	}
705
706
	function sanitize_1or0_option( $value ) {
707
		return ( 1 == $value ) ? 1 : 0;
708
	}
709
710
	function settings_checkbox( $name, $label_text, $extra_text = '', $default_to_checked = true ) {
711
		if ( empty( $name ) ) {
712
			return;
713
		}
714
		$option = $this->test_1or0_option( get_option( $name ), $default_to_checked );
715
		echo '<fieldset>';
716
		echo '<input type="checkbox" name="' . esc_attr( $name ) . '" id="' . esc_attr( $name ) . '" value="1" ';
717
		checked( '1', $option );
718
		echo '/> <label for="' . esc_attr( $name ) . '">' . $label_text . '</label>';
719
		if ( ! empty( $extra_text ) ) {
720
			echo '<p class="description">' . $extra_text . '</p>';
721
		}
722
		echo '</fieldset>';
723
	}
724
725
	function settings_select( $name, $values, $extra_text = '' ) {
726
		if ( empty( $name ) || ! is_array( $values ) || empty( $values ) ) {
727
			return;
728
		}
729
		$option = get_option( $name );
730
		echo '<fieldset>';
731
		echo '<select name="' . esc_attr( $name ) . '" id="' . esc_attr( $name ) . '">';
732
		foreach ( $values as $key => $value ) {
733
			echo '<option value="' . esc_attr( $key ) . '" ';
734
			selected( $key, $option );
735
			echo '>' . esc_html( $value ) . '</option>';
736
		}
737
		echo '</select>';
738
		if ( ! empty( $extra_text ) ) {
739
			echo '<p class="description">' . $extra_text . '</p>';
740
		}
741
		echo '</fieldset>';
742
	}
743
744
	function carousel_display_exif_callback() {
745
		$this->settings_checkbox( 'carousel_display_exif', __( 'Show photo metadata (<a href="http://en.wikipedia.org/wiki/Exchangeable_image_file_format" rel="noopener noreferrer" target="_blank">Exif</a>) in carousel, when available.', 'jetpack' ) );
746
	}
747
748
	function carousel_display_exif_sanitize( $value ) {
749
		return $this->sanitize_1or0_option( $value );
750
	}
751
752
	function carousel_display_geo_callback() {
753
		$this->settings_checkbox( 'carousel_display_geo', __( 'Show map of photo location in carousel, when available.', 'jetpack' ) );
754
	}
755
756
	function carousel_display_geo_sanitize( $value ) {
757
		return $this->sanitize_1or0_option( $value );
758
	}
759
760 View Code Duplication
	function carousel_background_color_callback() {
761
		$this->settings_select(
762
			'carousel_background_color', array(
763
				'black' => __( 'Black', 'jetpack' ),
764
				'white' => __( 'White', 'jetpack' ),
765
			)
766
		);
767
	}
768
769
	function carousel_background_color_sanitize( $value ) {
770
		return ( 'white' == $value ) ? 'white' : 'black';
771
	}
772
773
	function carousel_enable_it_callback() {
774
		$this->settings_checkbox( 'carousel_enable_it', __( 'Display images in full-size carousel slideshow.', 'jetpack' ) );
775
	}
776
777
	function carousel_enable_it_sanitize( $value ) {
778
		return $this->sanitize_1or0_option( $value );
779
	}
780
}
781
782
new Jetpack_Carousel;
783