Completed
Push — branch-4.0 ( fc0d6f...bf547c )
by
unknown
08:22
created

Jetpack_Subscriptions_Widget::defaults()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 0
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Module Name: Subscriptions
4
 * Module Description: Allow users to subscribe to your posts and comments and receive notifications via 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: 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
Jetpack_Sync::sync_options(
19
	__FILE__,
20
	'home',
21
	'blogname',
22
	'siteurl',
23
	'page_on_front',
24
	'permalink_structure',
25
	'category_base',
26
	'rss_use_excerpt',
27
	'subscription_options',
28
	'stb_enabled',
29
	'stc_enabled',
30
	'tag_base'
31
);
32
33
Jetpack_Sync::sync_posts( __FILE__ );
34
Jetpack_Sync::sync_comments( __FILE__ );
35
36
function jetpack_subscriptions_load() {
37
	Jetpack::enable_module_configurable( __FILE__ );
38
	Jetpack::module_configuration_load( __FILE__, 'jetpack_subscriptions_configuration_load' );
39
}
40
41
function jetpack_subscriptions_configuration_load() {
42
	wp_safe_redirect( admin_url( 'options-discussion.php#jetpack-subscriptions-settings' ) );
43
	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...
44
}
45
46
class Jetpack_Subscriptions {
47
	public $jetpack = false;
48
49
	public static $hash;
50
51
	/**
52
	 * Singleton
53
	 * @static
54
	 */
55
	static function init() {
56
		static $instance = false;
57
58
		if ( !$instance ) {
59
			$instance = new Jetpack_Subscriptions;
60
		}
61
62
		return $instance;
63
	}
64
65
	function __construct() {
66
		$this->jetpack = Jetpack::init();
67
68
		// Don't use COOKIEHASH as it could be shared across installs && is non-unique in multisite.
69
		// @see: https://twitter.com/nacin/status/378246957451333632
70
		self::$hash = md5( get_option( 'siteurl' ) );
71
72
		add_filter( 'jetpack_xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
73
74
		// @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...
75
76
		// Add Configuration Page
77
		add_action( 'admin_init', array( $this, 'configure' ) );
78
79
		// Set up the subscription widget.
80
		add_action( 'widgets_init', array( $this, 'widget_init' ) );
81
82
		// Catch subscription widget submits
83
		if ( isset( $_REQUEST['jetpack_subscriptions_widget'] ) )
84
			add_action( 'template_redirect', array( $this, 'widget_submit' ) );
85
86
		// Set up the comment subscription checkboxes
87
		add_action( 'comment_form', array( $this, 'comment_subscribe_init' ) );
88
89
		// Catch comment posts and check for subscriptions.
90
		add_action( 'comment_post', array( $this, 'comment_subscribe_submit' ), 50, 2 );
91
92
		// Adds post meta checkbox in the post submit metabox
93
		add_action( 'post_submitbox_misc_actions', array( $this, 'subscription_post_page_metabox' ) );
94
95
		add_action( 'transition_post_status', array( $this, 'maybe_send_subscription_email' ), 10, 3 );
96
	}
97
98
	function post_is_public( $the_post ) {
99
		if ( !$post = get_post( $the_post ) ) {
100
			return false;
101
		}
102
103
		if ( 'publish' === $post->post_status && strlen( (string) $post->post_password ) < 1 ) {
104
			/**
105
			 * Filter whether posts can be emailed to subscribers.
106
			 *
107
			 * @module subscriptions
108
			 *
109
			 * @since 2.4.0
110
			 *
111
			 * @param bool true Can the post be emailed to Subscribers. Default to true.
112
			 */
113
			return apply_filters( 'jetpack_is_post_mailable', true );
114
		}
115
	}
116
117
	/**
118
	 * Jetpack_Subscriptions::xmlrpc_methods()
119
	 *
120
	 * Register subscriptions methods with the Jetpack XML-RPC server.
121
	 * @param array $methods
122
	 */
123
	function xmlrpc_methods( $methods ) {
124
		return array_merge(
125
			$methods,
126
			array(
127
				'jetpack.subscriptions.subscribe' => array( $this, 'subscribe' ),
128
			)
129
		);
130
	}
131
132
	/*
133
	 * Disable Subscribe on Single Post
134
	 * Register post meta
135
	 */
136
	function subscription_post_page_metabox() {
137
		if (
138
			/**
139
			 * Filter whether or not to show the per-post subscription option.
140
			 *
141
			 * @module subscriptions
142
			 *
143
			 * @since 3.7.0
144
			 *
145
			 * @param bool true = show checkbox option on all new posts | false = hide the option.
146
			 */
147
			 ! apply_filters( 'jetpack_allow_per_post_subscriptions', false ) )
148
		{
149
			return;
150
		}
151
152
		if ( has_filter( 'jetpack_subscriptions_exclude_these_categories' ) || has_filter( 'jetpack_subscriptions_include_only_these_categories' ) ) {
153
			return;
154
		}
155
156
		global $post;
157
		$disable_subscribe_value = get_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', true );
158
		// Nonce it
159
		wp_nonce_field( 'disable_subscribe', 'disable_subscribe_nonce' );
160
		// only show checkbox if post hasn't been published and is a 'post' post type.
161
		if ( get_post_status( $post->ID ) !== 'publish' && get_post_type( $post->ID ) == 'post' ) : ?>
162
			<div class="misc-pub-section">
163
				<label for="_jetpack_dont_email_post_to_subs"><?php _e( 'Jetpack Subscriptions:', 'jetpack' ); ?></label><br>
164
				<input type="checkbox" name="_jetpack_dont_email_post_to_subs" id="jetpack-per-post-subscribe" value="1" <?php checked( $disable_subscribe_value, 1, true ); ?> />
165
				<?php _e( 'Don&#8217;t send this to subscribers', 'jetpack' ); ?>
166
			</div>
167
		<?php endif;
168
	}
169
170
	/**
171
	 * Checks whether or not the post should be emailed to subscribers
172
	 *
173
	 * It checks for the following things in order:
174
	 * - Usage of filter jetpack_subscriptions_exclude_these_categories
175
	 * - Usage of filter jetpack_subscriptions_include_only_these_categories
176
	 * - Existence of the per-post checkbox option
177
	 *
178
	 * Only one of these can be used at any given time.
179
	 *
180
	 * @param $new_status string - the "new" post status of the transition when saved
181
	 * @param $old_status string - the "old" post status of the transition when saved
182
	 * @param $post obj - The post object
183
	 */
184
	function maybe_send_subscription_email( $new_status, $old_status, $post ) {
185
		// Only do things on publish
186
		if ( 'publish' !== $new_status ) {
187
			return;
188
		}
189
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
190
			return;
191
		}
192
193
		/**
194
		 * Array of categories that will never trigger subscription emails.
195
		 *
196
		 * Will not send subscription emails from any post from within these categories.
197
		 *
198
		 * @module subscriptions
199
		 *
200
		 * @since 3.7.0
201
		 *
202
		 * @param array $args Array of category slugs or ID's.
203
		 */
204
		$excluded_categories = apply_filters( 'jetpack_subscriptions_exclude_these_categories', array() );
205
206
		// Never email posts from these categories
207 View Code Duplication
		if ( ! empty( $excluded_categories ) && in_category( $excluded_categories, $post->ID ) ) {
208
			update_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', 1 );
209
		}
210
211
		/**
212
		 * ONLY send subscription emails for these categories
213
		 *
214
		 * Will ONLY send subscription emails to these categories.
215
		 *
216
		 * @module subscriptions
217
		 *
218
		 * @since 3.7.0
219
		 *
220
		 * @param array $args Array of category slugs or ID's.
221
		 */
222
		$only_these_categories = apply_filters( 'jetpack_subscriptions_exclude_all_categories_except', array() );
223
224
		// Only emails posts from these categories
225 View Code Duplication
		if ( ! empty( $only_these_categories ) && ! in_category( $only_these_categories, $post->ID ) ) {
226
			update_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', 1 );
227
		}
228
229
		// Email the post, depending on the checkbox option
230
		if ( ! empty( $_POST['disable_subscribe_nonce'] ) && wp_verify_nonce( $_POST['disable_subscribe_nonce'], 'disable_subscribe' ) ) {
231
			if ( isset( $_POST['_jetpack_dont_email_post_to_subs'] ) ) {
232
				update_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', $_POST['_jetpack_dont_email_post_to_subs'] );
233
			}
234
		}
235
	}
236
237
	/**
238
	 * Jetpack_Subscriptions::configure()
239
	 *
240
	 * Jetpack Subscriptions configuration screen.
241
	 */
242
	function configure() {
243
		// Create the section
244
		add_settings_section(
245
			'jetpack_subscriptions',
246
			__( 'Jetpack Subscriptions Settings', 'jetpack' ),
247
			array( $this, 'subscriptions_settings_section' ),
248
			'discussion'
249
		);
250
251
		/** Subscribe to Posts ***************************************************/
252
253
		add_settings_field(
254
			'jetpack_subscriptions_post_subscribe',
255
			__( 'Follow Blog', 'jetpack' ),
256
			array( $this, 'subscription_post_subscribe_setting' ),
257
			'discussion',
258
			'jetpack_subscriptions'
259
		);
260
261
		register_setting(
262
			'discussion',
263
			'stb_enabled'
264
		);
265
266
		/** Subscribe to Comments ******************************************************/
267
268
		add_settings_field(
269
			'jetpack_subscriptions_comment_subscribe',
270
			__( 'Follow Comments', 'jetpack' ),
271
			array( $this, 'subscription_comment_subscribe_setting' ),
272
			'discussion',
273
			'jetpack_subscriptions'
274
		);
275
276
		register_setting(
277
			'discussion',
278
			'stc_enabled'
279
		);
280
281
		/** Subscription Messaging Options ******************************************************/
282
283
		register_setting(
284
			'reading',
285
			'subscription_options',
286
			array( $this, 'validate_settings' )
287
		);
288
289
		add_settings_section(
290
			'email_settings',
291
			__( 'Follower Settings', 'jetpack' ),
292
			array( $this, 'reading_section' ),
293
			'reading'
294
		);
295
296
		add_settings_field(
297
			'invitation',
298
			__( 'Blog follow email text', 'jetpack' ),
299
			array( $this, 'setting_invitation' ),
300
			'reading',
301
			'email_settings'
302
		);
303
304
		add_settings_field(
305
			'comment-follow',
306
			__( 'Comment follow email text', 'jetpack' ),
307
			array( $this, 'setting_comment_follow' ),
308
			'reading',
309
			'email_settings'
310
		);
311
	}
312
313
	/**
314
	 * Discussions setting section blurb
315
	 *
316
	 */
317
	function subscriptions_settings_section() {
318
	?>
319
320
		<p id="jetpack-subscriptions-settings"><?php _e( 'Change whether your visitors can subscribe to your posts or comments or both.', 'jetpack' ); ?></p>
321
322
	<?php
323
	}
324
325
	/**
326
	 * Post Subscriptions Toggle
327
	 *
328
	 */
329 View Code Duplication
	function subscription_post_subscribe_setting() {
330
331
		$stb_enabled = get_option( 'stb_enabled', 1 ); ?>
332
333
		<p class="description">
334
			<input type="checkbox" name="stb_enabled" id="jetpack-post-subscribe" value="1" <?php checked( $stb_enabled, 1 ); ?> />
335
			<?php _e( "Show a <em>'follow blog'</em> option in the comment form", 'jetpack' ); ?>
336
		</p>
337
	<?php
338
	}
339
340
	/**
341
	 * Comments Subscriptions Toggle
342
	 *
343
	 */
344 View Code Duplication
	function subscription_comment_subscribe_setting() {
345
346
		$stc_enabled = get_option( 'stc_enabled', 1 ); ?>
347
348
		<p class="description">
349
			<input type="checkbox" name="stc_enabled" id="jetpack-comment-subscribe" value="1" <?php checked( $stc_enabled, 1 ); ?> />
350
			<?php _e( "Show a <em>'follow comments'</em> option in the comment form", 'jetpack' ); ?>
351
		</p>
352
353
	<?php
354
	}
355
356
	function validate_settings( $settings ) {
357
		global $allowedposttags;
358
359
		$default = $this->get_default_settings();
360
361
		// Blog Follow
362
		$settings['invitation'] = trim( wp_kses( $settings['invitation'], $allowedposttags ) );
363
		if ( empty( $settings['invitation'] ) )
364
			$settings['invitation'] = $default['invitation'];
365
366
		// Comments Follow (single post)
367
		$settings['comment_follow'] = trim( wp_kses( $settings['comment_follow'], $allowedposttags ) );
368
		if ( empty( $settings['comment_follow'] ) )
369
			$settings['comment_follow'] = $default['comment_follow'];
370
371
		return $settings;
372
	}
373
374
	public function reading_section() {
375
		echo '<p id="follower-settings">';
376
		_e( 'These settings change emails sent from your blog to followers.', 'jetpack' );
377
		echo '</p>';
378
	}
379
380
	public function setting_invitation() {
381
		$settings = $this->get_settings();
382
		echo '<textarea name="subscription_options[invitation]" class="large-text" cols="50" rows="5">' . esc_textarea( $settings['invitation'] ) . '</textarea>';
383
		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>';
384
	}
385
386
	public function setting_comment_follow() {
387
		$settings = $this->get_settings();
388
		echo '<textarea name="subscription_options[comment_follow]" class="large-text" cols="50" rows="5">' . esc_textarea( $settings['comment_follow'] ) . '</textarea>';
389
		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>';
390
	}
391
392
	function get_default_settings() {
393
		return array(
394
			'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' ),
395
			'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' )
396
		);
