Completed
Push — add/react-videopress-settings ( 2ec3d2...3e14aa )
by
unknown
211:11 queued 203:41
created

Jetpack_Subscriptions::widget_submit()   D

Complexity

Conditions 14
Paths 194

Size

Total Lines 76
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 48
nc 194
nop 0
dl 0
loc 76
rs 4.8883
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
 * Module Name: Subscriptions
4
 * Module Description: Notify your readers of new posts and comments by email.
5
 * Jumpstart Description: Give visitors two easy subscription options — while commenting, or via a separate email subscription widget you can display.
6
 * Sort Order: 9
7
 * Recommendation Order: 8
8
 * First Introduced: 1.2
9
 * Requires Connection: Yes
10
 * Auto Activate: Yes
11
 * Module Tags: Social
12
 * Feature: Engagement, Jumpstart
13
 * Additional Search Queries: subscriptions, subscription, email, follow, followers, subscribers, signup
14
 */
15
16
add_action( 'jetpack_modules_loaded', 'jetpack_subscriptions_load' );
17
18
function jetpack_subscriptions_load() {
19
	Jetpack::enable_module_configurable( __FILE__ );
20
	Jetpack::module_configuration_load( __FILE__, 'jetpack_subscriptions_configuration_load' );
21
}
22
23
function jetpack_subscriptions_configuration_load() {
24
	wp_safe_redirect( admin_url( 'options-discussion.php#jetpack-subscriptions-settings' ) );
25
	exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function jetpack_subscriptions_configuration_load() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
26
}
27
28
class Jetpack_Subscriptions {
29
	public $jetpack = false;
30
31
	public static $hash;
32
33
	/**
34
	 * Singleton
35
	 * @static
36
	 */
37
	static function init() {
38
		static $instance = false;
39
40
		if ( !$instance ) {
41
			$instance = new Jetpack_Subscriptions;
42
		}
43
44
		return $instance;
45
	}
46
47
	function __construct() {
48
		$this->jetpack = Jetpack::init();
0 ignored issues
show
Documentation Bug introduced by
It seems like \Jetpack::init() of type object<Jetpack> is incompatible with the declared type boolean of property $jetpack.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
49
50
		// Don't use COOKIEHASH as it could be shared across installs && is non-unique in multisite.
51
		// @see: https://twitter.com/nacin/status/378246957451333632
52
		self::$hash = md5( get_option( 'siteurl' ) );
53
54
		add_filter( 'jetpack_xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
55
56
		// @todo remove sync from subscriptions and move elsewhere...
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
57
58
		// Add Configuration Page
59
		add_action( 'admin_init', array( $this, 'configure' ) );
60
61
		// Set up the subscription widget.
62
		add_action( 'widgets_init', array( $this, 'widget_init' ) );
63
64
		// Catch subscription widget submits
65
		if ( isset( $_REQUEST['jetpack_subscriptions_widget'] ) )
66
			add_action( 'template_redirect', array( $this, 'widget_submit' ) );
67
68
		// Set up the comment subscription checkboxes
69
		add_action( 'comment_form', array( $this, 'comment_subscribe_init' ) );
70
71
		// Catch comment posts and check for subscriptions.
72
		add_action( 'comment_post', array( $this, 'comment_subscribe_submit' ), 50, 2 );
73
74
		// Adds post meta checkbox in the post submit metabox
75
		add_action( 'post_submitbox_misc_actions', array( $this, 'subscription_post_page_metabox' ) );
76
77
		add_action( 'transition_post_status', array( $this, 'maybe_send_subscription_email' ), 10, 3 );
78
	}
79
80
	/**
81
	 * Jetpack_Subscriptions::xmlrpc_methods()
82
	 *
83
	 * Register subscriptions methods with the Jetpack XML-RPC server.
84
	 * @param array $methods
85
	 */
86
	function xmlrpc_methods( $methods ) {
87
		return array_merge(
88
			$methods,
89
			array(
90
				'jetpack.subscriptions.subscribe' => array( $this, 'subscribe' ),
91
			)
92
		);
93
	}
94
95
	/*
96
	 * Disable Subscribe on Single Post
97
	 * Register post meta
98
	 */
99
	function subscription_post_page_metabox() {
100
		if (
101
			/**
102
			 * Filter whether or not to show the per-post subscription option.
103
			 *
104
			 * @module subscriptions
105
			 *
106
			 * @since 3.7.0
107
			 *
108
			 * @param bool true = show checkbox option on all new posts | false = hide the option.
109
			 */
110
			 ! apply_filters( 'jetpack_allow_per_post_subscriptions', false ) )
111
		{
112
			return;
113
		}
114
115
		if ( has_filter( 'jetpack_subscriptions_exclude_these_categories' ) || has_filter( 'jetpack_subscriptions_include_only_these_categories' ) ) {
116
			return;
117
		}
118
119
		global $post;
120
		$disable_subscribe_value = get_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', true );
121
		// Nonce it
122
		wp_nonce_field( 'disable_subscribe', 'disable_subscribe_nonce' );
123
		// only show checkbox if post hasn't been published and is a 'post' post type.
124
		if ( get_post_status( $post->ID ) !== 'publish' && get_post_type( $post->ID ) == 'post' ) : ?>
125
			<div class="misc-pub-section">
126
				<label for="_jetpack_dont_email_post_to_subs"><?php _e( 'Jetpack Subscriptions:', 'jetpack' ); ?></label><br>
127
				<input type="checkbox" name="_jetpack_dont_email_post_to_subs" id="jetpack-per-post-subscribe" value="1" <?php checked( $disable_subscribe_value, 1, true ); ?> />
128
				<?php _e( 'Don&#8217;t send this to subscribers', 'jetpack' ); ?>
129
			</div>
130
		<?php endif;
131
	}
132
133
	/**
134
	 * Checks whether or not the post should be emailed to subscribers
135
	 *
136
	 * It checks for the following things in order:
137
	 * - Usage of filter jetpack_subscriptions_exclude_these_categories
138
	 * - Usage of filter jetpack_subscriptions_include_only_these_categories
139
	 * - Existence of the per-post checkbox option
140
	 *
141
	 * Only one of these can be used at any given time.
142
	 *
143
	 * @param $new_status string - the "new" post status of the transition when saved
144
	 * @param $old_status string - the "old" post status of the transition when saved
145
	 * @param $post obj - The post object
146
	 */
147
	function maybe_send_subscription_email( $new_status, $old_status, $post ) {
148
		// Only do things on publish
149
		if ( 'publish' !== $new_status ) {
150
			return;
151
		}
152
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
153
			return;
154
		}
155
156
		/**
157
		 * If we're updating the post, let's make sure the flag to not send to subscribers
158
		 * is set to minimize the chances of sending posts multiple times.
159
		 */
160
		if ( 'publish' == $old_status ) {
161
			update_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', 1 );
162
		}
163
164
		/**
165
		 * Array of categories that will never trigger subscription emails.
166
		 *
167
		 * Will not send subscription emails from any post from within these categories.
168
		 *
169
		 * @module subscriptions
170
		 *
171
		 * @since 3.7.0
172
		 *
173
		 * @param array $args Array of category slugs or ID's.
174
		 */
175
		$excluded_categories = apply_filters( 'jetpack_subscriptions_exclude_these_categories', array() );
176
177
		// Never email posts from these categories
178 View Code Duplication
		if ( ! empty( $excluded_categories ) && in_category( $excluded_categories, $post->ID ) ) {
179
			update_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', 1 );
180
		}
181
182
		/**
183
		 * ONLY send subscription emails for these categories
184
		 *
185
		 * Will ONLY send subscription emails to these categories.
186
		 *
187
		 * @module subscriptions
188
		 *
189
		 * @since 3.7.0
190
		 *
191
		 * @param array $args Array of category slugs or ID's.
192
		 */
193
		$only_these_categories = apply_filters( 'jetpack_subscriptions_exclude_all_categories_except', array() );
194
195
		// Only emails posts from these categories
196 View Code Duplication
		if ( ! empty( $only_these_categories ) && ! in_category( $only_these_categories, $post->ID ) ) {
197
			update_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', 1 );
198
		}
199
200
		// Email the post, depending on the checkbox option
201
		if ( ! empty( $_POST['disable_subscribe_nonce'] ) && wp_verify_nonce( $_POST['disable_subscribe_nonce'], 'disable_subscribe' ) ) {
202
			if ( isset( $_POST['_jetpack_dont_email_post_to_subs'] ) ) {
203
				update_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', $_POST['_jetpack_dont_email_post_to_subs'] );
204
			}
205
		}
206
	}
207
208
	/**
209
	 * Jetpack_Subscriptions::configure()
210
	 *
211
	 * Jetpack Subscriptions configuration screen.
212
	 */
213
	function configure() {
214
		// Create the section
215
		add_settings_section(
216
			'jetpack_subscriptions',
217
			__( 'Jetpack Subscriptions Settings', 'jetpack' ),
218
			array( $this, 'subscriptions_settings_section' ),
219
			'discussion'
220
		);
221
222
		/** Subscribe to Posts ***************************************************/
223
224
		add_settings_field(
225
			'jetpack_subscriptions_post_subscribe',
226
			__( 'Follow Blog', 'jetpack' ),
227
			array( $this, 'subscription_post_subscribe_setting' ),
228
			'discussion',
229
			'jetpack_subscriptions'
230
		);
231
232
		register_setting(
233
			'discussion',
234
			'stb_enabled'
235
		);
236
237
		/** Subscribe to Comments ******************************************************/
238
239
		add_settings_field(
240
			'jetpack_subscriptions_comment_subscribe',
241
			__( 'Follow Comments', 'jetpack' ),
242
			array( $this, 'subscription_comment_subscribe_setting' ),
243
			'discussion',
244
			'jetpack_subscriptions'
245
		);
246
247
		register_setting(
248
			'discussion',
249
			'stc_enabled'
250
		);
251
252
		/** Subscription Messaging Options ******************************************************/
253
254
		register_setting(
255
			'reading',
256
			'subscription_options',
257
			array( $this, 'validate_settings' )
258
		);
259
260
		add_settings_section(
261
			'email_settings',
262
			__( 'Follower Settings', 'jetpack' ),
263
			array( $this, 'reading_section' ),
264
			'reading'
265
		);
266
267
		add_settings_field(
268
			'invitation',
269
			__( 'Blog follow email text', 'jetpack' ),
270
			array( $this, 'setting_invitation' ),
271
			'reading',
272
			'email_settings'
273
		);
274
275
		add_settings_field(
276
			'comment-follow',
277
			__( 'Comment follow email text', 'jetpack' ),
278
			array( $this, 'setting_comment_follow' ),
279
			'reading',
280
			'email_settings'
281
		);
282
	}
283
284
	/**
285
	 * Discussions setting section blurb
286
	 *
287
	 */
288
	function subscriptions_settings_section() {
289
	?>
290
291
		<p id="jetpack-subscriptions-settings"><?php _e( 'Change whether your visitors can subscribe to your posts or comments or both.', 'jetpack' ); ?></p>
292
293
	<?php
294
	}
295
296
	/**
297
	 * Post Subscriptions Toggle
298
	 *
299
	 */
300 View Code Duplication
	function subscription_post_subscribe_setting() {
301
302
		$stb_enabled = get_option( 'stb_enabled', 1 ); ?>
303
304
		<p class="description">
305
			<input type="checkbox" name="stb_enabled" id="jetpack-post-subscribe" value="1" <?php checked( $stb_enabled, 1 ); ?> />
306
			<?php _e( "Show a <em>'follow blog'</em> option in the comment form", 'jetpack' ); ?>
307
		</p>
308
	<?php
309
	}
310
311
	/**
312
	 * Comments Subscriptions Toggle
313
	 *
314
	 */
315 View Code Duplication
	function subscription_comment_subscribe_setting() {
316
317
		$stc_enabled = get_option( 'stc_enabled', 1 ); ?>
318
319
		<p class="description">
320
			<input type="checkbox" name="stc_enabled" id="jetpack-comment-subscribe" value="1" <?php checked( $stc_enabled, 1 ); ?> />
321
			<?php _e( "Show a <em>'follow comments'</em> option in the comment form", 'jetpack' ); ?>
322
		</p>
323
324
	<?php
325
	}
326
327
	function validate_settings( $settings ) {
328
		global $allowedposttags;
329
330
		$default = $this->get_default_settings();
331
332
		// Blog Follow
333
		$settings['invitation'] = trim( wp_kses( $settings['invitation'], $allowedposttags ) );
334
		if ( empty( $settings['invitation'] ) )
335
			$settings['invitation'] = $default['invitation'];
336
337
		// Comments Follow (single post)
338
		$settings['comment_follow'] = trim( wp_kses( $settings['comment_follow'], $allowedposttags ) );
339
		if ( empty( $settings['comment_follow'] ) )
340
			$settings['comment_follow'] = $default['comment_follow'];
341
342
		return $settings;
343
	}
344
345
	public function reading_section() {
346
		echo '<p id="follower-settings">';
347
		_e( 'These settings change emails sent from your blog to followers.', 'jetpack' );
348
		echo '</p>';
349
	}
350
351
	public function setting_invitation() {
352
		$settings = $this->get_settings();
353
		echo '<textarea name="subscription_options[invitation]" class="large-text" cols="50" rows="5">' . esc_textarea( $settings['invitation'] ) . '</textarea>';
354
		echo '<p><span class="description">'.__( 'Introduction text sent when someone follows your blog. (Site and confirmation details will be automatically added for you.)', 'jetpack' ).'</span></p>';
355
	}
356
357
	public function setting_comment_follow() {
358
		$settings = $this->get_settings();
359
		echo '<textarea name="subscription_options[comment_follow]" class="large-text" cols="50" rows="5">' . esc_textarea( $settings['comment_follow'] ) . '</textarea>';
360
		echo '<p><span class="description">'.__( 'Introduction text sent when someone follows a post on your blog. (Site and confirmation details will be automatically added for you.)', 'jetpack' ).'</span></p>';
361
	}
362
363
	function get_default_settings() {
364
		return array(
365
			'invitation'     => __( "Howdy.\n\nYou recently followed this blog's posts. This means you will receive each new post by email.\n\nTo activate, click confirm below. If you believe this is an error, ignore this message and we'll never bother you again.", 'jetpack' ),
366
			'comment_follow' => __( "Howdy.\n\nYou recently followed one of my posts. This means you will receive an email when new comments are posted.\n\nTo activate, click confirm below. If you believe this is an error, ignore this message and we'll never bother you again.", 'jetpack' )
367
		);
368
	}
369
370
	function get_settings() {
371
		return wp_parse_args( (array) get_option( 'subscription_options', array() ), $this->get_default_settings() );
372
	}
373
374
	/**
375
	 * Jetpack_Subscriptions::subscribe()
376
	 *
377
	 * Send a synchronous XML-RPC subscribe to blog posts or subscribe to post comments request.
378
	 *
379
	 * @param string $email
380
	 * @param array  $post_ids (optional) defaults to 0 for blog posts only: array of post IDs to subscribe to blog's posts
0 ignored issues
show
Documentation introduced by
Should the type for parameter $post_ids not be integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
381
	 * @param bool   $async    (optional) Should the subscription be performed asynchronously?  Defaults to true.
382
	 *
383
	 * @return true|Jetpack_Error true on success
384
	 *	invalid_email   : not a valid email address
385
	 *	invalid_post_id : not a valid post ID
386
	 *	unknown_post_id : unknown post
387
	 *	not_subscribed  : strange error.  Jetpack servers at WordPress.com could subscribe the email.
388
	 *	disabled        : Site owner has disabled subscriptions.
389
	 *	active          : Already subscribed.
390
	 *	unknown         : strange error.  Jetpack servers at WordPress.com returned something malformed.
391
	 *	unknown_status  : strange error.  Jetpack servers at WordPress.com returned something I didn't understand.
392
	 */
393
	function subscribe( $email, $post_ids = 0, $async = true, $extra_data = array() ) {
394
		if ( !is_email( $email ) ) {
395
			return new Jetpack_Error( 'invalid_email' );
396
		}
397
398
		if ( !$async ) {
399
			Jetpack::load_xml_rpc_client();
400
			$xml = new Jetpack_IXR_ClientMulticall();
401
		}
402
403
		foreach ( (array) $post_ids as $post_id ) {
404
			$post_id = (int) $post_id;
405
			if ( $post_id < 0 ) {
406
				return new Jetpack_Error( 'invalid_post_id' );
407
			} else if ( $post_id && !$post = get_post( $post_id ) ) {
408
				return new Jetpack_Error( 'unknown_post_id' );
409
			}
410
411
			if ( $async ) {
412
				Jetpack::xmlrpc_async_call( 'jetpack.subscribeToSite', $email, $post_id, serialize( $extra_data ) );
413
			} else {
414
				$xml->addCall( 'jetpack.subscribeToSite', $email, $post_id, serialize( $extra_data ) );
0 ignored issues
show
Bug introduced by
The variable $xml does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
415
			}
416
		}
417
418
		if ( $async ) {
419
			return;
420
		}
421
422
		// Call
423
		$xml->query();
424
425
		if ( $xml->isError() ) {
426
			return $xml->get_jetpack_error();
427
		}
428
429
		$responses = $xml->getResponse();
430
431
		$r = array();
432
		foreach ( (array) $responses as $response ) {
433
			if ( isset( $response['faultCode'] ) || isset( $response['faultString'] ) ) {
434
				$r[] = $xml->get_jetpack_error( $response['faultCode'], $response['faultString'] );
435
				continue;
436
			}
437
438
			if ( !is_array( $response[0] ) || empty( $response[0]['status'] ) ) {
439
				$r[] = new Jetpack_Error( 'unknown' );
440
				continue;
441
			}
442
443
			switch ( $response[0]['status'] ) {
444
			case 'error' :
445
				$r[] = new Jetpack_Error( 'not_subscribed' );
446
				continue 2;
447
			case 'disabled' :
448
				$r[] = new Jetpack_Error( 'disabled' );
449
				continue 2;
450
			case 'active' :
451
				$r[] = new Jetpack_Error( 'active' );
452
				continue 2;
453
			case 'pending' :
454
				$r[] = true;
455
				continue 2;
456
			default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
457
				$r[] = new Jetpack_Error( 'unknown_status', (string) $response[0]['status'] );
458
				continue 2;
459
			}
460
		}
461
462
		return $r;
463
	}
464
465
	/**
466
	 * Jetpack_Subscriptions::widget_init()
467
	 *
468
	 * Initialize and register the Jetpack Subscriptions widget.
469
	 */
470
	function widget_init() {
471
		register_widget( 'Jetpack_Subscriptions_Widget' );
472
	}
473
474
	/**
475
	 * Jetpack_Subscriptions::widget_submit()
476
	 *
477
	 * When a user submits their email via the blog subscription widget, check the details and call the subsribe() method.
478
	 */
479
	function widget_submit() {
480
		// Check the nonce.
481
		if ( is_user_logged_in() ) {
482
			check_admin_referer( 'blogsub_subscribe_' . get_current_blog_id() );
483
		}
484
485
		if ( empty( $_REQUEST['email'] ) )
486
			return false;
487
488
		$redirect_fragment = false;
489
		if ( isset( $_REQUEST['redirect_fragment'] ) ) {
490
			$redirect_fragment = preg_replace( '/[^a-z0-9_-]/i', '', $_REQUEST['redirect_fragment'] );
491
		}
492
		if ( !$redirect_fragment ) {
493
			$redirect_fragment = 'subscribe-blog';
494
		}
495
496
		$subscribe = Jetpack_Subscriptions::subscribe(
497
												$_REQUEST['email'],
498
												0,
499
												false,
500
												array(
501
													'source'         => 'widget',
502
													'widget-in-use'  => is_active_widget( false, false, 'blog_subscription', true ) ? 'yes' : 'no',
503
													'comment_status' => '',
504
													'server_data'    => $_SERVER,
505
												)
506
		);
507
508
		if ( is_wp_error( $subscribe ) ) {
509
			$error = $subscribe->get_error_code();
510
		} else {
511
			$error = false;
512
			foreach ( $subscribe as $response ) {
0 ignored issues
show
Bug introduced by
The expression $subscribe of type object<Jetpack_Error>|null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

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

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

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

Loading history...
513
				if ( is_wp_error( $response ) ) {
514
					$error = $response->get_error_code();
515
					break;
516
				}
517
			}
518
		}
519
520
		switch ( $error ) {
521
			case false:
522
				$result = 'success';
523
				break;
524
			case 'invalid_email':
525
				$result = $error;
526
				break;
527
			case 'active':
528
			case 'blocked_email':
529
				$result = 'opted_out';
530
				break;
531
			case 'pending':
532
				$result = 'already';
533
				break;
534
			default:
535
				$result = 'error';
536
				break;
537
		}
538
539
		$redirect = add_query_arg( 'subscribe', $result );
540
541
		/**
542
		 * Fires on each subscription form submission.
543
		 *
544
		 * @module subscriptions
545
		 *
546
		 * @since 3.7.0
547
		 *
548
		 * @param string $result Result of form submission: success, invalid_email, already, error.
549
		 */
550
		do_action( 'jetpack_subscriptions_form_submission', $result );
551
552
		wp_safe_redirect( "$redirect#$redirect_fragment" );
553
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method widget_submit() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
554
	}
555
556
	/**
557
	 * Jetpack_Subscriptions::comment_subscribe_init()
558
	 *
559
	 * Set up and add the comment subscription checkbox to the comment form.
560
	 */
561
	function comment_subscribe_init() {
562
		global $post;
563
564
		$comments_checked = '';
565
		$blog_checked     = '';
566
567
		// Check for a comment / blog submission and set a cookie to retain the setting and check the boxes.
568
		if ( isset( $_COOKIE[ 'jetpack_comments_subscribe_' . self::$hash . '_' . $post->ID ] ) ) {
569
			$comments_checked = ' checked="checked"';
570
		}
571
572
		if ( isset( $_COOKIE[ 'jetpack_blog_subscribe_' . self::$hash ] ) ) {
573
			$blog_checked = ' checked="checked"';
574
		}
575
576
		// Some themes call this function, don't show the checkbox again
577
		remove_action( 'comment_form', 'subscription_comment_form' );
578
579
		// Check if Mark Jaquith's Subscribe to Comments plugin is active - if so, suppress Jetpack checkbox
580
581
		$str = '';
582
583
		if ( FALSE === has_filter( 'comment_form', 'show_subscription_checkbox' ) && 1 == get_option( 'stc_enabled', 1 ) && empty( $post->post_password ) && 'post' == get_post_type() ) {
584
			// Subscribe to comments checkbox
585
			$str .= '<p class="comment-subscription-form"><input type="checkbox" name="subscribe_comments" id="subscribe_comments" value="subscribe" style="width: auto; -moz-appearance: checkbox; -webkit-appearance: checkbox;"' . $comments_checked . ' /> ';
586
			$comment_sub_text = __( 'Notify me of follow-up comments by email.', 'jetpack' );
587
			$str .=	'<label class="subscribe-label" id="subscribe-label" for="subscribe_comments">' . esc_html(
588
				/**
589
				 * Filter the Subscribe to comments text appearing below the comment form.
590
				 *
591
				 * @module subscriptions
592
				 *
593
				 * @since 3.4.0
594
				 *
595
				 * @param string $comment_sub_text Subscribe to comments text.
596
				 */
597
				apply_filters( 'jetpack_subscribe_comment_label', $comment_sub_text )
598
			) . '</label>';
599
			$str .= '</p>';
600
		}
601
602
		if ( 1 == get_option( 'stb_enabled', 1 ) ) {
603
			// Subscribe to blog checkbox
604
			$str .= '<p class="comment-subscription-form"><input type="checkbox" name="subscribe_blog" id="subscribe_blog" value="subscribe" style="width: auto; -moz-appearance: checkbox; -webkit-appearance: checkbox;"' . $blog_checked . ' /> ';
605
			$blog_sub_text = __( 'Notify me of new posts by email.', 'jetpack' );
606
			$str .=	'<label class="subscribe-label" id="subscribe-blog-label" for="subscribe_blog">' . esc_html(
607
				/**
608
				 * Filter the Subscribe to blog text appearing below the comment form.
609
				 *
610
				 * @module subscriptions
611
				 *
612
				 * @since 3.4.0
613
				 *
614
				 * @param string $comment_sub_text Subscribe to blog text.
615
				 */
616
				apply_filters( 'jetpack_subscribe_blog_label', $blog_sub_text )
617
			) . '</label>';
618
			$str .= '</p>';
619
		}
620
621
		/**
622
		 * Filter the output of the subscription options appearing below the comment form.
623
		 *
624
		 * @module subscriptions
625
		 *
626
		 * @since 1.2.0
627
		 *
628
		 * @param string $str Comment Subscription form HTML output.
629
		 */
630
		echo apply_filters( 'jetpack_comment_subscription_form', $str );
631
	}
632
633
	/**
634
	 * Jetpack_Subscriptions::comment_subscribe_init()
635
	 *
636
	 * When a user checks the comment subscribe box and submits a comment, subscribe them to the comment thread.
637
	 */
638
	function comment_subscribe_submit( $comment_id, $approved ) {
639
		if ( 'spam' === $approved ) {
640
			return;
641
		}
642
643
		$comment = get_comment( $comment_id );
644
645
		// Set cookies for this post/comment
646
		$this->set_cookies( isset( $_REQUEST['subscribe_comments'] ), $comment->comment_post_ID, isset( $_REQUEST['subscribe_blog'] ) );
647
648
		if ( !isset( $_REQUEST['subscribe_comments'] ) && !isset( $_REQUEST['subscribe_blog'] ) )
649
			return;
650
651
		$post_ids = array();
652
653
		if ( isset( $_REQUEST['subscribe_comments'] ) )
654
			$post_ids[] = $comment->comment_post_ID;
655
656
		if ( isset( $_REQUEST['subscribe_blog'] ) )
657
			$post_ids[] = 0;
658
659
		Jetpack_Subscriptions::subscribe(
660
									$comment->comment_author_email,
661
									$post_ids,
0 ignored issues
show
Documentation introduced by
$post_ids is of type array, but the function expects a integer.

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...
662
									true,
663
									array(
664
										'source'         => 'comment-form',
665
										'widget-in-use'  => is_active_widget( false, false, 'blog_subscription', true ) ? 'yes' : 'no',
666
										'comment_status' => $approved,
667
										'server_data'    => $_SERVER,
668
									)
669
		);
670
	}
671
672
	/**
673
	 * Jetpack_Subscriptions::set_cookies()
674
	 *
675
	 * Set a cookie to save state on the comment and post subscription checkboxes.
676
	 *
677
	 * @param bool $subscribe_to_post Whether the user chose to subscribe to subsequent comments on this post.
678
	 * @param int $post_id If $subscribe_to_post is true, the post ID they've subscribed to.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $post_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
679
	 * @param bool $subscribe_to_blog Whether the user chose to subscribe to all new posts on the blog.
680
	 */
681
	function set_cookies( $subscribe_to_post = false, $post_id = null, $subscribe_to_blog = false ) {
682
		$post_id = intval( $post_id );
683
684
		/** This filter is already documented in core/wp-includes/comment-functions.php */
685
		$cookie_lifetime = apply_filters( 'comment_cookie_lifetime',       30000000 );
686
687
		/**
688
		 * Filter the Jetpack Comment cookie path.
689
		 *
690
		 * @module subscriptions
691
		 *
692
		 * @since 2.5.0
693
		 *
694
		 * @param string COOKIEPATH Cookie path.
695
		 */
696
		$cookie_path     = apply_filters( 'jetpack_comment_cookie_path',   COOKIEPATH );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 5 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...
697
698
		/**
699
		 * Filter the Jetpack Comment cookie domain.
700
		 *
701
		 * @module subscriptions
702
		 *
703
		 * @since 2.5.0
704
		 *
705
		 * @param string COOKIE_DOMAIN Cookie domain.
706
		 */
707
		$cookie_domain   = apply_filters( 'jetpack_comment_cookie_domain', COOKIE_DOMAIN );
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...
708
709
		if ( $subscribe_to_post && $post_id >= 0 ) {
710
			setcookie( 'jetpack_comments_subscribe_' . self::$hash . '_' . $post_id, 1, time() + $cookie_lifetime, $cookie_path, $cookie_domain );
711
		} else {
712
			setcookie( 'jetpack_comments_subscribe_' . self::$hash . '_' . $post_id, '', time() - 3600, $cookie_path, $cookie_domain );
713
		}
714
715
		if ( $subscribe_to_blog ) {
716
			setcookie( 'jetpack_blog_subscribe_' . self::$hash, 1, time() + $cookie_lifetime, $cookie_path, $cookie_domain );
717
		} else {
718
			setcookie( 'jetpack_blog_subscribe_' . self::$hash, '', time() - 3600, $cookie_path, $cookie_domain );
719
		}
720
	}
721
}
722
723
Jetpack_Subscriptions::init();
724
725
726
/***
727
 * Blog Subscription Widget
728
 */
