Completed
Push — refactor/subscriptions ( 2c6651 )
by Jeremy
23:44 queued 13:28
created

Widget::__construct()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 4
nop 0
dl 0
loc 29
rs 8.8337
c 0
b 0
f 0
1
<?php
2
/**
3
 * Display the Subscriptions Widget
4
 * on WordPress.com or in Jetpack
5
 *
6
 * @package Jetpack
7
 */
8
9
namespace Automattic\Jetpack\Subscriptions;
10
11
use Automattic\Jetpack\Subscriptions\Helpers;
12
use Blog_Subscription_Widget;
13
use WP_Widget;
14
15
if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
16
	class_alias( 'Automattic\Jetpack\Subscriptions\Widget', 'Blog_Subscription_Widget' );
17
}
18
19
/**
20
 * Register our Widget.
21
 */
22
function register() {
23
	register_widget( Widget::class );
24
}
25
add_action( 'widgets_init', __NAMESPACE__ . '\register' );
26
27
/**
28
 * Display a widget allowing one to subscribe to your site.
29
 * Supports both Jetpack and WordPress.com environments.
30
 */
31
class Widget extends WP_Widget {
32
	/**
33
	 * Unique number for the widget.
34
	 *
35
	 * @var int
36
	 */
37
	private static $instance_count = 0;
38
39
	/**
40
	 * When printing the submit button, what tags are allowed
41
	 *
42
	 * @var array
43
	 */
44
	private static $allowed_html_tags_for_submit_button = array( 'br' => array() );
45
46
	/**
47
	 * Use this variable when printing the message after submitting an email in subscription widgets
48
	 *
49
	 * @var array what tags are allowed
50
	 */
51
	public static $allowed_html_tags_for_message = array(
52
		'a'  => array(
53
			'href'   => array(),
54
			'title'  => array(),
55
			'rel'    => array(),
56
			'target' => array(),
57
		),
58
		'br' => array(),
59
		'p'  => array(),
60
	);
61
62
	/**
63
	 * Constructor
64
	 */
65
	public function __construct() {
66
		$widget_ops = array(
67
			'classname'                   => 'widget_blog_subscription jetpack_subscription_widget',
68
			'description'                 => __( 'Add an email signup form to allow people to subscribe to your blog.', 'jetpack' ),
69
			'customize_selective_refresh' => true,
70
		);
71
72
		$name = Helpers::is_jetpack() ?
73
			/** This filter is documented in modules/widgets/facebook-likebox.php */
74
			apply_filters( 'jetpack_widget_name', __( 'Blog Subscriptions', 'jetpack' ) )
75
			: __( 'Follow Blog', 'jetpack' );
76
77
		parent::__construct(
78
			'blog_subscription',
79
			$name,
80
			$widget_ops
81
		);
82
83
		if (
84
			Helpers::is_jetpack()
85
			&& (
86
				is_active_widget( false, false, $this->id_base )
87
				|| is_active_widget( false, false, 'monster' )
88
				|| is_customize_preview()
89
			)
90
		) {
91
			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_style' ) );
92
		}
93
	}
94
95
	/**
96
	 * Enqueue the form's CSS.
97
	 *
98
	 * @since 4.5.0
99
	 */
100
	public function enqueue_style() {
101
		wp_enqueue_style(
102
			'jetpack-subscriptions',
103
			plugins_url( 'subscriptions.css', __FILE__ ),
104
			array(),
105
			JETPACK__VERSION
106
		);
107
	}
108
109
	/**
110
	 * The default args for rendering a subscription form.
111
	 *
112
	 * @return array
113
	 */
114
	private static function defaults() {
115
		$defaults = array(
116
			'show_subscribers_total'     => true,
117
			'show_only_email_and_button' => false,
118
		);
119
120
		if ( Helpers::is_jetpack() ) {
121
			$defaults['title']                 = esc_html__( 'Subscribe to Blog via Email', 'jetpack' );
122
			$defaults['subscribe_text']        = esc_html__( 'Enter your email address to subscribe to this blog and receive notifications of new posts by email.', 'jetpack' );
123
			$defaults['subscribe_placeholder'] = esc_html__( 'Email Address', 'jetpack' );
124
			$defaults['subscribe_button']      = esc_html__( 'Subscribe', 'jetpack' );
125
			$defaults['success_message']       = esc_html__( "Success! An email was just sent to confirm your subscription. Please find the email now and click 'Confirm Follow' to start subscribing.", 'jetpack' );
126
		}
127
128
		if ( Helpers::is_wpcom() ) {
129
			// phpcs:disable WordPress.WP.I18n.MissingArgDomain -- These strings are only used on WordPress.com.
130
			$defaults['title']               = __( 'Follow Blog via Email' );
131
			$defaults['title_following']     = __( 'You are following this blog' );
132
			$defaults['subscribe_text']      = __( 'Enter your email address to follow this blog and receive notifications of new posts by email.' );
133
			$defaults['subscribe_button']    = __( 'Follow' );
134
			$defaults['subscribe_logged_in'] = __( 'Click to follow this blog and receive notifications of new posts by email.' );
135
			// phpcs:enable WordPress.WP.I18n.MissingArgDomain
136
		}
137
138
		return $defaults;
139
	}
140
141
	/**
142
	 * Renders the widget's options form in wp-admin.
143
	 *
144
	 * @param array $instance Widget options.
145
	 */
146
	public function form( $instance ) {
147
		$instance               = wp_parse_args( (array) $instance, $this->defaults() );
0 ignored issues
show
Documentation introduced by
$this->defaults() 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...
148
		$show_subscribers_total = checked( $instance['show_subscribers_total'], true, false );
149
150
		if ( Helpers::is_jetpack() ) {
151
			$this->jetpack_widget_admin_form( $instance, $show_subscribers_total );
152
		}
153
154
		if ( Helpers::is_wpcom() ) {
155
			$this->wpcom_widget_admin_form( $instance, $show_subscribers_total );
156
		}
157
	}
158
159
	/**
160
	 * Render the form in the Jetpack environment.
161
	 *
162
	 * @param array  $instance               Widget options.
163
	 * @param string $show_subscribers_total checked attribute or empty string.
164
	 */
165
	private function jetpack_widget_admin_form( $instance, $show_subscribers_total ) {
166
		$title                 = stripslashes( $instance['title'] );
167
		$subscribe_text        = stripslashes( $instance['subscribe_text'] );
168
		$subscribe_placeholder = stripslashes( $instance['subscribe_placeholder'] );
169
		$subscribe_button      = stripslashes( $instance['subscribe_button'] );
170
		$success_message       = stripslashes( $instance['success_message'] );
171
		$subs_fetch            = Helpers::fetch_subscriber_count();
172
		if ( 'failed' === $subs_fetch['status'] ) {
173
			printf(
174
				'<div class="error inline"><p>%s: %s</p></div>',
175
				esc_html( $subs_fetch['code'] ),
176
				esc_html( $subs_fetch['message'] )
177
			);
178
		}
179
		$subscribers_total = number_format_i18n( $subs_fetch['value'] );
180
181
		?>
182
		<p>
183
			<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">
184
				<?php esc_html_e( 'Widget title:', 'jetpack' ); ?>
185
				<input
186
					type="text"
187
					class="widefat"
188
					id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
189
					name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"
190
					value="<?php echo esc_attr( $title ); ?>"
191
				/>
192
			</label>
193
		</p>
194
		<p>
195
			<label for="<?php echo esc_attr( $this->get_field_id( 'subscribe_text' ) ); ?>">
196
				<?php esc_html_e( 'Optional text to display to your readers:', 'jetpack' ); ?>
197
				<textarea
198
					class="widefat"
199
					id="<?php echo esc_attr( $this->get_field_id( 'subscribe_text' ) ); ?>"
200
					name="<?php echo esc_attr( $this->get_field_name( 'subscribe_text' ) ); ?>"
201
					rows="3"
202
				><?php echo esc_html( $subscribe_text ); ?></textarea>
203
			</label>
204
		</p>
205
		<p>
206
			<label for="<?php echo esc_attr( $this->get_field_id( 'subscribe_placeholder' ) ); ?>">
207
				<?php esc_html_e( 'Subscribe Placeholder:', 'jetpack' ); ?>
208
				<input
209
					type="text"
210
					class="widefat"
211
					id="<?php echo esc_attr( $this->get_field_id( 'subscribe_placeholder' ) ); ?>"
212
					name="<?php echo esc_attr( $this->get_field_name( 'subscribe_placeholder' ) ); ?>"
213
					value="<?php echo esc_attr( $subscribe_placeholder ); ?>"
214
				/>
215
			</label>
216
		</p>
217
		<p>
218
			<label for="<?php echo esc_attr( $this->get_field_id( 'subscribe_button' ) ); ?>">
219
				<?php esc_html_e( 'Subscribe Button:', 'jetpack' ); ?>
220
				<input
221
					type="text"
222
					class="widefat"
223
					id="<?php echo esc_attr( $this->get_field_id( 'subscribe_button' ) ); ?>"
224
					name="<?php echo esc_attr( $this->get_field_name( 'subscribe_button' ) ); ?>"
225
					value="<?php echo esc_attr( $subscribe_button ); ?>"
226
				/>
227
			</label>
228
		</p>
229
		<p>
230
			<label for="<?php echo esc_attr( $this->get_field_id( 'success_message' ) ); ?>">
231
				<?php esc_html_e( 'Success Message Text:', 'jetpack' ); ?>
232
				<textarea
233
					class="widefat"
234
					id="<?php echo esc_attr( $this->get_field_id( 'success_message' ) ); ?>"
235
					name="<?php echo esc_attr( $this->get_field_name( 'success_message' ) ); ?>"
236
					rows="5"
237
				><?php echo esc_html( $success_message ); ?></textarea>
238
			</label>
239
		</p>
240
		<p>
241
			<label for="<?php echo esc_attr( $this->get_field_id( 'show_subscribers_total' ) ); ?>">
242
				<input
243
					type="checkbox"
244
					id="<?php echo esc_attr( $this->get_field_id( 'show_subscribers_total' ) ); ?>"
245
					name="<?php echo esc_attr( $this->get_field_name( 'show_subscribers_total' ) ); ?>"
246
					value="1"
247
					<?php echo $show_subscribers_total; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
248
				/>
249
				<?php
250
				echo esc_html(
251
					sprintf(
252
						/* translators: placeholder is a number */
253
						_n(
254
							'Show total number of subscribers? (%s subscriber)',
255
							'Show total number of subscribers? (%s subscribers)',
256
							$subscribers_total,
257
							'jetpack'
258
						),
259
						$subscribers_total
260
					)
261
				);
262
				?>
263
			</label>
264
		</p>
265
		<?php
266
	}
267
268
	/**
269
	 * Render the form in the WordPress.com environment.
270
	 *
271
	 * @param array  $instance               Widget options.
272
	 * @param string $show_subscribers_total checked attribute or empty string.
273
	 */
274
	private function wpcom_widget_admin_form( $instance, $show_subscribers_total ) {
275
		$title               = esc_attr( stripslashes( $instance['title'] ) );
276
		$title_following     = esc_attr( stripslashes( $instance['title_following'] ) );
277
		$subscribe_text      = esc_attr( stripslashes( $instance['subscribe_text'] ) );
278
		$subscribe_logged_in = esc_attr( stripslashes( $instance['subscribe_logged_in'] ) );
279
		$subscribe_button    = esc_attr( stripslashes( $instance['subscribe_button'] ) );
280
		$subscribers_total   = Helpers::fetch_subscriber_count();
281
282
		// phpcs:disable WordPress.WP.I18n.MissingArgDomain -- These strings are only used on WordPress.com.
283
		?>
284
		<p>
285
			<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>">
286
				<?php esc_html_e( 'Widget title for non-followers:' ); ?>
287
				<input
288
					type="text"
289
					class="widefat"
290
					id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"
291
					name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>"
292
					value="<?php echo esc_attr( $title ); ?>"
293
				/>
294
			</label>
295
		</p>
296
		<p>
297
			<label for="<?php echo esc_attr( $this->get_field_id( 'title_following' ) ); ?>">
298
				<?php esc_html_e( 'Widget title for followers:' ); ?>
299
				<input
300
					type="text"
301
					class="widefat"
302
					id="<?php echo esc_attr( $this->get_field_id( 'title_following' ) ); ?>"
303
					name="<?php echo esc_attr( $this->get_field_name( 'title_following' ) ); ?>"
304
					value="<?php echo esc_attr( $title_following ); ?>"
305
				/>
306
			</label>
307
		</p>
308
		<p>
309
			<label for="<?php echo esc_attr( $this->get_field_id( 'subscribe_logged_in' ) ); ?>">
310
				<?php esc_html_e( 'Optional text to display to logged in WordPress.com users:' ); ?>
311
				<textarea
312
					type="text"
313
					style="width: 95%"
314
					id="<?php echo esc_attr( $this->get_field_id( 'subscribe_logged_in' ) ); ?>"
315
					name="<?php echo esc_attr( $this->get_field_name( 'subscribe_logged_in' ) ); ?>"
316
				>
317
					<?php echo esc_html( $subscribe_logged_in ); ?>
318
				</textarea>
319
			</label>
320
		</p>
321
		<p>
322
			<label for="<?php echo esc_attr( $this->get_field_id( 'subscribe_text' ) ); ?>">
323
				<?php esc_html_e( 'Optional text to display to non-WordPress.com users:' ); ?>
324
				<textarea
325
					type="text"
326
					style="width: 95%"
327
					id="<?php echo esc_attr( $this->get_field_id( 'subscribe_text' ) ); ?>"
328
					name="<?php echo esc_attr( $this->get_field_name( 'subscribe_text' ) ); ?>"
329
				>
330
					<?php echo esc_html( $subscribe_text ); ?>
331
				</textarea>
332
			</label>
333
		</p>
334
		<p>
335
			<label for="<?php echo esc_attr( $this->get_field_id( 'subscribe_button' ) ); ?>">
336
				<?php esc_html_e( 'Follow Button Text:' ); ?>
337
				<input
338
					type="text"
339
					class="widefat"
340
					id="<?php echo esc_attr( $this->get_field_id( 'subscribe_button' ) ); ?>"
341
					name="<?php echo esc_attr( $this->get_field_name( 'subscribe_button' ) ); ?>"
342
					value="<?php echo esc_attr( $subscribe_button ); ?>"
343
				/>
344
			</label>
345
		</p>
346
		<p>
347
			<label for="<?php echo esc_attr( $this->get_field_id( 'show_subscribers_total' ) ); ?>">
348
				<input
349
					type="checkbox"
350
					id="<?php echo esc_attr( $this->get_field_id( 'show_subscribers_total' ) ); ?>"
351
					name="<?php echo esc_attr( $this->get_field_name( 'show_subscribers_total' ) ); ?>"
352
					value="1"
353
					<?php echo $show_subscribers_total; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
354
				/>
355
				<?php
356
				echo esc_html(
357
					sprintf(
358
						/* translators: placeholder is a number. */
359
						_n(
360
							'Show total number of followers? (%s follower)',
361
							'Show total number of followers? (%s followers)',
362
							$subscribers_total
363
						),
364
						number_format_i18n( $subscribers_total )
365
					)
366
				);
367
				?>
368
			</label>
369
		</p>
370
		<?php
371
		// phpcs:enable WordPress.WP.I18n.MissingArgDomain
372
	}
373
374
	/**
375
	 * Updates a particular instance of a widget when someone saves it in wp-admin.
376
	 *
377
	 * @param array $new_instance Old widget options.
378
	 * @param array $old_instance New widget options.
379
	 *
380
	 * @return array
381
	 */
382
	public function update( $new_instance, $old_instance ) {
383
		$instance = $old_instance;
384
385
		if ( Helpers::is_jetpack() ) {
386
			$instance['title']                 = wp_kses( stripslashes( $new_instance['title'] ), array() );
387
			$instance['subscribe_placeholder'] = wp_kses( stripslashes( $new_instance['subscribe_placeholder'] ), array() );
388
			$instance['subscribe_button']      = wp_kses( stripslashes( $new_instance['subscribe_button'] ), array() );
389
			$instance['success_message']       = wp_kses( stripslashes( $new_instance['success_message'] ), array() );
390
		}
391
392
		if ( Helpers::is_wpcom() ) {
393
			$instance['title']               = wp_strip_all_tags( stripslashes( $new_instance['title'] ) );
394
			$instance['title_following']     = wp_strip_all_tags( stripslashes( $new_instance['title_following'] ) );
395
			$instance['subscribe_logged_in'] = wp_filter_post_kses( stripslashes( $new_instance['subscribe_logged_in'] ) );
396
			$instance['subscribe_button']    = wp_strip_all_tags( stripslashes( $new_instance['subscribe_button'] ) );
397
		}
398
399
		$instance['show_subscribers_total']     = isset( $new_instance['show_subscribers_total'] ) && $new_instance['show_subscribers_total'];
400
		$instance['show_only_email_and_button'] = isset( $new_instance['show_only_email_and_button'] ) && $new_instance['show_only_email_and_button'];
401
		$instance['subscribe_text']             = wp_filter_post_kses( stripslashes( $new_instance['subscribe_text'] ) );
402
403
		return $instance;
404
	}
405
406
	/**
407
	 * Renders a full widget either within the context of WordPress widget, or in response to a shortcode.
408
	 *
409
	 * @param array $args Display arguments including 'before_title', 'after_title', 'before_widget', and 'after_widget'.
410
	 * @param array $instance The settings for the particular instance of the widget.
411
	 */
412
	public function widget( $args, $instance ) {
413
		if (
414
			Helpers::is_jetpack()
415
			/** This filter is documented in modules/contact-form/grunion-contact-form.php */
416
			&& false === apply_filters( 'jetpack_auto_fill_logged_in_user', false )
417
		) {
418
			$subscribe_email = '';
419
			$stats_action    = 'jetpack_subscriptions';
420
		} else {
421
			$current_user = wp_get_current_user();
422
			if ( ! empty( $current_user->user_email ) ) {
423
				$subscribe_email = esc_attr( $current_user->user_email );
424
			} else {
425
				$subscribe_email = '';
426
			}
427
			$stats_action = 'follow_blog';
428
		}
429
430
		/** This action is documented in modules/widgets/gravatar-profile.php */
431
		do_action( 'jetpack_stats_extra', 'widget_view', $stats_action );
432
433
		$after_widget  = isset( $args['after_widget'] ) ? $args['after_widget'] : '';
434
		$before_widget = isset( $args['before_widget'] ) ? $args['before_widget'] : '';
435
		$instance      = wp_parse_args( (array) $instance, $this->defaults() );
0 ignored issues
show
Documentation introduced by
$this->defaults() 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...
436
437
		echo $before_widget; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
438
439
		self::$instance_count ++;
440
441
		$this->title( $args, $instance );
442
443
		$this->status_messages( $instance );
444
445
		if ( Helpers::is_wpcom() && Helpers::is_current_user_subscribed() ) {
446
			$this->form_already_subscribed( $instance );
447
		} else {
448
			$this->subscription_form( $args, $instance, $subscribe_email );
449
		}
450
451
		echo "\n";
452
		echo $after_widget; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
453
	}
454
455
	/**
456
	 * Widget title.
457
	 * If show_only_email_and_button is true, we will not show a title.
458
	 *
459
	 * @param array $args Display arguments including 'before_title', 'after_title', 'before_widget', and 'after_widget'.
460
	 * @param array $instance The settings for the particular instance of the widget.
461
	 */
462
	private function title( $args, $instance ) {
463
		$show_only_email_and_button = $instance['show_only_email_and_button'];
464
		$before_title               = isset( $args['before_title'] ) ? $args['before_title'] : '';
465
		$after_title                = isset( $args['after_title'] ) ? $args['after_title'] : '';
466
		$title_label_id             = sprintf(
467
			'subscribe-field%1$s',
468
			( absint( self::$instance_count ) > 1
469
				? '-' . absint( self::$instance_count )
470
				: ''
471
			)
472
		);
473
474
		if ( Helpers::is_jetpack() && empty( $show_only_email_and_button ) ) {
475
			$title = esc_attr( $instance['title'] );
476
		} elseif ( Helpers::is_wpcom() && empty( $show_only_email_and_button ) ) {
477
			if ( Helpers::is_current_user_subscribed() ) {
478
				$title = ( ! empty( $instance['title_following'] ) )
479
					? sprintf(
480
						'<label for="%1$s>%2$s</label>',
481
						$title_label_id,
482
						esc_attr( $instance['title_following'] )
483
					)
484
					: '';
485
			} else {
486
				$title = ( ! empty( $instance['title'] ) )
487
					? sprintf(
488
						'<label for="%1$s>%2$s</label>',
489
						$title_label_id,
490
						esc_attr( $instance['title'] )
491
					)
492
					: '';
493
			}
494
		} else {
495
			$title = '';
496
		}
497
498
		echo $before_title; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
499
		echo $title; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped earlier, can contain label HTML tags.
500
		echo $after_title; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
501
		echo "\n";
502
	}
503
504
	/**
505
	 * Prints the subscription block's status messages after someone has attempted to subscribe.
506
	 * Either a success message or an error message.
507
	 *
508
	 * @param array $instance The settings for the particular instance of the widget.
509
	 */
510
	private function status_messages( $instance ) {
511
		if (
512
			Helpers::is_jetpack()
513
			&& isset( $_GET['subscribe'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
514
		) {
515
			$status_message = $this->jetpack_status_messages( $instance );
516
			printf(
517
				'<%1$s class="%2$s">%3$s</%1$s>',
518
				( 'success' === $status_message['status'] ? 'div' : 'p' ),
519
				esc_attr( $status_message['status'] ),
520
				wp_kses(
521
					$status_message['message'],
522
					self::$allowed_html_tags_for_message
523
				)
524
			);
525
		}
526
527
		if (
528
			Helpers::is_wpcom()
529
			&& Helpers::has_status_message()
530
		) {
531
			global $themecolors;
532
533
			$status_message = $this->wpcom_status_messages();
534
			$style          = sprintf(
535
				'background-color: #%1$s; border: 1px solid #%2$s; color: #%3$s; padding-left: 5px; padding-right: 5px; margin-bottom: 10px;',
536
				$themecolors['bg'],
537
				$themecolors['border'],
538
				$themecolors['text']
539
			);
540
541
			printf(
542
				'<div style="%1$s">%2$s</div>',
543
				esc_attr( $style ),
544
				wp_kses(
545
					$status_message,
546
					self::$allowed_html_tags_for_message
547
				)
548
			);
549
		}
550
	}
551
552
	/**
553
	 * Prints the subscription block's status messages for Jetpack.
554
	 *
555
	 * @param array $instance The settings for the particular instance of the widget.
556
	 *
557
	 * @return array $status_message Array of info about the message. Status and message.
558
	 */
559
	private function jetpack_status_messages( $instance ) {
560
		$success_message   = isset( $instance['success_message'] ) ? stripslashes( $instance['success_message'] ) : '';
561
		$subscribers_total = Helpers::fetch_subscriber_count();
562
563
		/*
564
		 * Defaults.
565
		 */
566
		$status  = 'success';
0 ignored issues
show
Unused Code introduced by
$status is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
567
		$message = '';
0 ignored issues
show
Unused Code introduced by
$message is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
568
569
		switch ( $_GET['subscribe'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
570
			case 'invalid_email':
571
				$status  = 'error';
572
				$message = esc_html__( 'The email you entered was invalid. Please check and try again.', 'jetpack' );
573
				break;
574 View Code Duplication
			case 'opted_out':
575
				$status  = 'error';
576
				$message = sprintf(
577
					/* translators: 1: Link to Subscription Management page https://subscribe.wordpress.com/, 2: Description of this link */
578
					__( 'The email address has opted out of subscription emails. <br /> You can manage your preferences at <a href="%1$s" title="%2$s" target="_blank" rel="noopener noreferrer">subscribe.wordpress.com</a>', 'jetpack' ),
579
					'https://subscribe.wordpress.com/',
580
					esc_attr__( 'Manage your email preferences.', 'jetpack' )
581
				);
582
				break;
583 View Code Duplication
			case 'already':
584
				$status  = 'error';
585
				$message = sprintf(
586
					/* translators: 1: Link to Subscription Management page https://subscribe.wordpress.com/, 2: Description of this link */
587
					__( 'You have already subscribed to this site. Please check your inbox. <br /> You can manage your preferences at <a href="%1$s" title="%2$s" target="_blank" rel="noopener noreferrer">subscribe.wordpress.com</a>', 'jetpack' ),
588
					'https://subscribe.wordpress.com/',
589
					esc_attr__( 'Manage your email preferences.', 'jetpack' )
590
				);
591
				break;
592 View Code Duplication
			case 'many_pending_subs':
593
				$status  = 'error';
594
				$message = sprintf(
595
					/* translators: 1: Link to Subscription Management page https://subscribe.wordpress.com/, 2: Description of this link */
596
					__( 'You already have several pending email subscriptions. <br /> Approve or delete a few subscriptions at <a href="%1$s" title="%2$s" target="_blank" rel="noopener noreferrer">subscribe.wordpress.com</a> before continuing.', 'jetpack' ),
597
					'https://subscribe.wordpress.com/',
598
					esc_attr__( 'Manage your email preferences.', 'jetpack' )
599
				);
600
				break;
601 View Code Duplication
			case 'pending':
602
				$status  = 'error';
603
				$message = sprintf(
604
					/* translators: 1: Link to Subscription Management page https://subscribe.wordpress.com/, 2: Description of this link */
605
					__( 'You subscribed this site before but you have not clicked the confirmation link yet. Please check your inbox. <br /> Otherwise, you can manage your preferences at <a href="%1$s" title="%2$s" target="_blank" rel="noopener noreferrer">subscribe.wordpress.com</a>.', 'jetpack' ),
606
					'https://subscribe.wordpress.com/',
607
					esc_attr__( 'Manage your email preferences.', 'jetpack' )
608
				);
609
				break;
610
			case 'success':
611
				$status  = 'success';
612
				$message = wpautop(
613
					str_replace(
614
						'[total-subscribers]',
615
						number_format_i18n( $subscribers_total['value'] ),
616
						$success_message
617
					)
618
				);
619
				break;
620
			default:
621
				$status  = 'error';
622
				$message = esc_html__( 'There was an error when subscribing. Please try again.', 'jetpack' );
623
				break;
624
		}
625
626
		return array(
627
			'status'  => $status,
628
			'message' => $message,
629
		);
630
	}
631
632
	/**
633
	 * Prints the subscription block's status messages for WordPress.com.
634
	 *
635
	 * @return string $message Status message. Can contain HTML tags.
636
	 */
637
	private function wpcom_status_messages() {
638
		// Message is empty by default.
639
		$message = '';
640
641
		// phpcs:disable WordPress.WP.I18n.MissingArgDomain -- These strings are only used on WordPress.com.
642
		switch ( $_GET['blogsub'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
643
			case 'confirming':
644
				$message = sprintf(
645
					/* translators: placeholder is a link to a contact form. */
646
					__( 'Thanks for subscribing! You’ll get an email with a link to confirm your subscription. If you don’t get it, please <a href="%1$s" target="_blank" rel="noopener noreferrer">contact us</a>.' ),
647
					'https://wordpress.com/support/contact/'
648
				);
649
				break;
650
			case 'blocked':
651
				$message = esc_html__( 'Subscriptions have been blocked for this email address.' );
652
				break;
653
			case 'flooded':
654
				$message = sprintf(
655
					/* translators: placeholder is a link to our subscription management tool. */
656
					__( 'You already have several pending email subscriptions. Approve or delete a few through your <a href="%1$s" target="_blank" rel="noopener noreferrer">Subscription Manager</a> before attempting to subscribe to more blogs.' ),
657
					'https://subscribe.wordpress.com/'
658
				);
659
				break;
660
			case 'spammed':
661
				$message = sprintf(
662
					/* translators: placeholder is a link to our subscription management tool. */
663
					__( 'Because there are many pending subscriptions for this email address, we have blocked the subscription. Please <a href="%1$s" target="_blank" rel="noopener noreferrer">activate or delete</a> pending subscriptions before attempting to subscribe.' ),
664
					'https://subscribe.wordpress.com/'
665
				);
666
				break;
667
			case 'subscribed':
668
				$message = esc_html__( 'You are already subscribed to this site.' );
669
				break;
670
			case 'pending':
671
				$message = sprintf(
672
					/* translators: placeholder is a link to a contact form. */
673
					__( 'You have a pending subscription already; we just sent you another email. Click the link or <a href="%1$s" target="_blank" rel="noopener noreferrer">contact us</a> if you don’t receive it.' ),
674
					'https://wordpress.com/support/contact/'
675
				);
676
				break;
677
			case 'confirmed':
678
				$message = esc_html__( 'Congrats, you’re subscribed! You’ll get an email with the details of your subscription and an unsubscribe link.' );
679
				break;
680
		}
681
		// phpcs:enable WordPress.WP.I18n.MissingArgDomain
682
683
		return $message;
684
	}
685
686
	/**
687
	 * Renders a message to folks who are already subscribed.
688
	 * Only on WordPress.com.
689
	 *
690
	 * @param array $instance The settings for the particular instance of the widget.
691
	 */
692
	private function form_already_subscribed( $instance ) {
693
		$subscribers_total = Helpers::fetch_subscriber_count();
694
		$edit_subs_url     = 'https://wordpress.com/following/edit/';
695
		if ( function_exists( 'localized_wpcom_url' ) ) {
696
			$edit_subs_url = localized_wpcom_url( 'https://wordpress.com/following/edit/', get_user_locale() );
697
		}
698
		$show_subscribers_total = (bool) $instance['show_subscribers_total'];
699
700
		// phpcs:disable WordPress.WP.I18n.MissingArgDomain -- These strings are only used on WordPress.com.
701
		if ( $show_subscribers_total && $subscribers_total > 1 ) {
702
			$subscribers_not_me = $subscribers_total - 1;
703
			$message            = sprintf(
704
				/* translators: 1: number of folks following the blog 2: Subscription management URL */
705
				_n(
706
					'<p>You are following this blog, along with %1$s other amazing person (<a href="%2$s" target="_blank" rel="noopener noreferrer">manage</a>).</p>',
707
					'<p>You are following this blog, along with %1$s other amazing people (<a href="%2$s" target="_blank" rel="noopener noreferrer">manage</a>).</p>',
708
					$subscribers_not_me
709
				),
710
				number_format_i18n( $subscribers_not_me ),
711
				esc_url( $edit_subs_url )
712
			);
713
		} else {
714
			$message = sprintf(
715
				/* translators: placeholder is a subscription management URL */
716
				__( '<p>You are following this blog (<a href="%s" target="_blank" rel="noopener noreferrer">manage</a>).</p>' ),
717
				esc_url( $edit_subs_url )
718
			);
719
		}
720
		// phpcs:enable WordPress.WP.I18n.MissingArgDomain
721
722
		echo wp_kses(
723
			$message,
724
			self::$allowed_html_tags_for_message
725
		);
726
	}
727
728
	/**
729
	 * Renders a form allowing folks to subscribe to the blog.
730
	 *
731
	 * @param array  $args            Display arguments including 'before_title', 'after_title', 'before_widget', and 'after_widget'.
732
	 * @param array  $instance        The settings for the particular instance of the widget.
733
	 * @param string $subscribe_email The email to use to prefill the form.
734
	 */
735
	private function subscription_form( $args, $instance, $subscribe_email ) {
736
		$widget_id = ! empty( $args['widget_id'] )
737
			? esc_attr( $args['widget_id'] )
738
			: wp_rand( 450, 550 );
739
740
		if ( Helpers::is_wpcom() && ! Helpers::has_status_message() ) {
741
			$this->wpcom_subscription_form( $instance, $widget_id );
742
		}
743
744
		if ( Helpers::is_jetpack() ) {
745
			$this->jetpack_subscription_form( $instance, $subscribe_email, $widget_id );
746
		}
747
	}
748
749
	/**
750
	 * Render the form on the frontend of Jetpack sites.
751
	 *
752
	 * @param array  $instance        The settings for the particular instance of the widget.
753
	 * @param string $subscribe_email The email to use to prefill the form.
754
	 * @param string $widget_id       Unique Widget ID.
755
	 */
756
	private function jetpack_subscription_form( $instance, $subscribe_email, $widget_id ) {
757
		/**
758
		 * Filter the subscription form's ID prefix.
759
		 *
760
		 * @module subscriptions
761
		 *
762
		 * @since 2.7.0
763
		 *
764
		 * @param string subscribe-field Subscription form field prefix.
765
		 * @param int    $widget_id      Widget ID.
766
		 */
767
		$subscribe_field_id = apply_filters( 'subscribe_field_id', 'subscribe-field', $widget_id );
768
		$subscribers_total  = Helpers::fetch_subscriber_count();
769
		?>
770
		<form action="#" method="post" accept-charset="utf-8" id="subscribe-blog-<?php echo esc_attr( $widget_id ); ?>">
771
			<?php
772
			if (
773
				empty( $instance['show_only_email_and_button'] )
774
				&& ( ! isset( $_GET['subscribe'] ) || 'success' !== $_GET['subscribe'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
775
			) {
776
				printf(
777
					'<div id="subscribe-text">%1$s</div>',
778
					wp_kses(
779
						wpautop(
780
							str_replace(
781
								'[total-subscribers]',
782
								number_format_i18n( $subscribers_total['value'] ),
783
								$instance['subscribe_text']
784
							)
785
						),
786
						self::$allowed_html_tags_for_message
787
					)
788
				);
789
			}
790
791
			if ( $instance['show_subscribers_total'] && 0 < $subscribers_total['value'] ) {
792
				echo esc_html(
793
					sprintf( /* translators: %s: number of folks following the blog */
794
						_n(
795
							'Join %s other subscriber',
796
							'Join %s other subscribers',
797
							$subscribers_total['value'],
798
							'jetpack'
799
						),
800
						number_format_i18n( $subscribers_total['value'] )
801
					)
802
				);
803
			}
804
805
			if ( ! isset( $_GET['subscribe'] ) || 'success' !== $_GET['subscribe'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
806
				echo '<p id="subscribe-email">';
807
808
				printf(
809
					'<label id="jetpack-subscribe-label" class="screen-reader-text" for="%1$s">%2$s</label>',
810
					esc_attr( $subscribe_field_id ) . '-' . esc_attr( $widget_id ),
811
					! empty( $instance['subscribe_placeholder'] )
812
						? esc_html( $instance['subscribe_placeholder'] )
813
						: esc_html__( 'Email Address:', 'jetpack' )
814
				);
815
816
				printf(
817
					'<input
818
						type="email"
819
						name="email"
820
						required="required"
821
						class="required"
822
						value="%1$s"
823
						id="%2$s"
824
						placeholder="%3$s"
825
					/>
826
					',
827
					esc_attr( $subscribe_email ),
828
					esc_attr( $subscribe_field_id ) . '-' . esc_attr( $widget_id ),
829
					! empty( $instance['subscribe_placeholder'] )
830
						? esc_attr( $instance['subscribe_placeholder'] )
831
						: ''
832
				);
833
834
				echo '</p>';
835
836
				// Submit button.
837
				$this->form_submit_button( $widget_id, $instance );
838
			}
839
			?>
840
		</form>
841
		<?php
842
	}
843
844
	/**
845
	 * Render the form on the frontend of WordPress.com sites.
846
	 *
847
	 * @param array  $instance        The settings for the particular instance of the widget.
848
	 * @param string $widget_id       Unique Widget ID.
849
	 */
850
	private function wpcom_subscription_form( $instance, $widget_id ) {
851
		$url                 = defined( 'SUBSCRIBE_BLOG_URL' ) ? SUBSCRIBE_BLOG_URL : '';
852
		$instance_unique_id  = self::$instance_count > 1 ? '-' . self::$instance_count : '';
853
		$subscribers_total   = Helpers::fetch_subscriber_count();
854
		$display_subscribers = (bool) $instance['show_subscribers_total'] && 0 < $subscribers_total
855
			? sprintf(
856
				/* translators: %s: number of folks following the blog */
857
				_n( // phpcs:ignore WordPress.WP.I18n.MissingArgDomain
858
					'Join %s other follower',
859
					'Join %s other followers',
860
					$subscribers_total
861
				),
862
				number_format_i18n( $subscribers_total )
863
			)
864
			: '';
865
		?>
866
		<form
867
			action="<?php echo esc_url( $url ); ?>"
868
			method="post"
869
			accept-charset="utf-8"
870
			id="<?php echo esc_attr( 'subscribe-blog' . $instance_unique_id ); ?>"
871
		>
872
			<?php
873
874
			if ( is_user_logged_in() ) {
875
				if (
876
					empty( $instance['show_only_email_and_button'] )
877
					&& ! empty( $instance['subscribe_logged_in'] )
878
				) {
879
					echo wp_kses(
880
						wpautop( $instance['subscribe_logged_in'] ),
881
						self::$allowed_html_tags_for_message
882
					);
883
				}
884
				echo esc_html( $display_subscribers );
885
			} else {
886
				if ( empty( $instance['show_only_email_and_button'] ) ) {
887
					echo wp_kses(
888
						wpautop( $instance['subscribe_text'] ),
889
						self::$allowed_html_tags_for_message
890
					);
891
				}
892
				echo esc_html( $display_subscribers );
893
894
				echo '<p>';
895
896
				printf(
897
					'<input
898
						type="text"
899
						name="email"
900
						style="width: 95%; padding: 1px 10px"
901
						placeholder="%1$s"
902
						value=""
903
						id="%2$s"
904
					/>',
905
					esc_attr__( 'Enter your email address', 'jetpack' ),
906
					esc_attr( 'subscribe-field' . $instance_unique_id )
907
				);
908
909
				echo '</p>';
910
			}
911
912
			// Submit button.
913
			$this->form_submit_button( $widget_id, $instance );
914
915
			?>
916
917
		</form>
918
		<?php
919
	}
920
921
	/**
922
	 * Submit a Subscription form.
923
	 *
924
	 * @param string $widget_id Unique Widget ID.
925
	 * @param array  $instance  The settings for the particular instance of the widget.
926
	 */
927
	private function form_submit_button( $widget_id, $instance ) {
928
		$referer          = ( is_ssl() ? 'https' : 'http' ) . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
929
		$source           = 'widget';
930
		$subscribe_button = ! empty( $instance['submit_button_text'] )
931
			? $instance['submit_button_text']
932
			: $instance['subscribe_button'];
933
934
		if ( Helpers::is_wpcom() ) {
935
			global $current_blog;
936
			$blog_id = $current_blog->blog_id;
937
		} else {
938
			$blog_id = get_current_blog_id();
939
		}
940
941
		?>
942
		<p id="subscribe-submit">
943
			<input type="hidden" name="action" value="subscribe"/>
944
			<?php if ( Helpers::is_wpcom() ) { ?>
945
			<input type="hidden" name="blog_id" value="<?php echo absint( $blog_id ); ?>"/>
946
			<?php } ?>
947
			<input type="hidden" name="source" value="<?php echo esc_url( $referer ); ?>"/>
948
			<input type="hidden" name="sub-type" value="<?php echo esc_url( $source ); ?>"/>
949
			<input type="hidden" name="redirect_fragment" value="<?php echo esc_attr( $widget_id ); ?>"/>
950
			<?php
951
			if ( is_user_logged_in() || Helpers::is_wpcom() ) {
952
				wp_nonce_field( 'blogsub_subscribe_' . absint( $blog_id ) . '_wpnonce', false );
953
			}
954
			?>
955
			<button
956
				type="submit"
957
				<?php if ( ! empty( $instance['submit_button_classes'] ) ) { ?>
958
					class="<?php echo esc_attr( $instance['submit_button_classes'] ); ?>"
959
				<?php } ?>
960
				<?php if ( ! empty( $instance['submit_button_styles'] ) ) { ?>
961
					style="<?php echo esc_attr( $instance['submit_button_styles'] ); ?>"
962
				<?php } ?>
963
				<?php if ( Helpers::is_jetpack() ) { ?>
964
					name="jetpack_subscriptions_widget"
965
				<?php } ?>
966
			>
967
			<?php
968
				echo wp_kses(
969
					$subscribe_button,
970
					self::$allowed_html_tags_for_submit_button
971
				);
972
			?>
973
			</button>
974
		</p>
975
		<?php
976
	}
977
}
978