397
	}
398
399
	function get_settings() {
400
		return wp_parse_args( (array) get_option( 'subscription_options', array() ), $this->get_default_settings() );
401
	}
402
403
	/**
404
	 * Jetpack_Subscriptions::subscribe()
405
	 *
406
	 * Send a synchronous XML-RPC subscribe to blog posts or subscribe to post comments request.
407
	 *
408
	 * @param string $email
409
	 * @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...
410
	 * @param bool   $async    (optional) Should the subscription be performed asynchronously?  Defaults to true.
411
	 *
412
	 * @return true|Jetpack_Error true on success
413
	 *	invalid_email   : not a valid email address
414
	 *	invalid_post_id : not a valid post ID
415
	 *	unknown_post_id : unknown post
416
	 *	not_subscribed  : strange error.  Jetpack servers at WordPress.com could subscribe the email.
417
	 *	disabled        : Site owner has disabled subscriptions.
418
	 *	active          : Already subscribed.
419
	 *	unknown         : strange error.  Jetpack servers at WordPress.com returned something malformed.
420
	 *	unknown_status  : strange error.  Jetpack servers at WordPress.com returned something I didn't understand.
421
	 */
422
	function subscribe( $email, $post_ids = 0, $async = true, $extra_data = array() ) {
423
		if ( !is_email( $email ) ) {
424
			return new Jetpack_Error( 'invalid_email' );
425
		}
426
427
		if ( !$async ) {
428
			Jetpack::load_xml_rpc_client();
429
			$xml = new Jetpack_IXR_ClientMulticall();
430
		}
431
432
		foreach ( (array) $post_ids as $post_id ) {
433
			$post_id = (int) $post_id;
434
			if ( $post_id < 0 ) {
435
				return new Jetpack_Error( 'invalid_post_id' );
436
			} else if ( $post_id && !$post = get_post( $post_id ) ) {
437
				return new Jetpack_Error( 'unknown_post_id' );
438
			}
439
440
			if ( $async ) {
441
				Jetpack::xmlrpc_async_call( 'jetpack.subscribeToSite', $email, $post_id, serialize( $extra_data ) );
442
			} else {
443
				$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...
444
			}
445
		}
446
447
		if ( $async ) {
448
			return;
449
		}
450
451
		// Call
452
		$xml->query();
453
454
		if ( $xml->isError() ) {
455
			return $xml->get_jetpack_error();
456
		}
457
458
		$responses = $xml->getResponse();
459
460
		$r = array();
461
		foreach ( (array) $responses as $response ) {
462
			if ( isset( $response['faultCode'] ) || isset( $response['faultString'] ) ) {
463
				$r[] = $xml->get_jetpack_error( $response['faultCode'], $response['faultString'] );
464
				continue;
465
			}
466
467
			if ( !is_array( $response[0] ) || empty( $response[0]['status'] ) ) {
468
				$r[] = new Jetpack_Error( 'unknown' );
469
				continue;
470
			}
471
472
			switch ( $response[0]['status'] ) {
473
			case 'error' :
474
				$r[] = new Jetpack_Error( 'not_subscribed' );
475
				continue 2;
476
			case 'disabled' :
477
				$r[] = new Jetpack_Error( 'disabled' );
478
				continue 2;
479
			case 'active' :
480
				$r[] = new Jetpack_Error( 'active' );
481
				continue 2;
482
			case 'pending' :
483
				$r[] = true;
484
				continue 2;
485
			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...
486
				$r[] = new Jetpack_Error( 'unknown_status', (string) $response[0]['status'] );
487
				continue 2;
488
			}
489
		}
490
491
		return $r;
492
	}
