Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
12.74% covered (danger)
12.74%
53 / 416
13.33% covered (danger)
13.33%
4 / 30
CRAP
0.00% covered (danger)
0.00%
0 / 1
jetpack_subscriptions_load
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
jetpack_subscriptions_cherry_pick_server_data
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
42
Jetpack_Subscriptions
13.13% covered (danger)
13.13%
52 / 396
10.71% covered (danger)
10.71%
3 / 28
10367.59
0.00% covered (danger)
0.00%
0 / 1
 init
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 __construct
96.55% covered (success)
96.55%
28 / 29
0.00% covered (danger)
0.00%
0 / 1
2
 xmlrpc_methods
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 subscription_post_page_metabox
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
42
 maybe_send_subscription_email
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
13.78
 update_published_message
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 should_email_post_to_subscribers
78.57% covered (warning)
78.57%
11 / 14
0.00% covered (danger)
0.00%
0 / 1
8.63
 set_post_flags
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 configure
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 1
2
 subscriptions_settings_section
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 subscription_post_subscribe_setting
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
2
 subscription_comment_subscribe_setting
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
2
 social_notifications_subscribe_section
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
2
 social_notifications_subscribe_field
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 social_notifications_subscribe_validate
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 subscribe
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 1
462
 widget_submit
0.00% covered (danger)
0.00%
0 / 50
0.00% covered (danger)
0.00%
0 / 1
420
 comment_subscribe_init
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
110
 comment_subscribe_submit
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
90
 set_cookies
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 set_social_notifications_subscribe
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 set_featured_image_in_email_default
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 set_newsletter_send_default
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 maybe_set_first_published_status
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
6
 first_published_status_meta_auth_callback
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 register_post_meta
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
2
 add_subscribers_menu
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
56
 track_newsletter_category_creation
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName)
2/**
3 * Module Name: Newsletter
4 * Module Description: Grow your subscriber list and deliver your content directly to their email inbox.
5 * Sort Order: 9
6 * Recommendation Order: 8
7 * First Introduced: 1.2
8 * Requires Connection: Yes
9 * Requires User Connection: Yes
10 * Auto Activate: No
11 * Module Tags: Social
12 * Feature: Engagement
13 * Additional Search Queries: subscriptions, subscription, email, follow, followers, subscribers, signup, newsletter, creator
14 */
15
16// phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed -- TODO: Move classes to appropriately-named class files.
17
18use Automattic\Jetpack\Admin_UI\Admin_Menu;
19use Automattic\Jetpack\Connection\Manager as Connection_Manager;
20use Automattic\Jetpack\Connection\XMLRPC_Async_Call;
21use Automattic\Jetpack\Newsletter\Settings as Newsletter_Settings;
22use Automattic\Jetpack\Redirect;
23use Automattic\Jetpack\Status;
24use Automattic\Jetpack\Status\Host;
25use Automattic\Jetpack\Subscribers_Dashboard\Dashboard as Subscribers_Dashboard;
26
27if ( ! defined( 'ABSPATH' ) ) {
28    exit( 0 );
29}
30
31add_action( 'jetpack_modules_loaded', 'jetpack_subscriptions_load' );
32
33// Loads the User Content Link Redirection feature.
34require_once __DIR__ . '/subscriptions/jetpack-user-content-link-redirection.php';
35
36/**
37 * Loads the Subscriptions module.
38 */
39function jetpack_subscriptions_load() {
40    Jetpack::enable_module_configurable( __FILE__ );
41}
42
43/**
44 * Cherry picks keys from `$_SERVER` array.
45 *
46 * @since 6.0.0
47 *
48 * @return array An array of server data.
49 */
50function jetpack_subscriptions_cherry_pick_server_data() {
51    $data = array();
52
53    foreach ( $_SERVER as $key => $value ) {
54        if ( ! is_string( $value ) || str_starts_with( $key, 'HTTP_COOKIE' ) ) {
55            continue;
56        }
57
58        if ( str_starts_with( $key, 'HTTP_' ) || in_array( $key, array( 'REMOTE_ADDR', 'REQUEST_URI', 'DOCUMENT_URI' ), true ) ) {
59            $data[ $key ] = $value;
60        }
61    }
62
63    return $data;
64}
65
66/**
67 * Main class file for the Subscriptions module.
68 *
69 * @phan-constructor-used-for-side-effects
70 */
71class Jetpack_Subscriptions {
72    /**
73     * Whether Jetpack has been instantiated or not.
74     *
75     * @var bool
76     */
77    public $jetpack = false;
78
79    /**
80     * Hash of the siteurl option.
81     *
82     * @var string
83     */
84    public static $hash;
85
86    /**
87     * Singleton
88     *
89     * @static
90     */
91    public static function init() {
92        static $instance = false;
93
94        if ( ! $instance ) {
95            $instance = new Jetpack_Subscriptions();
96        }
97
98        return $instance;
99    }
100
101    /**
102     * Jetpack_Subscriptions constructor.
103     */
104    public function __construct() {
105        $this->jetpack = Jetpack::init();
106
107        // Don't use COOKIEHASH as it could be shared across installs && is non-unique in multisite.
108        // @see: https://twitter.com/nacin/status/378246957451333632 .
109        self::$hash = md5( get_option( 'siteurl' ) );
110
111        add_filter( 'jetpack_xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
112
113        // @todo remove sync from subscriptions and move elsewhere...
114
115        // Add Configuration Page.
116        add_action( 'admin_init', array( $this, 'configure' ) );
117
118        // Catch subscription widget submits.
119        if ( isset( $_REQUEST['jetpack_subscriptions_widget'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce checked in widget_submit() for logged in users.
120            add_action( 'template_redirect', array( $this, 'widget_submit' ) );
121        }
122
123        // Set up the comment subscription checkboxes.
124        add_filter( 'comment_form_submit_field', array( $this, 'comment_subscribe_init' ), 10, 2 );
125
126        // Catch comment posts and check for subscriptions.
127        add_action( 'comment_post', array( $this, 'comment_subscribe_submit' ), 50, 2 );
128
129        // Adds post meta checkbox in the post submit metabox.
130        add_action( 'post_submitbox_misc_actions', array( $this, 'subscription_post_page_metabox' ) );
131
132        add_action( 'transition_post_status', array( $this, 'maybe_send_subscription_email' ), 10, 3 );
133
134        add_filter( 'jetpack_published_post_flags', array( $this, 'set_post_flags' ), 10, 2 );
135
136        add_filter( 'post_updated_messages', array( $this, 'update_published_message' ), 18, 1 );
137
138        // Set "social_notifications_subscribe" option during the first-time activation.
139        add_action( 'jetpack_activate_module_subscriptions', array( $this, 'set_social_notifications_subscribe' ) );
140        add_action( 'jetpack_activate_module_subscriptions', array( $this, 'set_featured_image_in_email_default' ) );
141        add_action( 'jetpack_activate_module_subscriptions', array( $this, 'set_newsletter_send_default' ) );
142
143        // Hide subscription messaging in Publish panel for posts that were published in the past
144        add_action( 'init', array( $this, 'register_post_meta' ), 20 );
145        add_action( 'transition_post_status', array( $this, 'maybe_set_first_published_status' ), 10, 3 );
146
147        // Add Subscribers menu to Jetpack navigation.
148        add_action( 'jetpack_admin_menu', array( $this, 'add_subscribers_menu' ) );
149
150        // Customize the configuration URL to lead to the Subscriptions settings.
151        add_filter(
152            'jetpack_module_configuration_url_subscriptions',
153            function () {
154                return Jetpack::admin_url( array( 'page' => 'jetpack#/newsletter' ) );
155            }
156        );
157
158        // Track categories created through the category editor page
159        add_action( 'wp_ajax_add-tag', array( $this, 'track_newsletter_category_creation' ), 1 );
160        $subscribers_dashboard = new Subscribers_Dashboard();
161        $subscribers_dashboard::init();
162
163        $newsletter_settings = new Newsletter_Settings();
164        $newsletter_settings::init();
165    }
166
167    /**
168     * Jetpack_Subscriptions::xmlrpc_methods()
169     *
170     * Register subscriptions methods with the Jetpack XML-RPC server.
171     *
172     * @param array $methods Methods being registered.
173     */
174    public function xmlrpc_methods( $methods ) {
175        return array_merge(
176            $methods,
177            array(
178                'jetpack.subscriptions.subscribe' => array( $this, 'subscribe' ),
179            )
180        );
181    }
182
183    /**
184     * Disable Subscribe on Single Post
185     * Register post meta
186     */
187    public function subscription_post_page_metabox() {
188        if (
189            /**
190             * Filter whether or not to show the per-post subscription option.
191             *
192             * @module subscriptions
193             *
194             * @since 3.7.0
195             *
196             * @param bool true = show checkbox option on all new posts | false = hide the option.
197             */
198            ! apply_filters( 'jetpack_allow_per_post_subscriptions', false ) ) {
199            return;
200        }
201
202        if ( has_filter( 'jetpack_subscriptions_exclude_these_categories' ) || has_filter( 'jetpack_subscriptions_include_only_these_categories' ) ) {
203            return;
204        }
205
206        global $post;
207        $disable_subscribe_value = get_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', true );
208        // only show checkbox if post hasn't been published and is a 'post' post type.
209        if ( get_post_status( $post->ID ) !== 'publish' && get_post_type( $post->ID ) === 'post' ) :
210            // Nonce it.
211            wp_nonce_field( 'disable_subscribe', 'disable_subscribe_nonce' );
212            ?>
213            <div class="misc-pub-section">
214                <label for="_jetpack_dont_email_post_to_subs"><?php esc_html_e( 'Jetpack Subscriptions:', 'jetpack' ); ?></label><br>
215                <input type="checkbox" name="_jetpack_dont_email_post_to_subs" id="jetpack-per-post-subscribe" value="1" <?php checked( $disable_subscribe_value, 1, true ); ?> />
216                <?php esc_html_e( 'Don&#8217;t send this to subscribers', 'jetpack' ); ?>
217            </div>
218            <?php
219        endif;
220    }
221
222    /**
223     * Checks whether or not the post should be emailed to subscribers
224     *
225     * It checks for the following things in order:
226     * - Usage of filter jetpack_subscriptions_exclude_these_categories
227     * - Usage of filter jetpack_subscriptions_include_only_these_categories
228     * - Existence of the per-post checkbox option
229     *
230     * Only one of these can be used at any given time.
231     *
232     * @param string $new_status Tthe "new" post status of the transition when saved.
233     * @param string $old_status The "old" post status of the transition when saved.
234     * @param object $post obj The post object.
235     */
236    public function maybe_send_subscription_email( $new_status, $old_status, $post ) {
237
238        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
239            return;
240        }
241
242        // Make sure that the checkbox is preseved.
243        if ( ! empty( $_POST['disable_subscribe_nonce'] ) && wp_verify_nonce( $_POST['disable_subscribe_nonce'], 'disable_subscribe' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- WP Core doesn't unslash or sanitize nonces either.
244            $set_checkbox = isset( $_POST['_jetpack_dont_email_post_to_subs'] ) ? 1 : 0;
245            update_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', $set_checkbox );
246        }
247    }
248
249    /**
250     * Message used when publishing a post.
251     *
252     * @param array $messages Message array for a post.
253     */
254    public function update_published_message( $messages ) {
255        global $post;
256        if ( ! $this->should_email_post_to_subscribers( $post ) ) {
257            return $messages;
258        }
259
260        $view_post_link_html = sprintf(
261            ' <a href="%1$s">%2$s</a>',
262            esc_url( get_permalink( $post ) ),
263            __( 'View post', 'jetpack' )
264        );
265
266        $messages['post'][6] = sprintf(
267            /* translators: Message shown after a post is published */
268            esc_html__( 'Post published and sending emails to subscribers.', 'jetpack' )
269        ) . $view_post_link_html;
270        return $messages;
271    }
272
273    /**
274     * Determine if a post should notifiy subscribers via email.
275     *
276     * @param object $post The post.
277     */
278    public function should_email_post_to_subscribers( $post ) {
279        $should_email = true;
280        if ( get_post_meta( $post->ID, '_jetpack_dont_email_post_to_subs', true ) ) {
281            return false;
282        }
283
284        // Only posts are currently supported.
285        if ( 'post' !== $post->post_type ) {
286            return false;
287        }
288
289        // Private posts are not sent to subscribers.
290        if ( 'private' === $post->post_status ) {
291            return false;
292        }
293
294        /**
295         * Array of categories that will never trigger subscription emails.
296         *
297         * Will not send subscription emails from any post from within these categories.
298         *
299         * @module subscriptions
300         *
301         * @since 3.7.0
302         *
303         * @param array $args Array of category slugs or ID's.
304         */
305        $excluded_categories = apply_filters( 'jetpack_subscriptions_exclude_these_categories', array() );
306
307        // Never email posts from these categories.
308        if ( ! empty( $excluded_categories ) && in_category( $excluded_categories, $post->ID ) ) {
309            $should_email = false;
310        }
311
312        /**
313         * ONLY send subscription emails for these categories
314         *
315         * Will ONLY send subscription emails to these categories.
316         *
317         * @module subscriptions
318         *
319         * @since 3.7.0
320         *
321         * @param array $args Array of category slugs or ID's.
322         */
323        $only_these_categories = apply_filters( 'jetpack_subscriptions_exclude_all_categories_except', array() );
324
325        // Only emails posts from these categories.
326        if ( ! empty( $only_these_categories ) && ! in_category( $only_these_categories, $post->ID ) ) {
327            $should_email = false;
328        }
329
330        return $should_email;
331    }
332
333    /**
334     * Retrieve which flags should be added to a particular post.
335     *
336     * @param array  $flags Flags to be added.
337     * @param object $post A post object.
338     */
339    public function set_post_flags( $flags, $post ) {
340        $flags['send_subscription'] = $this->should_email_post_to_subscribers( $post );
341        return $flags;
342    }
343
344    /**
345     * Jetpack_Subscriptions::configure()
346     *
347     * Jetpack Subscriptions configuration screen.
348     */
349    public function configure() {
350        // Create the section.
351        add_settings_section(
352            'jetpack_subscriptions',
353            __( 'Jetpack Subscriptions Settings', 'jetpack' ),
354            array( $this, 'subscriptions_settings_section' ),
355            'discussion'
356        );
357
358        /** Subscribe to Posts */
359
360        add_settings_field(
361            'jetpack_subscriptions_post_subscribe',
362            __( 'Follow Blog', 'jetpack' ),
363            array( $this, 'subscription_post_subscribe_setting' ),
364            'discussion',
365            'jetpack_subscriptions'
366        );
367
368        register_setting(
369            'discussion',
370            'stb_enabled'
371        );
372
373        /** Subscribe to Comments */
374
375        add_settings_field(
376            'jetpack_subscriptions_comment_subscribe',
377            __( 'Follow Comments', 'jetpack' ),
378            array( $this, 'subscription_comment_subscribe_setting' ),
379            'discussion',
380            'jetpack_subscriptions'
381        );
382
383        register_setting(
384            'discussion',
385            'stc_enabled'
386        );
387
388        /** Email me whenever: Someone subscribes to my blog */
389        /* @since 8.1 */
390
391        add_settings_section(
392            'notifications_section',
393            __( 'Someone subscribes to my blog', 'jetpack' ),
394            array( $this, 'social_notifications_subscribe_section' ),
395            'discussion'
396        );
397
398        add_settings_field(
399            'jetpack_subscriptions_social_notifications_subscribe',
400            __( 'Email me whenever', 'jetpack' ),
401            array( $this, 'social_notifications_subscribe_field' ),
402            'discussion',
403            'notifications_section'
404        );
405
406        register_setting(
407            'discussion',
408            'social_notifications_subscribe',
409            array( $this, 'social_notifications_subscribe_validate' )
410        );
411    }
412
413    /**
414     * Discussions setting section blurb.
415     */
416    public function subscriptions_settings_section() {
417        ?>
418        <p id="jetpack-subscriptions-settings"><?php esc_html_e( 'Change whether your visitors can subscribe to your posts or comments or both.', 'jetpack' ); ?></p>
419
420        <?php
421    }
422
423    /**
424     * Post Subscriptions Toggle.
425     */
426    public function subscription_post_subscribe_setting() {
427
428        $stb_enabled = get_option( 'stb_enabled', 1 );
429        ?>
430
431        <p class="description">
432            <input type="checkbox" name="stb_enabled" id="jetpack-post-subscribe" value="1" <?php checked( $stb_enabled, 1 ); ?> />
433            <?php
434            echo wp_kses(
435                __(
436                    "Show a <em>'follow blog'</em> option in the comment form",
437                    'jetpack'
438                ),
439                array( 'em' => array() )
440            );
441            ?>
442        </p>
443        <?php
444    }
445
446    /**
447     * Comments Subscriptions Toggle.
448     */
449    public function subscription_comment_subscribe_setting() {
450
451        $stc_enabled = get_option( 'stc_enabled', 1 );
452        ?>
453
454        <p class="description">
455            <input type="checkbox" name="stc_enabled" id="jetpack-comment-subscribe" value="1" <?php checked( $stc_enabled, 1 ); ?> />
456            <?php
457            echo wp_kses(
458                __(
459                    "Show a <em>'follow comments'</em> option in the comment form",
460                    'jetpack'
461                ),
462                array( 'em' => array() )
463            );
464            ?>
465        </p>
466
467        <?php
468    }
469
470    /**
471     * Someone subscribes to my blog section
472     *
473     * @since 8.1
474     */
475    public function social_notifications_subscribe_section() {
476        // Atypical usage here. We emit jquery to move subscribe notification checkbox to be with the rest of the email notification settings.
477        ?>
478        <script type="text/javascript">
479            jQuery( function( $ )  {
480                var table = $( '#social_notifications_subscribe' ).parents( 'table:first' ),
481                    header = table.prevAll( 'h2:first' ),
482                    newParent = $( '#moderation_notify' ).parent( 'label' ).parent();
483
484                if ( ! table.length || ! header.length || ! newParent.length ) {
485                    return;
486                }
487
488                newParent.append( '<br/>' ).append( table.end().parent( 'label' ).siblings().andSelf() );
489                header.remove();
490                table.remove();
491            } );
492        </script>
493        <?php
494    }
495
496    /**
497     * Someone subscribes to my blog Toggle
498     *
499     * @since 8.1
500     */
501    public function social_notifications_subscribe_field() {
502        $checked = (int) ( 'on' === get_option( 'social_notifications_subscribe', 'on' ) );
503        ?>
504
505        <label>
506            <input type="checkbox" name="social_notifications_subscribe" id="social_notifications_subscribe" value="1" <?php checked( $checked ); ?> />
507            <?php
508                /* translators: this is a label for a setting that starts with "Email me whenever" */
509                esc_html_e( 'Someone subscribes to my blog', 'jetpack' );
510            ?>
511        </label>
512        <?php
513    }
514
515    /**
516     * Validate "Someone subscribes to my blog" option
517     *
518     * @since 8.1
519     *
520     * @param String $input the input string to be validated.
521     * @return string on|off
522     */
523    public function social_notifications_subscribe_validate( $input ) {
524        // If it's not set (was unchecked during form submission) or was set to off (during option update), return 'off'.
525        if ( ! $input || 'off' === $input ) {
526            return 'off';
527        }
528
529        // Otherwise we return 'on'.
530        return 'on';
531    }
532
533    /**
534     * Jetpack_Subscriptions::subscribe()
535     *
536     * Send a synchronous XML-RPC subscribe to blog posts or subscribe to post comments request.
537     *
538     * @param string $email being subscribed.
539     * @param array  $post_ids (optional) defaults to 0 for blog posts only: array of post IDs to subscribe to blog's posts.
540     * @param bool   $async    (optional) Should the subscription be performed asynchronously?  Defaults to true.
541     * @param array  $extra_data Additional data passed to the `jetpack.subscribeToSite` call.
542     *
543     * @return true|WP_Error true on success
544     *  invalid_email   : not a valid email address
545     *  invalid_post_id : not a valid post ID
546     *  unknown_post_id : unknown post
547     *  not_subscribed  : strange error.  Jetpack servers at WordPress.com could subscribe the email.
548     *  disabled        : Site owner has disabled subscriptions.
549     *  active          : Already subscribed.
550     *  pending         : Tried to subscribe before but the confirmation link is never clicked. No confirmation email is sent.
551     *  unknown         : strange error.  Jetpack servers at WordPress.com returned something malformed.
552     *  unknown_status  : strange error.  Jetpack servers at WordPress.com returned something I didn't understand.
553     */
554    public function subscribe( $email, $post_ids = 0, $async = true, $extra_data = array() ) {
555        if ( ! is_email( $email ) ) {
556            return new WP_Error( 'invalid_email' );
557        }
558
559        if ( ! $async ) {
560            $xml = new Jetpack_IXR_ClientMulticall();
561        }
562
563        foreach ( (array) $post_ids as $post_id ) {
564            $post_id = (int) $post_id;
565            if ( $post_id < 0 ) {
566                return new WP_Error( 'invalid_post_id' );
567            } elseif ( $post_id && ! get_post( $post_id ) ) {
568                return new WP_Error( 'unknown_post_id' );
569            }
570
571            if ( $async ) {
572                XMLRPC_Async_Call::add_call( 'jetpack.subscribeToSite', 0, $email, $post_id, serialize( $extra_data ) ); //phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize
573            } else {
574                // @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $xml is set when $async is false
575                $xml->addCall( 'jetpack.subscribeToSite', $email, $post_id, serialize( $extra_data ) ); //phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize
576            }
577        }
578
579        if ( $async ) {
580            return;
581        }
582
583        // Call.
584        // @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $xml is set when $async is false, otherwise we return early
585        $xml->query();
586
587        // @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $xml is set when $async is false, otherwise we return early
588        if ( $xml->isError() ) {
589            // @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $xml is set when $async is false, otherwise we return early
590            return $xml->get_jetpack_error();
591        }
592
593        // @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $xml is set when $async is false
594        $responses = $xml->getResponse();
595
596        $r = array();
597        foreach ( (array) $responses as $response ) {
598            if ( isset( $response['faultCode'] ) || isset( $response['faultString'] ) ) {
599                // @phan-suppress-next-line PhanPossiblyUndeclaredVariable -- $xml is set when $async is false
600                $r[] = $xml->get_jetpack_error( $response['faultCode'], $response['faultString'] );
601                continue;
602            }
603
604            if ( ! is_array( $response[0] ) || empty( $response[0]['status'] ) ) {
605                $r[] = new WP_Error( 'unknown' );
606                continue;
607            }
608
609            switch ( $response[0]['status'] ) {
610                case 'error':
611                    $r[] = new WP_Error( 'not_subscribed' );
612                    continue 2;
613                case 'disabled':
614                    $r[] = new WP_Error( 'disabled' );
615                    continue 2;
616                case 'active':
617                    $r[] = new WP_Error( 'active' );
618                    continue 2;
619                case 'confirming':
620                    $r[] = true;
621                    continue 2;
622                case 'pending':
623                    $r[] = new WP_Error( 'pending' );
624                    continue 2;
625                default:
626                    $r[] = new WP_Error( 'unknown_status', (string) $response[0]['status'] );
627                    continue 2;
628            }
629        }
630
631        return $r;
632    }
633
634    /**
635     * Jetpack_Subscriptions::widget_submit()
636     *
637     * When a user submits their email via the blog subscription widget, check the details and call the subsribe() method.
638     */
639    public function widget_submit() {
640        // Check the nonce.
641        if ( ! wp_verify_nonce( isset( $_REQUEST['_wpnonce'] ) ? sanitize_key( $_REQUEST['_wpnonce'] ) : '', 'blogsub_subscribe_' . \Jetpack_Options::get_option( 'id' ) ) ) {
642            return false;
643        }
644
645        if ( empty( $_REQUEST['email'] ) || ! is_string( $_REQUEST['email'] ) ) {
646            return false;
647        }
648
649        $redirect_fragment = false;
650        if ( isset( $_REQUEST['redirect_fragment'] ) ) {
651            $redirect_fragment = preg_replace( '/[^a-z0-9_-]/i', '', $_REQUEST['redirect_fragment'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- This is manually unslashing and sanitizing.
652        }
653        if ( ! $redirect_fragment || ! is_string( $redirect_fragment ) ) {
654            $redirect_fragment = 'subscribe-blog';
655        }
656
657        $subscribe = self::subscribe(
658            isset( $_REQUEST['email'] ) ? wp_unslash( $_REQUEST['email'] ) : null, // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Validated inside self::subscribe().
659            0,
660            false,
661            array(
662                'source'         => 'widget',
663                'widget-in-use'  => is_active_widget( false, false, 'blog_subscription', true ) ? 'yes' : 'no',
664                'comment_status' => '',
665                'server_data'    => jetpack_subscriptions_cherry_pick_server_data(),
666            )
667        );
668
669        if ( is_wp_error( $subscribe ) ) {
670            $error = $subscribe->get_error_code();
671        } else {
672            $error = false;
673            foreach ( $subscribe as $response ) {
674                if ( is_wp_error( $response ) ) {
675                    $error = $response->get_error_code();
676                    break;
677                }
678            }
679        }
680
681        switch ( $error ) {
682            case false:
683                $result = 'success';
684                break;
685            case 'invalid_email':
686                $result = $error;
687                break;
688            case 'blocked_email':
689                $result = 'opted_out';
690                break;
691            case 'active':
692                $result = 'already';
693                break;
694            case 'flooded_email':
695                $result = 'many_pending_subs';
696                break;
697            case 'pending':
698                $result = 'pending';
699                break;
700            default:
701                $result = 'error';
702                break;
703        }
704
705        $redirect = add_query_arg( 'subscribe', $result );
706
707        /**
708         * Fires on each subscription form submission.
709         *
710         * @module subscriptions
711         *
712         * @since 3.7.0
713         *
714         * @param string $result Result of form submission: success, invalid_email, already, error.
715         */
716        do_action( 'jetpack_subscriptions_form_submission', $result );
717
718        wp_safe_redirect( "$redirect#$redirect_fragment" );
719        exit( 0 );
720    }
721
722    /**
723     * Jetpack_Subscriptions::comment_subscribe_init()
724     *
725     * Set up and add the comment subscription checkbox to the comment form.
726     *
727     * @param string $submit_button HTML markup for the submit field.
728     */
729    public function comment_subscribe_init( $submit_button ) {
730        global $post;
731
732        // Subscriptions are only available for posts so far.
733        if ( ! $post || 'post' !== $post->post_type ) {
734            return $submit_button;
735        }
736
737        $comments_checked = '';
738        $blog_checked     = '';
739
740        // Check for a comment / blog submission and set a cookie to retain the setting and check the boxes.
741        if ( isset( $_COOKIE[ 'jetpack_comments_subscribe_' . self::$hash . '_' . $post->ID ] ) ) {
742            $comments_checked = ' checked="checked"';
743        }
744
745        if ( isset( $_COOKIE[ 'jetpack_blog_subscribe_' . self::$hash ] ) ) {
746            $blog_checked = ' checked="checked"';
747        }
748
749        // Some themes call this function, don't show the checkbox again.
750        remove_action( 'comment_form', 'subscription_comment_form' );
751
752        // Check if Mark Jaquith's Subscribe to Comments plugin is active - if so, suppress Jetpack checkbox.
753
754        $str = '';
755
756        if ( false === has_filter( 'comment_form', 'show_subscription_checkbox' ) && 1 === (int) get_option( 'stc_enabled', 1 ) && empty( $post->post_password ) && 'post' === get_post_type() ) {
757            // Subscribe to comments checkbox.
758            $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 . ' /> ';
759            $comment_sub_text = __( 'Notify me of follow-up comments by email.', 'jetpack' );
760            $str             .= '<label class="subscribe-label" id="subscribe-label" for="subscribe_comments">' . esc_html(
761                /**
762                 * Filter the Subscribe to comments text appearing below the comment form.
763                 *
764                 * @module subscriptions
765                 *
766                 * @since 3.4.0
767                 *
768                 * @param string $comment_sub_text Subscribe to comments text.
769                 */
770                apply_filters( 'jetpack_subscribe_comment_label', $comment_sub_text )
771            ) . '</label>';
772            $str .= '</p>';
773        }
774
775        if ( 1 === (int) get_option( 'stb_enabled', 1 ) ) {
776            // Subscribe to blog checkbox.
777            $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 . ' /> ';
778            $blog_sub_text = __( 'Notify me of new posts by email.', 'jetpack' );
779            $str          .= '<label class="subscribe-label" id="subscribe-blog-label" for="subscribe_blog">' . esc_html(
780                /**
781                 * Filter the Subscribe to blog text appearing below the comment form.
782                 *
783                 * @module subscriptions
784                 *
785                 * @since 3.4.0
786                 *
787                 * @param string $comment_sub_text Subscribe to blog text.
788                 */
789                apply_filters( 'jetpack_subscribe_blog_label', $blog_sub_text )
790            ) . '</label>';
791            $str .= '</p>';
792        }
793
794        /**
795         * Filter the output of the subscription options appearing below the comment form.
796         *
797         * @module subscriptions
798         *
799         * @since 1.2.0
800         *
801         * @param string $str Comment Subscription form HTML output.
802         */
803        $str = apply_filters( 'jetpack_comment_subscription_form', $str );
804
805        return $str . $submit_button;
806    }
807
808    /**
809     * Jetpack_Subscriptions::comment_subscribe_init()
810     *
811     * When a user checks the comment subscribe box and submits a comment, subscribe them to the comment thread.
812     *
813     * @param int|string $comment_id Comment thread being subscribed to.
814     * @param string     $approved Comment status.
815     */
816    public function comment_subscribe_submit( $comment_id, $approved ) {
817        /**
818         * Filters whether to skip comment subscription processing.
819         *
820         * @since 15.5
821         *
822         * @param bool $skip Whether to skip comment subscription. Default false.
823         */
824        if ( apply_filters( 'jetpack_subscription_comment_subscribe_skip', false ) ) {
825            return;
826        }
827
828        if ( 'spam' === $approved ) {
829            return;
830        }
831
832        $comment = get_comment( $comment_id );
833        if ( ! $comment ) {
834            return;
835        }
836
837        // Set cookies for this post/comment.
838        $this->set_cookies( isset( $_REQUEST['subscribe_comments'] ), $comment->comment_post_ID, isset( $_REQUEST['subscribe_blog'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
839
840        if ( ! isset( $_REQUEST['subscribe_comments'] ) && ! isset( $_REQUEST['subscribe_blog'] ) ) {  // phpcs:ignore WordPress.Security.NonceVerification.Recommended
841            return;
842        }
843
844        $post_ids = array();
845
846        if ( isset( $_REQUEST['subscribe_comments'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
847            $post_ids[] = $comment->comment_post_ID;
848        }
849
850        if ( isset( $_REQUEST['subscribe_blog'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
851            $post_ids[] = 0;
852        }
853
854        $result = self::subscribe(
855            $comment->comment_author_email,
856            $post_ids,
857            true,
858            array(
859                'source'         => 'comment-form',
860                'widget-in-use'  => is_active_widget( false, false, 'blog_subscription', true ) ? 'yes' : 'no',
861                'comment_status' => $approved,
862                'server_data'    => jetpack_subscriptions_cherry_pick_server_data(),
863            )
864        );
865
866        /**
867         * Fires on each comment subscription form submission.
868         *
869         * @module subscriptions
870         *
871         * @since 5.5.0
872         *
873         * @param NULL|WP_Error $result Result of form submission: NULL on success, WP_Error otherwise.
874         * @param array $post_ids An array of post IDs that the user subscribed to, 0 means blog subscription.
875         */
876        do_action( 'jetpack_subscriptions_comment_form_submission', $result, $post_ids );
877    }
878
879    /**
880     * Jetpack_Subscriptions::set_cookies()
881     *
882     * Set a cookie to save state on the comment and post subscription checkboxes.
883     *
884     * @param bool $subscribe_to_post Whether the user chose to subscribe to subsequent comments on this post.
885     * @param int  $post_id If $subscribe_to_post is true, the post ID they've subscribed to.
886     * @param bool $subscribe_to_blog Whether the user chose to subscribe to all new posts on the blog.
887     */
888    public function set_cookies( $subscribe_to_post = false, $post_id = null, $subscribe_to_blog = false ) {
889        $post_id = (int) $post_id;
890
891        /** This filter is already documented in core/wp-includes/comment-functions.php */
892        $cookie_lifetime = apply_filters( 'comment_cookie_lifetime', YEAR_IN_SECONDS );
893
894        /**
895         * Filter the Jetpack Comment cookie path.
896         *
897         * @module subscriptions
898         *
899         * @since 2.5.0
900         *
901         * @param string COOKIEPATH Cookie path.
902         */
903        $cookie_path = apply_filters( 'jetpack_comment_cookie_path', COOKIEPATH );
904
905        /**
906         * Filter the Jetpack Comment cookie domain.
907         *
908         * @module subscriptions
909         *
910         * @since 2.5.0
911         *
912         * @param string COOKIE_DOMAIN Cookie domain.
913         */
914        $cookie_domain = apply_filters( 'jetpack_comment_cookie_domain', COOKIE_DOMAIN );
915
916        if ( $subscribe_to_post && $post_id >= 0 ) {
917            setcookie( 'jetpack_comments_subscribe_' . self::$hash . '_' . $post_id, '1', time() + $cookie_lifetime, $cookie_path, $cookie_domain, is_ssl(), true );
918        } else {
919            setcookie( 'jetpack_comments_subscribe_' . self::$hash . '_' . $post_id, '', time() - 3600, $cookie_path, $cookie_domain, is_ssl(), true );
920        }
921
922        if ( $subscribe_to_blog ) {
923            setcookie( 'jetpack_blog_subscribe_' . self::$hash, '1', time() + $cookie_lifetime, $cookie_path, $cookie_domain, is_ssl(), true );
924        } else {
925            setcookie( 'jetpack_blog_subscribe_' . self::$hash, '', time() - 3600, $cookie_path, $cookie_domain, is_ssl(), true );
926        }
927    }
928
929    /**
930     * Set the social_notifications_subscribe option to `off` when the Subscriptions module is activated in the first time.
931     *
932     * @since 8.1
933     *
934     * @return void
935     */
936    public function set_social_notifications_subscribe() {
937        if ( false === get_option( 'social_notifications_subscribe' ) ) {
938            add_option( 'social_notifications_subscribe', 'off' );
939        }
940    }
941
942    /**
943     * Set the featured image in email option to `1` when the Subscriptions module is activated in the first time.
944     *
945     * @return void
946     */
947    public function set_featured_image_in_email_default() {
948        add_option( 'wpcom_featured_image_in_email', 1 );
949    }
950
951    /**
952     * Set the email post to subscribers default option to `1` when the Subscriptions module is activated for the first time.
953     *
954     * @return void
955     */
956    public function set_newsletter_send_default() {
957        add_option( 'wpcom_newsletter_send_default', 1 );
958    }
959
960    /**
961     * Save a flag when a post was ever published.
962     *
963     * It saves the post meta when the post was published and becomes a draft.
964     * Then this meta is used to hide subscription messaging in Publish panel.
965     *
966     * @param string $new_status Tthe "new" post status of the transition when saved.
967     * @param string $old_status The "old" post status of the transition when saved.
968     * @param object $post obj The post object.
969     */
970    public function maybe_set_first_published_status( $new_status, $old_status, $post ) {
971        // Subscriptions are only available for posts so far.
972        if ( ! $post instanceof \WP_Post || 'post' !== $post->post_type ) {
973            return;
974        }
975
976        $was_post_ever_published = get_post_meta( $post->ID, '_jetpack_post_was_ever_published', true );
977        if ( ! $was_post_ever_published && 'publish' === $old_status && 'draft' === $new_status ) {
978            update_post_meta( $post->ID, '_jetpack_post_was_ever_published', true );
979        }
980    }
981
982    /**
983     * Checks if the current user can publish posts.
984     *
985     * @return bool
986     */
987    public function first_published_status_meta_auth_callback() {
988        /**
989         * Filter the capability to view if a post was ever published in the Subscription Module.
990         *
991         * @module subscriptions
992         *
993         * @since 13.4
994         *
995         * @param string $capability User capability needed to view if a post was ever published. Default to publish_posts.
996         */
997        $capability = apply_filters( 'jetpack_subscriptions_post_was_ever_published_capability', 'publish_posts' );
998        if ( current_user_can( $capability ) ) {
999            return true;
1000        }
1001        return false;
1002    }
1003
1004    /**
1005     * Registers the 'post_was_ever_published' post meta for use in the REST API.
1006     */
1007    public function register_post_meta() {
1008        $jetpack_post_was_ever_published = array(
1009            'type'           => 'boolean',
1010            'description'    => __( 'Whether the post was ever published.', 'jetpack' ),
1011            'single'         => true,
1012            'default'        => false,
1013            'show_in_rest'   => array(
1014                'name' => 'jetpack_post_was_ever_published',
1015            ),
1016            'auth_callback'  => array( $this, 'first_published_status_meta_auth_callback' ),
1017            'object_subtype' => 'post', // Subscriptions are only for the post post type so far, so we can limit this meta to posts only.
1018        );
1019
1020        register_meta( 'post', '_jetpack_post_was_ever_published', $jetpack_post_was_ever_published );
1021    }
1022
1023    /**
1024     * Create a Subscribers menu displayed on self-hosted sites.
1025     *
1026     * - It is not displayed on WordPress.com sites.
1027     * - It directs you to Calypso to the existing Subscribers page.
1028     *
1029     * @return void
1030     */
1031    public function add_subscribers_menu() {
1032        /**
1033         * Enables the new in development subscribers in wp-admin dashboard.
1034         *
1035         * @since 9.5.0
1036         *
1037         * @param bool If the new dashboard is enabled. Default false.
1038         */
1039        if ( apply_filters( 'jetpack_wp_admin_subscriber_management_enabled', false ) ) {
1040            return;
1041        }
1042
1043        /*
1044         * Do not display any menu on WoA and WordPress.com Simple sites (unless Classic wp-admin is enabled).
1045         * They already get a menu item under Users via nav-unification.
1046         */
1047        if ( ( new Host() )->is_wpcom_platform() && get_option( 'wpcom_admin_interface' ) !== 'wp-admin' ) {
1048            return;
1049        }
1050
1051        $status = new Status();
1052
1053        /*
1054         * Do not display if we're in Offline mode,
1055         * or if the user is not connected.
1056         */
1057        if (
1058            $status->is_offline_mode()
1059            || ! ( new Connection_Manager( 'jetpack' ) )->is_user_connected()
1060        ) {
1061            return;
1062        }
1063
1064        $blog_id = Connection_Manager::get_site_id( true );
1065
1066        $link = Redirect::get_url(
1067            'jetpack-menu-jetpack-manage-subscribers',
1068            array( 'site' => $blog_id ? $blog_id : $status->get_site_suffix() )
1069        );
1070
1071        Admin_Menu::add_menu(
1072            __( 'Subscribers', 'jetpack' ),
1073            __( 'Subscribers', 'jetpack' ) . ' <span aria-hidden="true">↗</span>',
1074            'manage_options',
1075            esc_url( $link ),
1076            null,
1077            15
1078        );
1079    }
1080
1081    /**
1082     * Record tracks event if categories is created when user enters
1083     * the edit category page through the newsletter settings page.
1084     *
1085     * @return void
1086     */
1087    public function track_newsletter_category_creation() {
1088
1089        // phpcs:disable WordPress.Security.NonceVerification.Missing
1090        if ( empty( $_POST['_wp_http_referer'] ) ) {
1091            return;
1092        }
1093
1094        if ( strpos( sanitize_url( wp_unslash( $_POST['_wp_http_referer'] ) ), 'referer=newsletter-categories' ) > -1 ) {
1095
1096            $parent = filter_var( empty( $_POST['parent'] ) ? 0 : wp_unslash( $_POST['parent'] ), FILTER_SANITIZE_NUMBER_INT );
1097
1098            $is_child_category = $parent > 0;
1099
1100            $tracking = new Automattic\Jetpack\Tracking();
1101            $tracking->tracks_record_event(
1102                wp_get_current_user(),
1103                'jetpack_newsletter_add_category',
1104                array(
1105                    'is_child_category' => $is_child_category,
1106                )
1107            );
1108        }
1109    }
1110}
1111
1112Jetpack_Subscriptions::init();
1113
1114require __DIR__ . '/subscriptions/views.php';
1115require __DIR__ . '/subscriptions/subscribe-modal/class-jetpack-subscribe-modal.php';
1116require __DIR__ . '/subscriptions/subscribe-overlay/class-jetpack-subscribe-overlay.php';
1117require __DIR__ . '/subscriptions/subscribe-floating-button/class-jetpack-subscribe-floating-button.php';
1118require __DIR__ . '/subscriptions/newsletter-widget/class-jetpack-newsletter-dashboard-widget.php';
1119
1120require_once __DIR__ . '/subscriptions/abilities/class-newsletter-abilities.php';
1121\Automattic\Jetpack\Plugin\Abilities\Newsletter_Abilities::init();