729
730
class Jetpack_Subscriptions_Widget extends WP_Widget {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
731 View Code Duplication
	function __construct() {
732
		$widget_ops  = array( 'classname' => 'jetpack_subscription_widget', 'description' => __( 'Add an email signup form to allow people to subscribe to your blog.', 'jetpack' ) );
733
		$control_ops = array( 'width' => 300 );
734
735
		parent::__construct(
736
			'blog_subscription',
737
			/** This filter is documented in modules/widgets/facebook-likebox.php */
738
			apply_filters( 'jetpack_widget_name', __( 'Blog Subscriptions', 'jetpack' ) ),
739
			$widget_ops,
740
			$control_ops
741
		);
742
	}
743
744
	function widget( $args, $instance ) {
745
		if (
746
			( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) &&
747
			/** This filter is already documented in modules/contact-form/grunion-contact-form.php */
748
			false === apply_filters( 'jetpack_auto_fill_logged_in_user', false )
749
		) {
750
			$subscribe_email = '';
751
		} else {
752
			global $current_user;
753
			if ( ! empty( $current_user->user_email ) ) {
754
				$subscribe_email = esc_attr( $current_user->user_email );
755
			} else {
756
				$subscribe_email = '';
757
			}
758
		}
759
760
		/** This action is already documented in modules/widgets/gravatar-profile.php */
761
		do_action( 'jetpack_stats_extra', 'widget_view', 'jetpack_subscriptions' );
762
763
		$source                 = 'widget';
764
		$instance            	= wp_parse_args( (array) $instance, $this->defaults() );
765
		$subscribe_text      	= isset( $instance['subscribe_text'] )        ? stripslashes( $instance['subscribe_text'] )        : '';
766
		$subscribe_placeholder 	= isset( $instance['subscribe_placeholder'] ) ? stripslashes( $instance['subscribe_placeholder'] ) : '';
767
		$subscribe_button    	= isset( $instance['subscribe_button'] )      ? stripslashes( $instance['subscribe_button'] )      : '';
768
		$success_message    	= isset( $instance['success_message'] )       ? stripslashes( $instance['success_message'] )      : '';
769
		$widget_id              = esc_attr( !empty( $args['widget_id'] )      ? esc_attr( $args['widget_id'] ) : mt_rand( 450, 550 ) );
770
771
		$show_subscribers_total = (bool) $instance['show_subscribers_total'];
772
		$subscribers_total      = $this->fetch_subscriber_count(); // Only used for the shortcode [total-subscribers]
773
774
		// Give the input element a unique ID
775
		/**
776
		 * Filter the subscription form's ID prefix.
777
		 *
778
		 * @module subscriptions
779
		 *
780
		 * @since 2.7.0
781
		 *
782
		 * @param string subscribe-field Subscription form field prefix.
783
		 * @param int $widget_id Widget ID.
784
		 */
785
		$subscribe_field_id = apply_filters( 'subscribe_field_id', 'subscribe-field', $widget_id );
786
787
		// Enqueue the form's CSS
788
		wp_register_style( 'jetpack-subscriptions', plugins_url( 'subscriptions/subscriptions.css', __FILE__ ) );
789
		wp_enqueue_style( 'jetpack-subscriptions' );
790
791
		// Display the subscription form
792
		echo $args['before_widget'];
793
794
		// Only show the title if there actually is a title
795 View Code Duplication
		if( ! empty( $instance['title'] ) ) {
796
			echo $args['before_title'] . esc_attr( $instance['title'] ) . $args['after_title'] . "\n";
797
		}
798
799
		$referer = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
800
801
		// Display any errors
802
		if ( isset( $_GET['subscribe'] ) ) :
803
			switch ( $_GET['subscribe'] ) :
804
				case 'invalid_email' : ?>
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
805
					<p class="error"><?php esc_html_e( 'The email you entered was invalid. Please check and try again.', 'jetpack' ); ?></p>
806
				<?php break;
0 ignored issues
show
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
807
				case 'opted_out' : ?>
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
808
					<p class="error"><?php printf( __( '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">subscribe.wordpress.com</a>', 'jetpack' ),
809
							'https://subscribe.wordpress.com/',
810
							__( 'Manage your email preferences.', 'jetpack' )
811
						); ?>
812
				<?php break;
0 ignored issues
show
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
813
				case 'already' : ?>
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
814
					<p class="error"><?php esc_html_e( 'You have already subscribed to this site. Please check your inbox.', 'jetpack' ); ?></p>
815
				<?php break;
0 ignored issues
show
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
816
				case 'success' : ?>
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
817
					<div class="success"><?php echo wpautop( str_replace( '[total-subscribers]', number_format_i18n( $subscribers_total['value'] ), $success_message ) ); ?></div>
818
					<?php break;
0 ignored issues
show
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
819
				default : ?>
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
The default body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a default statement must start on the line immediately following the statement.

switch ($expr) {
    default:
        doSomething(); //right
        break;
}


switch ($expr) {
    default:

        doSomething(); //wrong
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
820
					<p class="error"><?php esc_html_e( 'There was an error when subscribing. Please try again.', 'jetpack' ); ?></p>
821
				<?php break;
0 ignored issues
show
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
822
			endswitch;
823
		endif;
824
825
		// Display a subscribe form
826
		if ( isset( $_GET['subscribe'] ) && 'success' == $_GET['subscribe'] ) { ?>
827
			<?php
828
		} else { ?>
829
			<form action="#" method="post" accept-charset="utf-8" id="subscribe-blog-<?php echo $widget_id; ?>">
830
				<?php
831
				if ( ! isset ( $_GET['subscribe'] ) || 'success' != $_GET['subscribe'] ) {
832
					?><div id="subscribe-text"><?php echo wpautop( str_replace( '[total-subscribers]', number_format_i18n( $subscribers_total['value'] ), $subscribe_text ) ); ?></div><?php
833
				}
834
835
				if ( $show_subscribers_total && 0 < $subscribers_total['value'] ) {
836
					echo wpautop( sprintf( _n( 'Join %s other subscriber', 'Join %s other subscribers', $subscribers_total['value'], 'jetpack' ), number_format_i18n( $subscribers_total['value'] ) ) );
837
				}
838
				if ( ! isset ( $_GET['subscribe'] ) || 'success' != $_GET['subscribe'] ) { ?>
839
					<p id="subscribe-email">
840
						<label id="jetpack-subscribe-label" for="<?php echo esc_attr( $subscribe_field_id ) . '-' . esc_attr( $widget_id ); ?>">
841
							<?php echo !empty( $subscribe_placeholder ) ? esc_html( $subscribe_placeholder ) : esc_html__( 'Email Address:', 'jetpack' ); ?>
842
						</label>
843
						<input type="email" name="email" required="required" class="required" value="<?php echo esc_attr( $subscribe_email ); ?>" id="<?php echo esc_attr( $subscribe_field_id ) . '-' . esc_attr( $widget_id ); ?>" placeholder="<?php echo esc_attr( $subscribe_placeholder ); ?>" />
844
					</p>
845
846
					<p id="subscribe-submit">
847
						<input type="hidden" name="action" value="subscribe" />
848
						<input type="hidden" name="source" value="<?php echo esc_url( $referer ); ?>" />
849
						<input type="hidden" name="sub-type" value="<?php echo esc_attr( $source ); ?>" />
850
						<input type="hidden" name="redirect_fragment" value="<?php echo $widget_id; ?>" />
851
						<?php
852
							if ( is_user_logged_in() ) {
853
								wp_nonce_field( 'blogsub_subscribe_'. get_current_blog_id(), '_wpnonce', false );
854
							}
855
						?>
856
						<input type="submit" value="<?php echo esc_attr( $subscribe_button ); ?>" name="jetpack_subscriptions_widget" />
857
					</p>
858
				<?php }?>
859
			</form>
860
861
			<script>
862
			/*
863
			Custom functionality for safari and IE
864
			 */
865
			(function( d ) {
866
				// In case the placeholder functionality is available we remove labels
867
				if ( ( 'placeholder' in d.createElement( 'input' ) ) ) {
868
					var label = d.querySelector( 'label[for=subscribe-field-<?php echo $widget_id; ?>]' );
869
						label.style.clip 	 = 'rect(1px, 1px, 1px, 1px)';
870
						label.style.position = 'absolute';
871
						label.style.height   = '1px';
872
						label.style.width    = '1px';
873
						label.style.overflow = 'hidden';
874
				}
875
876
				// Make sure the email value is filled in before allowing submit
877
				var form = d.getElementById('subscribe-blog-<?php echo $widget_id; ?>'),
878
					input = d.getElementById('<?php echo esc_attr( $subscribe_field_id ) . '-' . esc_attr( $widget_id ); ?>'),
879
					handler = function( event ) {
880
						if ( '' === input.value ) {
881
							input.focus();
882
883
							if ( event.preventDefault ){
884
								event.preventDefault();
885
							}
886
887
							return false;
888
						}
889
					};
890
891
				if ( window.addEventListener ) {
892
					form.addEventListener( 'submit', handler, false );
893
				} else {
894
					form.attachEvent( 'onsubmit', handler );
895
				}
896
			})( document );
897
			</script>
898
		<?php } ?>
899
		<?php
900
901
		echo "\n" . $args['after_widget'];
902
	}
903
904
	function increment_subscriber_count( $current_subs_array = array() ) {
905
		$current_subs_array['value']++;
906
907
		set_transient( 'wpcom_subscribers_total', $current_subs_array, 3600 ); // try to cache the result for at least 1 hour
908
909
		return $current_subs_array;
910
	}
911
912
	function fetch_subscriber_count() {
913
		$subs_count = get_transient( 'wpcom_subscribers_total' );
914
915
		if ( FALSE === $subs_count || 'failed' == $subs_count['status'] ) {
916
			Jetpack:: load_xml_rpc_client();
0 ignored issues
show
Coding Style introduced by
Expected 0 spaces after double colon; 1 found

This check looks for references to static members where there are spaces between the name of the type and the actual member.

An example:

Certificate:: TRIPLEDES_CBC

will actually work, but is not very readable.

Loading history...
917
918
			$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
919
920
			$xml->query( 'jetpack.fetchSubscriberCount' );
921
922
			if ( $xml->isError() ) { // if we get an error from .com, set the status to failed so that we will try again next time the data is requested
923
				$subs_count = array(
924
					'status'  => 'failed',
925
					'code'    => $xml->getErrorCode(),
926
					'message' => $xml->getErrorMessage(),
927
					'value'	  => ( isset( $subs_count['value'] ) ) ? $subs_count['value'] : 0,
928
				);
929
			} else {
930
				$subs_count = array(
931
					'status' => 'success',
932
					'value'  => $xml->getResponse(),
933
				);
934
			}
935
936
			set_transient( 'wpcom_subscribers_total', $subs_count, 3600 ); // try to cache the result for at least 1 hour
937
		}
938
939
		return $subs_count;
940
	}
941
942
	function update( $new_instance, $old_instance ) {
943
		$instance = $old_instance;
944
945
		$instance['title']					= wp_kses( stripslashes( $new_instance['title'] ), array() );
946
		$instance['subscribe_text']			= wp_filter_post_kses( stripslashes( $new_instance['subscribe_text'] ) );
947
		$instance['subscribe_placeholder']	= wp_kses( stripslashes( $new_instance['subscribe_placeholder'] ), array() );
948
		$instance['subscribe_button']		= wp_kses( stripslashes( $new_instance['subscribe_button'] ), array() );
949
		$instance['success_message']		= wp_kses( stripslashes( $new_instance['success_message'] ), array() );
950
		$instance['show_subscribers_total']	= isset( $new_instance['show_subscribers_total'] ) && $new_instance['show_subscribers_total'];
951
952
		return $instance;
953
	}
954
955
	public static function defaults() {
956
		return array(
957
			'title'               	 => esc_html__( 'Subscribe to Blog via Email', 'jetpack' ),
958
			'subscribe_text'      	 => esc_html__( 'Enter your email address to subscribe to this blog and receive notifications of new posts by email.', 'jetpack' ),
959
			'subscribe_placeholder'	 => esc_html__( 'Email Address', 'jetpack' ),
960
			'subscribe_button'    	 => esc_html__( 'Subscribe', 'jetpack' ),
961
			'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' ),
962
			'show_subscribers_total' => true,
963
		);
964
	}
965
966
	function form( $instance ) {
967
		$instance = wp_parse_args( (array) $instance, $this->defaults() );
968
969
		$title               	= stripslashes( $instance['title'] );
970
		$subscribe_text      	= stripslashes( $instance['subscribe_text'] );
971
		$subscribe_placeholder 	= stripslashes( $instance['subscribe_placeholder'] );
972
		$subscribe_button    	= stripslashes( $instance['subscribe_button'] );
973
		$success_message		= stripslashes( $instance['success_message']);
974
		$show_subscribers_total = checked( $instance['show_subscribers_total'], true, false );
975
976
		$subs_fetch = $this->fetch_subscriber_count();
977
978
		if ( 'failed' == $subs_fetch['status'] ) {
979
			printf( '<div class="error inline"><p>' . __( '%s: %s', 'jetpack' ) . '</p></div>', esc_html( $subs_fetch['code'] ), esc_html( $subs_fetch['message'] ) );
980
		}
981
		$subscribers_total = number_format_i18n( $subs_fetch['value'] );
982
?>
983
<p>
984
	<label for="<?php echo $this->get_field_id( 'title' ); ?>">
985
		<?php _e( 'Widget title:', 'jetpack' ); ?>
986
		<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
987
	</label>
988
</p>
989
<p>
990
	<label for="<?php echo $this->get_field_id( 'subscribe_text' ); ?>">
991
		<?php _e( 'Optional text to display to your readers:', 'jetpack' ); ?>
992
		<textarea style="width: 95%" id="<?php echo $this->get_field_id( 'subscribe_text' ); ?>" name="<?php echo $this->get_field_name( 'subscribe_text' ); ?>" type="text"><?php echo esc_html( $subscribe_text ); ?></textarea>
993
	</label>
994
</p>
995
<p>
996
	<label for="<?php echo $this->get_field_id( 'subscribe_placeholder' ); ?>">
997
		<?php esc_html_e( 'Subscribe Placeholder:', 'jetpack' ); ?>
998
		<input class="widefat" id="<?php echo $this->get_field_id( 'subscribe_placeholder' ); ?>" name="<?php echo $this->get_field_name( 'subscribe_placeholder' ); ?>" type="text" value="<?php echo esc_attr( $subscribe_placeholder ); ?>" />
999
	</label>
1000
</p>
1001
<p>
1002
	<label for="<?php echo $this->get_field_id( 'subscribe_button' ); ?>">
1003
		<?php _e( 'Subscribe Button:', 'jetpack' ); ?>
1004
		<input class="widefat" id="<?php echo $this->get_field_id( 'subscribe_button' ); ?>" name="<?php echo $this->get_field_name( 'subscribe_button' ); ?>" type="text" value="<?php echo esc_attr( $subscribe_button ); ?>" />
1005
	</label>
1006
</p>
1007
<p>
1008
	<label for="<?php echo $this->get_field_id( 'success_message' ); ?>">
1009
		<?php _e( 'Success Message Text:', 'jetpack' ); ?>
1010
		<textarea style="width: 95%" id="<?php echo $this->get_field_id( 'success_message' ); ?>" name="<?php echo $this->get_field_name( 'success_message' ); ?>" type="text"><?php echo esc_html( $success_message ); ?></textarea>
1011
	</label>
1012
</p>
1013
<p>
1014
	<label for="<?php echo $this->get_field_id( 'show_subscribers_total' ); ?>">
1015
		<input type="checkbox" id="<?php echo $this->get_field_id( 'show_subscribers_total' ); ?>" name="<?php echo $this->get_field_name( 'show_subscribers_total' ); ?>" value="1"<?php echo $show_subscribers_total; ?> />
1016
		<?php echo esc_html( sprintf( _n( 'Show total number of subscribers? (%s subscriber)', 'Show total number of subscribers? (%s subscribers)', $subscribers_total, 'jetpack' ), $subscribers_total ) ); ?>
1017
	</label>
1018
</p>
1019
<?php
1020
	}
1021
}
1022
1023
add_shortcode( 'jetpack_subscription_form', 'jetpack_do_subscription_form' );
1024
1025
function jetpack_do_subscription_form( $instance ) {
1026
	$instance['show_subscribers_total'] = empty( $instance['show_subscribers_total'] ) ? false : true;
1027
	$instance = shortcode_atts( Jetpack_Subscriptions_Widget::defaults(), $instance, 'jetpack_subscription_form' );
1028
	$args = array(
1029
		'before_widget' => sprintf( '<div class="%s">', 'jetpack_subscription_widget' ),
1030
	);
1031
	ob_start();
1032
	the_widget( 'Jetpack_Subscriptions_Widget', $instance, $args );
1033
	$output = ob_get_clean();
1034
	return $output;
1035
}
1036