493
494
	/**
495
	 * Jetpack_Subscriptions::widget_init()
496
	 *
497
	 * Initialize and register the Jetpack Subscriptions widget.
498
	 */
499
	function widget_init() {
500
		register_widget( 'Jetpack_Subscriptions_Widget' );
501
	}
502
503
	/**
504
	 * Jetpack_Subscriptions::widget_submit()
505
	 *
506
	 * When a user submits their email via the blog subscription widget, check the details and call the subsribe() method.
507
	 */
508
	function widget_submit() {
509
		// Check the nonce.
510
		if ( is_user_logged_in() ) {
511
			check_admin_referer( 'blogsub_subscribe_' . get_current_blog_id() );
512
		}
513
514
		if ( empty( $_REQUEST['email'] ) )
515
			return false;
516
517
		$redirect_fragment = false;
518
		if ( isset( $_REQUEST['redirect_fragment'] ) ) {
519
			$redirect_fragment = preg_replace( '/[^a-z0-9_-]/i', '', $_REQUEST['redirect_fragment'] );
520
		}
521
		if ( !$redirect_fragment ) {
522
			$redirect_fragment = 'subscribe-blog';
523
		}
524
525
		$subscribe = Jetpack_Subscriptions::subscribe(
526
												$_REQUEST['email'],
527
												0,
528
												false,
529
												array(
530
													'source'         => 'widget',
531
													'widget-in-use'  => is_active_widget( false, false, 'blog_subscription', true ) ? 'yes' : 'no',
532
													'comment_status' => '',
533
													'server_data'    => $_SERVER,
534
												)
535
		);
536
537
		if ( is_wp_error( $subscribe ) ) {
538
			$error = $subscribe->get_error_code();
539
		} else {
540
			$error = false;
541
			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...
542
				if ( is_wp_error( $response ) ) {
543
					$error = $response->get_error_code();
544
					break;
545
				}
546
			}
547
		}
