Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
61.98% covered (warning)
61.98%
75 / 121
40.00% covered (danger)
40.00%
4 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Subscribe_Modal
65.79% covered (warning)
65.79%
75 / 114
40.00% covered (danger)
40.00%
4 / 10
130.72
0.00% covered (danger)
0.00%
0 / 1
 init
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 get_block_template_part_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 __construct
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 enqueue_assets
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
12
 get_global_styles_background_css
100.00% covered (success)
100.00%
31 / 31
100.00% covered (success)
100.00%
1 / 1
13
 add_subscribe_modal_to_frontend
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 get_block_template_filter
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
4.25
 get_template
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
1
 get_subscribe_template_content
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 should_user_see_modal
66.67% covered (warning)
66.67%
14 / 21
0.00% covered (danger)
0.00%
0 / 1
27.70
1<?php
2/**
3 * Adds support for Jetpack Subscribe Modal feature
4 *
5 * @package automattic/jetpack-mu-wpcom
6 * @since 12.4
7 */
8
9use Automattic\Jetpack\Extensions\Premium_Content\Subscription_Service\Abstract_Token_Subscription_Service;
10use const Automattic\Jetpack\Extensions\Subscriptions\META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS;
11
12/**
13 * Jetpack_Subscribe_Modal class.
14 */
15class Jetpack_Subscribe_Modal {
16    /**
17     * Jetpack_Subscribe_Modal singleton instance.
18     *
19     * @var Jetpack_Subscribe_Modal|null
20     */
21    private static $instance;
22
23    /**
24     * Jetpack_Subscribe_Modal instance init.
25     */
26    public static function init() {
27        if ( self::$instance === null ) {
28            self::$instance = new Jetpack_Subscribe_Modal();
29        }
30
31        return self::$instance;
32    }
33
34    const BLOCK_TEMPLATE_PART_SLUG = 'jetpack-subscribe-modal';
35
36    /**
37     * Returns the block template part ID.
38     *
39     * @return string
40     */
41    public static function get_block_template_part_id() {
42        return get_stylesheet() . '//' . self::BLOCK_TEMPLATE_PART_SLUG;
43    }
44
45    /**
46     * Jetpack_Subscribe_Modal class constructor.
47     */
48    public function __construct() {
49        if ( get_option( 'sm_enabled', false ) ) {
50            add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
51            add_action( 'wp_footer', array( $this, 'add_subscribe_modal_to_frontend' ) );
52        }
53        add_filter( 'get_block_template', array( $this, 'get_block_template_filter' ), 10, 3 );
54    }
55
56    /**
57     * Enqueues JS to load modal.
58     *
59     * @return void
60     */
61    public function enqueue_assets() {
62        if ( $this->should_user_see_modal() ) {
63            wp_enqueue_style( 'subscribe-modal-css', plugins_url( 'subscribe-modal.css', __FILE__ ), array(), JETPACK__VERSION );
64            $background_css = self::get_global_styles_background_css();
65            if ( $background_css ) {
66                wp_add_inline_style( 'subscribe-modal-css', $background_css );
67            }
68            wp_enqueue_script( 'subscribe-modal-js', plugins_url( 'subscribe-modal.js', __FILE__ ), array( 'wp-dom-ready' ), JETPACK__VERSION, true );
69
70            /**
71             * Filter how many milliseconds until the Subscribe Modal appears.
72             *
73             * @module subscriptions
74             *
75             * @since 13.4
76             *
77             * @param int 60000 Time in milliseconds for the Subscribe Modal to appear.
78             */
79            $load_time = absint( apply_filters( 'jetpack_subscribe_modal_load_time', 60000 ) );
80
81            /**
82             * Filter how many percentage of the page should be scrolled before the Subscribe Modal appears.
83             *
84             * @module subscriptions
85             *
86             * @since 13.6
87             *
88             * @param int Percentage of the page scrolled before the Subscribe Modal appears.
89             */
90            $scroll_threshold = absint( apply_filters( 'jetpack_subscribe_modal_scroll_threshold', 50 ) );
91
92            /**
93             * Filter to control the interval at which the subscribe modal is shown to the same user.  The default interval is 24 hours.
94             *
95             * @since 13.7
96             *
97             * @param int 24 Hours before we show the same user the Subscribe Modal to again.
98             */
99            $modal_interval = absint( apply_filters( 'jetpack_subscribe_modal_interval', 24 ) );
100
101            wp_localize_script(
102                'subscribe-modal-js',
103                'Jetpack_Subscriptions',
104                array(
105                    'modalLoadTime'        => $load_time,
106                    'modalScrollThreshold' => $scroll_threshold,
107                    'modalInterval'        => ( $modal_interval * HOUR_IN_SECONDS * 1000 ),
108                    'modalLabel'           => __( 'Subscribe', 'jetpack' ),
109                )
110            );
111        }
112    }
113
114    /**
115     * Gives the modal the site's Global Styles page background, so the text it inherits from the page stays readable.
116     *
117     * @since $$next-version$$
118     *
119     * @return string CSS, or an empty string to keep the stylesheet's background.
120     */
121    public static function get_global_styles_background_css() {
122        // Read the whole tree: for a missing path, wp_get_global_styles() returns every style instead of null.
123        $styles = wp_get_global_styles();
124        // The server cannot tell what a page image shows. Removing a theme's image stores 'none'.
125        $image = $styles['background']['backgroundImage'] ?? null;
126        if ( ! empty( $image ) && 'none' !== $image ) {
127            return '';
128        }
129
130        $declarations = wp_style_engine_get_styles(
131            array(
132                'color'      => array(
133                    'background' => $styles['color']['background'] ?? null,
134                    'gradient'   => $styles['color']['gradient'] ?? null,
135                ),
136                'background' => array( 'gradient' => $styles['background']['gradient'] ?? null ),
137            )
138        )['declarations'] ?? array();
139        foreach ( $declarations as $property => $value ) {
140            // The style engine returns values unfiltered, so only accept those core's CSS filter leaves intact.
141            $declaration = $property . ': ' . $value;
142            if ( esc_html( $declaration ) !== $declaration || safecss_filter_attr( $declaration ) !== $declaration ) {
143                return '';
144            }
145        }
146
147        $css = array();
148        if ( isset( $declarations['background-color'] ) ) {
149            $css[] = '--jetpack-subscribe-modal--page-background: ' . $declarations['background-color'] . ';';
150        }
151        // A color.gradient value is a `background` shorthand, which resets the color the stylesheet sets.
152        if ( isset( $declarations['background'] ) ) {
153            $css[] = 'background: ' . $declarations['background'] . ';';
154            $css[] = 'background-color: var(--jetpack-subscribe-modal--page-background, #fefefe);';
155        }
156        if ( isset( $declarations['background-image'] ) ) {
157            $css[] = 'background-image: ' . $declarations['background-image'] . ';';
158        }
159        if ( ! $css ) {
160            return '';
161        }
162
163        // A saved template whose blocks set their own colors was styled against the light panel.
164        $template = get_block_template( self::get_block_template_part_id(), 'wp_template_part' );
165        if ( $template && 'plugin' !== $template->source && preg_match( '/\bhas-(?:text-color|link-color|inline-color|background)(?![\w-])/', $template->content ) ) {
166            return '';
167        }
168
169        return '.jetpack-subscribe-modal__modal-content { ' . implode( ' ', $css ) . ' }';
170    }
171
172    /**
173     * Adds modal with Subscribe Modal content.
174     *
175     * @return void
176     */
177    public function add_subscribe_modal_to_frontend() {
178        if ( $this->should_user_see_modal() ) { ?>
179                    <div class="jetpack-subscribe-modal">
180                        <div class="jetpack-subscribe-modal__modal-content">
181                            <?php block_template_part( self::BLOCK_TEMPLATE_PART_SLUG ); ?>
182                        </div>
183                    </div>
184            <?php
185        }
186    }
187
188    /**
189     * Makes get_block_template return the WP_Block_Template for the Subscribe Modal.
190     *
191     * @param WP_Block_Template $block_template The block template to be returned.
192     * @param string            $id Template unique identifier (example: theme_slug//template_slug).
193     * @param string            $template_type Template type: `'wp_template'` or '`wp_template_part'`.
194     *
195     * @return WP_Block_Template
196     */
197    public function get_block_template_filter( $block_template, $id, $template_type ) {
198        if ( empty( $block_template ) && $template_type === 'wp_template_part' ) {
199            if ( $id === self::get_block_template_part_id() ) {
200                return $this->get_template();
201            }
202        }
203
204        return $block_template;
205    }
206
207    /**
208     * Returns a custom template for the Subscribe Modal.
209     *
210     * @return WP_Block_Template
211     */
212    public function get_template() {
213        $template                 = new WP_Block_Template();
214        $template->theme          = get_stylesheet();
215        $template->slug           = self::BLOCK_TEMPLATE_PART_SLUG;
216        $template->id             = self::get_block_template_part_id();
217        $template->area           = 'uncategorized';
218        $template->content        = $this->get_subscribe_template_content();
219        $template->source         = 'plugin';
220        $template->type           = 'wp_template_part';
221        $template->title          = __( 'Jetpack Subscribe modal', 'jetpack' );
222        $template->status         = 'publish';
223        $template->has_theme_file = false;
224        $template->is_custom      = true;
225        $template->description    = __( 'A subscribe form that pops up when someone visits your site.', 'jetpack' );
226
227        return $template;
228    }
229
230    /**
231     * Returns the initial content of the Subscribe Modal template.
232     * This can then be edited by the user.
233     *
234     * @return string
235     */
236    public function get_subscribe_template_content() {
237        // translators: %s is the name of the site.
238        $discover_more_from = sprintf( __( 'Discover more from %s', 'jetpack' ), get_bloginfo( 'name' ) );
239        $continue_reading   = __( 'Continue reading', 'jetpack' );
240        $subscribe_text     = __( 'Subscribe now to keep reading and get access to the full archive.', 'jetpack' );
241        $group_block_name   = esc_attr__( 'Subscription pop-up container', 'jetpack' );
242
243        return <<<HTML
244    <!-- wp:group {"metadata":{"name":"$group_block_name"},"style":{"spacing":{"padding":{"top":"32px","bottom":"32px","left":"32px","right":"32px"},"margin":{"top":"0","bottom":"0"}},"border":{"color":"#dddddd","width":"1px"}},"layout":{"type":"constrained","contentSize":"450px"}} -->
245    <div class="wp-block-group has-border-color" style="border-color:#dddddd;border-width:1px;margin-top:0;margin-bottom:0;padding-top:32px;padding-right:32px;padding-bottom:32px;padding-left:32px">
246
247    <!-- wp:heading {"textAlign":"center","style":{"typography":{"fontStyle":"normal","fontWeight":"600","fontSize":"26px"},"layout":{"selfStretch":"fit","flexSize":null},"spacing":{"margin":{"top":"4px","bottom":"10px"}}}} -->
248        <h2 class="wp-block-heading has-text-align-center" style="margin-top:4px;margin-bottom:10px;font-size:26px;font-style:normal;font-weight:600">$discover_more_from</h2>
249        <!-- /wp:heading -->
250
251        <!-- wp:paragraph {"align":"center","style":{"typography":{"fontSize":"15px"},"spacing":{"margin":{"top":"4px","bottom":"0px"}}}} -->
252        <p class='has-text-align-center' style='margin-top:4px;margin-bottom:1em;font-size:15px'>$subscribe_text</p>
253        <!-- /wp:paragraph -->
254
255        <!-- wp:jetpack/subscriptions {"borderRadius":50,"className":"is-style-compact","appSource":"subscribe-modal"} /-->
256
257        <!-- wp:paragraph {"align":"center","style":{"spacing":{"margin":{"top":"20px"}},"typography":{"fontSize":"14px"}},"className":"jetpack-subscribe-modal__close"} -->
258        <p class="has-text-align-center jetpack-subscribe-modal__close" style="margin-top:20px;margin-bottom:0;font-size:14px"><a href="#">$continue_reading</a></p>
259        <!-- /wp:paragraph -->
260    </div>
261    <!-- /wp:group -->
262HTML;
263    }
264
265    /**
266     * Returns true if a site visitor should see
267     * the Subscribe Modal.
268     *
269     * @return bool
270     */
271    public function should_user_see_modal() {
272        // Only show when viewing frontend single post.
273        if ( is_admin() || ! is_singular( 'post' ) ) {
274            return false;
275        }
276
277        // Needed because Elementor editor makes is_admin() return false
278        // See https://coreysalzano.com/wordpress/why-elementor-disobeys-is_admin/
279        // Ignore nonce warning as just checking if is set
280        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
281        if ( isset( $_GET['elementor-preview'] ) ) {
282            return false;
283        }
284
285        // Don't show when previewing blog posts or site's theme
286        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
287        if ( isset( $_GET['preview'] ) || isset( $_GET['theme_preview'] ) || isset( $_GET['customize_preview'] ) || isset( $_GET['hide_banners'] ) ) {
288            return false;
289        }
290
291        // Don't show if one of subscribe query params is set.
292        // They are set when user submits the subscribe form.
293        // The nonce is checked elsewhere before redirect back to this page with query params.
294        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
295        if ( isset( $_GET['subscribe'] ) || isset( $_GET['blogsub'] ) ) {
296            return false;
297        }
298
299        // Don't show if post is not a post, is for subscribers only, or has paywall block
300        global $post;
301        if ( ! $post instanceof WP_Post ) {
302            return false;
303        }
304        if ( defined( 'Automattic\\Jetpack\\Extensions\\Subscriptions\\META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS' ) ) {
305            $access_level = get_post_meta( $post->ID, META_NAME_FOR_POST_LEVEL_ACCESS_SETTINGS, true );
306        } else {
307            $access_level = get_post_meta( $post->ID, '_jetpack_newsletter_access', true );
308        }
309        require_once JETPACK__PLUGIN_DIR . 'extensions/blocks/premium-content/_inc/subscription-service/include.php';
310        $is_accessible_by_everyone = Abstract_Token_Subscription_Service::POST_ACCESS_LEVEL_EVERYBODY === $access_level || empty( $access_level );
311        if ( ! $is_accessible_by_everyone ) {
312            return false;
313        }
314
315        // Don't show if user is subscribed to blog or awaiting subscription confirmation.
316        require_once __DIR__ . '/../views.php';
317        if ( ! class_exists( 'Jetpack_Memberships' ) || Jetpack_Memberships::is_current_user_subscribed() || Jetpack_Memberships::user_is_pending_subscriber() ) {
318            return false;
319        }
320        return true;
321    }
322}
323
324Jetpack_Subscribe_Modal::init();
325
326add_action(
327    'rest_api_switched_to_blog',
328    function () {
329        Jetpack_Subscribe_Modal::init();
330    }
331);