548
549
		switch ( $error ) {
550
			case false:
551
				$result = 'success';
552
				break;
553
			case 'invalid_email':
554
				$result = $error;
555
				break;
556
			case 'active':
557
			case 'blocked_email':
558
				$result = 'opted_out';
559
				break;
560
			case 'pending':
561
				$result = 'already';
562
				break;
563
			default:
564
				$result = 'error';
565
				break;
566
		}
567
568
		$redirect = add_query_arg( 'subscribe', $result );
569
570
		/**
571
		 * Fires on each subscription form submission.
572
		 *
573
		 * @module subscriptions
574
		 *
575
		 * @since 3.7.0
576
		 *
577
		 * @param string $result Result of form submission: success, invalid_email, already, error.
578
		 */
579
		do_action( 'jetpack_subscriptions_form_submission', $result );
580
581
		wp_safe_redirect( "$redirect#$redirect_fragment" );
582
		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...
583
	}
584
585
	/**
586
	 * Jetpack_Subscriptions::comment_subscribe_init()
587
	 *
588
	 * Set up and add the comment subscription checkbox to the comment form.
589
	 */
590
	function comment_subscribe_init() {
591
		global $post;
592
593
		$comments_checked = '';
594
		$blog_checked     = '';
595
596
		// Check for a comment / blog submission and set a cookie to retain the setting and check the boxes.
597
		if ( isset( $_COOKIE[ 'jetpack_comments_subscribe_' . self::$hash ] ) && $_COOKIE[ 'jetpack_comments_subscribe_' . self::$hash ] == $post->ID )
598
			$comments_checked = ' checked="checked"';
599
600
		if ( isset( $_COOKIE[ 'jetpack_blog_subscribe_' . self::$hash ] ) )
601
			$blog_checked = ' checked="checked"';
602
603
		// Some themes call this function, don't show the checkbox again
604
		remove_action( 'comment_form', 'subscription_comment_form' );
605
606
		// Check if Mark Jaquith's Subscribe to Comments plugin is active - if so, suppress Jetpack checkbox
607
608
		$str = '';
609
610
		if ( FALSE === has_filter( 'comment_form', 'show_subscription_checkbox' ) && 1 == get_option( 'stc_enabled', 1 ) && empty( $post->post_password ) && 'post' == get_post_type() ) {
611
			// Subscribe to comments checkbox
612
			$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 . ' /> ';
613
			$comment_sub_text = __( 'Notify me of follow-up comments by email.', 'jetpack' );
614
			$str .=	'<label class="subscribe-label" id="subscribe-label" for="subscribe_comments">' . esc_html(
615
				/**
616
				 * Filter the Subscribe to comments text appearing below the comment form.
617
				 *
618
				 * @module subscriptions
619
				 *
620
				 * @since 3.4.0
621
				 *
622
				 * @param string $comment_sub_text Subscribe to comments text.
623
				 */
624
				apply_filters( 'jetpack_subscribe_comment_label', $comment_sub_text )
625
			) . '</label>';
626
			$str .= '</p>';
627
		}
628
629
		if ( 1 == get_option( 'stb_enabled', 1 ) ) {
630
			// Subscribe to blog checkbox
631
			$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 . ' /> ';
632
			$blog_sub_text = __( 'Notify me of new posts by email.', 'jetpack' );
633
			$str .=	'<label class="subscribe-label" id="subscribe-blog-label" for="subscribe_blog">' . esc_html(
634
				/**
635
				 * Filter the Subscribe to blog text appearing below the comment form.
636
				 *
637
				 * @module subscriptions
638
				 *
639
				 * @since 3.4.0
640
				 *
641
				 * @param string $comment_sub_text Subscribe to blog text.
642
				 */
643
				apply_filters( 'jetpack_subscribe_blog_label', $blog_sub_text )
644
			) . '</label>';
645
			$str .= '</p>';
646
		}
647
648
		/**
649
		 * Filter the output of the subscription options appearing below the comment form.
650
		 *
651
		 * @module subscriptions
652
		 *
653
		 * @since 1.2.0
654
		 *
655
		 * @param string $str Comment Subscription form HTML output.
656
		 */
657
		echo apply_filters( 'jetpack_comment_subscription_form', $str );
658
	}
659
660
	/**
661
	 * Jetpack_Subscriptions::comment_subscribe_init()
662
	 *
663
	 * When a user checks the comment subscribe box and submits a comment, subscribe them to the comment thread.
664
	 */
665
	function comment_subscribe_submit( $comment_id, $approved ) {
666
		if ( 'spam' === $approved ) {
667
			return;
668
		}
669
670
		// Set cookies for this post/comment
671
		$this->set_cookies( isset( $_REQUEST['subscribe_comments'] ), isset( $_REQUEST['subscribe_blog'] ) );
672
673
		if ( !isset( $_REQUEST['subscribe_comments'] ) && !isset( $_REQUEST['subscribe_blog'] ) )
674
			return;
675
676
		$comment  = get_comment( $comment_id );
677
		$post_ids = array();
678
679
		if ( isset( $_REQUEST['subscribe_comments'] ) )
680
			$post_ids[] = $comment->comment_post_ID;
681
682
		if ( isset( $_REQUEST['subscribe_blog'] ) )
683
			$post_ids[] = 0;
684
685
		Jetpack_Subscriptions::subscribe(
686
									$comment->comment_author_email,
687
									$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...
688
									true,
689
									array(
690
										'source'         => 'comment-form',
691
										'widget-in-use'  => is_active_widget( false, false, 'blog_subscription', true ) ? 'yes' : 'no',
692
										'comment_status' => $approved,
693
										'server_data'    => $_SERVER,
694
									)
695
		);
696
	}
697
698
	/**
699
	 * Jetpack_Subscriptions::set_cookies()
700
	 *
701
	 * Set a cookie to save state on the comment and post subscription checkboxes.
702
	 */
703
	function set_cookies( $comments = true, $posts = true ) {
704
		global $post;
705
706
		/** This filter is already documented in core/wp-includes/comment-functions.php */
707
		$cookie_lifetime = apply_filters( 'comment_cookie_lifetime',       30000000 );
708
		/**
709
		 * Filter the Jetpack Comment cookie path.
710
		 *
711
		 * @module subscriptions
712
		 *
713
		 * @since 2.5.0
714
		 *
715
		 * @param string COOKIEPATH Cookie path.
716
		 */
717
		$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...
718
		/**
719
		 * Filter the Jetpack Comment cookie domain.
720
		 *
721
		 * @module subscriptions
722
		 *
723
		 * @since 2.5.0
724
		 *
725
		 * @param string COOKIE_DOMAIN Cookie domain.
726
		 */
727
		$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...
728
729 View Code Duplication
		if ( $comments )
730
			setcookie( 'jetpack_comments_subscribe_' . self::$hash, $post->ID, time() + $cookie_lifetime, $cookie_path, $cookie_domain );
731
		else
732
			setcookie( 'jetpack_comments_subscribe_' . self::$hash, '', time() - 3600, $cookie_path, $cookie_domain );
733
734 View Code Duplication
		if ( $posts )
735
			setcookie( 'jetpack_blog_subscribe_' . self::$hash, 1, time() + $cookie_lifetime, $cookie_path, $cookie_domain );
736
		else
737
			setcookie( 'jetpack_blog_subscribe_' . self::$hash, '', time() - 3600, $cookie_path, $cookie_domain );
738
	}
739
}
740
741
Jetpack_Subscriptions::init();
742
743
744
/***
745
 * Blog Subscription Widget
746
 */
747
748
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...
749 View Code Duplication
	function __construct() {
750
		$widget_ops  = array( 'classname' => 'jetpack_subscription_widget', 'description' => __( 'Add an email signup form to allow people to subscribe to your blog.', 'jetpack' ) );
751
		$control_ops = array( 'width' => 300 );
752
753
		parent::__construct(
754
			'blog_subscription',
755
			/** This filter is documented in modules/widgets/facebook-likebox.php */
756
			apply_filters( 'jetpack_widget_name', __( 'Blog Subscriptions', 'jetpack' ) ),
757
			$widget_ops,
758
			$control_ops
759
		);
760
	}
761
762
	function widget( $args, $instance ) {
763
		if (
764
			( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) &&
765
			/** This filter is already documented in modules/contact-form/grunion-contact-form.php */
766
			false === apply_filters( 'jetpack_auto_fill_logged_in_user', false )
767
		) {
768
			$subscribe_email = '';
769
		} else {
770
			global $current_user;
771
			if ( ! empty( $current_user->user_email ) ) {
772
				$subscribe_email = esc_attr( $current_user->user_email );
773
			} else {
774
				$subscribe_email = '';
775
			}
776
		}
777
778
779
780
		$source                 = 'widget';
781
		$instance            	= wp_parse_args( (array) $instance, $this->defaults() );
782
		$subscribe_text      	= isset( $instance['subscribe_text'] )        ? stripslashes( $instance['subscribe_text'] )        : '';
783
		$subscribe_placeholder 	= isset( $instance['subscribe_placeholder'] ) ? stripslashes( $instance['subscribe_placeholder'] ) : '';
784
		$subscribe_button    	= isset( $instance['subscribe_button'] )      ? stripslashes( $instance['subscribe_button'] )      : '';
785
		$success_message    	= isset( $instance['success_message'] )       ? stripslashes( $instance['success_message'] )      : '';
786
		$widget_id              = esc_attr( !empty( $args['widget_id'] )      ? esc_attr( $args['widget_id'] ) : mt_rand( 450, 550 ) );
787
788
		$show_subscribers_total = (bool) $instance['show_subscribers_total'];
789
		$subscribers_total      = $this->fetch_subscriber_count(); // Only used for the shortcode [total-subscribers]
790
791
		// Give the input element a unique ID
792
		/**
793
		 * Filter the subscription form's ID prefix.
794
		 *
795
		 * @module subscriptions
796
		 *
797
		 * @since 2.7.0
798
		 *
799
		 * @param string subscribe-field Subscription form field prefix.
800
		 * @param int $widget_id Widget ID.
801
		 */
802
		$subscribe_field_id = apply_filters( 'subscribe_field_id', 'subscribe-field', $widget_id );
803
804
		// Enqueue the form's CSS
805
		wp_register_style( 'jetpack-subscriptions', plugins_url( 'subscriptions/subscriptions.css', __FILE__ ) );
806
		wp_enqueue_style( 'jetpack-subscriptions' );
807
808
		// Display the subscription form
809
		echo $args['before_widget'];
810
811
		// Only show the title if there actually is a title
812 View Code Duplication
		if( ! empty( $instance['title'] ) ) {
813
			echo $args['before_title'] . esc_attr( $instance['title'] ) . $args['after_title'] . "\n";
814
		}
815
816
		$referer = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
817
818
		// Display any errors
819
		if ( isset( $_GET['subscribe'] ) ) :
820
			switch ( $_GET['subscribe'] ) :
821
				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...
822
					<p class="error"><?php esc_html_e( 'The email you entered was invalid. Please check and try again.', 'jetpack' ); ?></p>
823
				<?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...
824
				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...
825
					<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' ),
826
							'https://subscribe.wordpress.com/',
827
							__( 'Manage your email preferences.', 'jetpack' )
828
						); ?>
829
				<?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...
830
				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...
831
					<p class="error"><?php esc_html_e( 'You have already subscribed to this site. Please check your inbox.', 'jetpack' ); ?></p>
832
				<?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...
833
				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...
834
					<div class="success"><?php echo wpautop( str_replace( '[total-subscribers]', number_format_i18n( $subscribers_total['value'] ), $success_message ) ); ?></div>
835
					<?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...
836
				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...
837
					<p class="error"><?php esc_html_e( 'There was an error when subscribing. Please try again.', 'jetpack' ); ?></p>
838
				<?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...
839
			endswitch;
840
		endif;
841
842
		// Display a subscribe form
843
		if ( isset( $_GET['subscribe'] ) && 'success' == $_GET['subscribe'] ) { ?>
844
			<?php
845
		} else { ?>
846
			<form action="#" method="post" accept-charset="utf-8" id="subscribe-blog-<?php echo $widget_id; ?>">
847
				<?php
848
				if ( ! isset ( $_GET['subscribe'] ) || 'success' != $_GET['subscribe'] ) {
849
					?><div id="subscribe-text"><?php echo wpautop( str_replace( '[total-subscribers]', number_format_i18n( $subscribers_total['value'] ), $subscribe_text ) ); ?></div><?php
850
				}
851
852
				if ( $show_subscribers_total && 0 < $subscribers_total['value'] ) {
853
					echo wpautop( sprintf( _n( 'Join %s other subscriber', 'Join %s other subscribers', $subscribers_total['value'], 'jetpack' ), number_format_i18n( $subscribers_total['value'] ) ) );
854
				}
855
				if ( ! isset ( $_GET['subscribe'] ) || 'success' != $_GET['subscribe'] ) { ?>
856
					<p id="subscribe-email">
857
						<label id="jetpack-subscribe-label" for="<?php echo esc_attr( $subscribe_field_id ) . '-' . esc_attr( $widget_id ); ?>">
858
							<?php echo !empty( $subscribe_placeholder ) ? esc_html( $subscribe_placeholder ) : esc_html__( 'Email Address:', 'jetpack' ); ?>
859
						</label>
860
						<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 ); ?>" />
861
					</p>
862
863
					<p id="subscribe-submit">
864
						<input type="hidden" name="action" value="subscribe" />
865
						<input type="hidden" name="source" value="<?php echo esc_url( $referer ); ?>" />
866
						<input type="hidden" name="sub-type" value="<?php echo esc_attr( $source ); ?>" />
867
						<input type="hidden" name="redirect_fragment" value="<?php echo $widget_id; ?>" />
868
						<?php
869
							if ( is_user_logged_in() ) {
870
								wp_nonce_field( 'blogsub_subscribe_'. get_current_blog_id(), '_wpnonce', false );
871
							}
872
						?>
873
						<input type="submit" value="<?php echo esc_attr( $subscribe_button ); ?>" name="jetpack_subscriptions_widget" />
874
					</p>
875
				<?php }?>
876
			</form>
877
878
			<script>
879
			/*
880
			Custom functionality for safari and IE
881
			 */
882
			(function( d ) {
883
				// In case the placeholder functionality is available we remove labels
884
				if ( ( 'placeholder' in d.createElement( 'input' ) ) ) {
885
					var label = d.querySelector( 'label[for=subscribe-field-<?php echo $widget_id; ?>]' );
886
						label.style.clip 	 = 'rect(1px, 1px, 1px, 1px)';
887
						label.style.position = 'absolute';
888
						label.style.height   = '1px';
889
						label.style.width    = '1px';
890
						label.style.overflow = 'hidden';
891
				}
892
893
				// Make sure the email value is filled in before allowing submit
894
				var form = d.getElementById('subscribe-blog-<?php echo $widget_id; ?>'),
895
					input = d.getElementById('<?php echo esc_attr( $subscribe_field_id ) . '-' . esc_attr( $widget_id ); ?>'),
896
					handler = function( event ) {
897
						if ( '' === input.value ) {
898
							input.focus();
899
900
							if ( event.preventDefault ){
901
								event.preventDefault();
902
							}
903
904
							return false;
905
						}
906
					};
907
908
				if ( window.addEventListener ) {
909
					form.addEventListener( 'submit', handler, false );
910
				} else {
911
					form.attachEvent( 'onsubmit', handler );
912
				}
913
			})( document );
914
			</script>
915
		<?php } ?>
916
		<?php
917
918
		echo "\n" . $args['after_widget'];
919
	}
920
921
	function increment_subscriber_count( $current_subs_array = array() ) {
922
		$current_subs_array['value']++;
923
924
		set_transient( 'wpcom_subscribers_total', $current_subs_array, 3600 ); // try to cache the result for at least 1 hour
925
926
		return $current_subs_array;
927
	}
928
929
	function fetch_subscriber_count() {
930
		$subs_count = get_transient( 'wpcom_subscribers_total' );
931
932
		if ( FALSE === $subs_count || 'failed' == $subs_count['status'] ) {
933
			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...
934
935
			$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
936
937
			$xml->query( 'jetpack.fetchSubscriberCount' );
938
939
			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
940
				$subs_count = array(
941
					'status'  => 'failed',
942
					'code'    => $xml->getErrorCode(),
943
					'message' => $xml->getErrorMessage(),
944
					'value'	  => ( isset( $subs_count['value'] ) ) ? $subs_count['value'] : 0,
945
				);
946
			} else {
947
				$subs_count = array(
948
					'status' => 'success',
949
					'value'  => $xml->getResponse(),
950
				);
951
			}
952
953
			set_transient( 'wpcom_subscribers_total', $subs_count, 3600 ); // try to cache the result for at least 1 hour
954
		}
955
956
		return $subs_count;
957
	}
958
959
	function update( $new_instance, $old_instance ) {
960
		$instance = $old_instance;
961
962
		$instance['title']					= wp_kses( stripslashes( $new_instance['title'] ), array() );
963
		$instance['subscribe_text']			= wp_filter_post_kses( stripslashes( $new_instance['subscribe_text'] ) );
964
		$instance['subscribe_placeholder']	= wp_kses( stripslashes( $new_instance['subscribe_placeholder'] ), array() );
965
		$instance['subscribe_button']		= wp_kses( stripslashes( $new_instance['subscribe_button'] ), array() );
966
		$instance['success_message']		= wp_kses( stripslashes( $new_instance['success_message'] ), array() );
967
		$instance['show_subscribers_total']	= isset( $new_instance['show_subscribers_total'] ) && $new_instance['show_subscribers_total'];
968
969
		return $instance;
970
	}
971
972
	public static function defaults() {
973
		return array(
974
			'title'               	 => esc_html__( 'Subscribe to Blog via Email', 'jetpack' ),
975
			'subscribe_text'      	 => esc_html__( 'Enter your email address to subscribe to this blog and receive notifications of new posts by email.', 'jetpack' ),
976
			'subscribe_placeholder'	 => esc_html__( 'Email Address', 'jetpack' ),
977
			'subscribe_button'    	 => esc_html__( 'Subscribe', 'jetpack' ),
978
			'success_message'    	 => esc_html__( 'Success! An email was just sent to confirm your subscription. Please find the email now and click activate to start subscribing.', 'jetpack' ),
979
			'show_subscribers_total' => true,
980
		);
981
	}
982
983
	function form( $instance ) {
984
		$instance = wp_parse_args( (array) $instance, $this->defaults() );
985
986
		$title               	= stripslashes( $instance['title'] );
987
		$subscribe_text      	= stripslashes( $instance['subscribe_text'] );
988
		$subscribe_placeholder 	= stripslashes( $instance['subscribe_placeholder'] );
989
		$subscribe_button    	= stripslashes( $instance['subscribe_button'] );
990
		$success_message		= stripslashes( $instance['success_message']);
991
		$show_subscribers_total = checked( $instance['show_subscribers_total'], true, false );
992
993
		$subs_fetch = $this->fetch_subscriber_count();
994
995
		if ( 'failed' == $subs_fetch['status'] ) {
996
			printf( '<div class="error inline"><p>' . __( '%s: %s', 'jetpack' ) . '</p></div>', esc_html( $subs_fetch['code'] ), esc_html( $subs_fetch['message'] ) );
997
		}
998
		$subscribers_total = number_format_i18n( $subs_fetch['value'] );
999
?>
1000
<p>
1001
	<label for="<?php echo $this->get_field_id( 'title' ); ?>">
1002
		<?php _e( 'Widget title:', 'jetpack' ); ?>
1003
		<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 ); ?>" />
1004
	</label>
1005
</p>
1006
<p>
1007
	<label for="<?php echo $this->get_field_id( 'subscribe_text' ); ?>">
1008
		<?php _e( 'Optional text to display to your readers:', 'jetpack' ); ?>
1009
		<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>
1010
	</label>
1011
</p>
1012
<p>
1013
	<label for="<?php echo $this->get_field_id( 'subscribe_placeholder' ); ?>">
1014
		<?php esc_html_e( 'Subscribe Placeholder:', 'jetpack' ); ?>
1015
		<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 ); ?>" />
1016
	</label>
1017
</p>
1018
<p>
1019
	<label for="<?php echo $this->get_field_id( 'subscribe_button' ); ?>">
1020
		<?php _e( 'Subscribe Button:', 'jetpack' ); ?>
1021
		<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 ); ?>" />
1022
	</label>
1023
</p>
1024
<p>
1025
	<label for="<?php echo $this->get_field_id( 'success_message' ); ?>">
1026
		<?php _e( 'Success Message Text:', 'jetpack' ); ?>
1027
		<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>
1028
	</label>
1029
</p>
1030
<p>
1031
	<label for="<?php echo $this->get_field_id( 'show_subscribers_total' ); ?>">
1032
		<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; ?> />
1033
		<?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 ) ); ?>
1034
	</label>
1035
</p>
1036
<?php
1037
	}
1038
}
1039
1040
add_shortcode( 'jetpack_subscription_form', 'jetpack_do_subscription_form' );
1041
1042
function jetpack_do_subscription_form( $instance ) {
1043
	$instance['show_subscribers_total'] = empty( $instance['show_subscribers_total'] ) ? false : true;
1044
	$instance = shortcode_atts( Jetpack_Subscriptions_Widget::defaults(), $instance, 'jetpack_subscription_form' );
1045
	$args = array(
1046
		'before_widget' => sprintf( '<div class="%s">', 'jetpack_subscription_widget' ),
1047
	);
1048
	ob_start();
1049
	the_widget( 'Jetpack_Subscriptions_Widget', $instance, $args );
1050
	$output = ob_get_clean();
1051
	return $output;
1052
}
1053