Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 526
0.00% covered (danger)
0.00%
0 / 22
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Comments
0.00% covered (danger)
0.00%
0 / 522
0.00% covered (danger)
0.00%
0 / 22
13340
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 __construct
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 set_default_color_theme_based_on_theme_settings
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 setup_globals
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 new_comments_enabled
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 setup_actions
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 setup_filters
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 manage_post_cookie
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
30
 get_avatar
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 comment_reply_link
0.00% covered (danger)
0.00%
0 / 31
0.00% covered (danger)
0.00%
0 / 1
6
 get_blog_token
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 comment_form_before
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 comment_form_after
0.00% covered (danger)
0.00%
0 / 113
0.00% covered (danger)
0.00%
0 / 1
756
 watch_comment_parent
0.00% covered (danger)
0.00%
0 / 60
0.00% covered (danger)
0.00%
0 / 1
30
 pre_comment_on_post
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
210
 retry_submit_comment_form_locally
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
6
 add_comment_meta
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
182
 should_show_subscription_modal
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
42
 get_subscription_modal_data_to_parent
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 subscription_modal_status_track_event
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
30
 capture_comment_duplicate_trigger
0.00% covered (danger)
0.00%
0 / 53
0.00% covered (danger)
0.00%
0 / 1
12
 capture_comment_post_redirect_to_reload_parent_frame
0.00% covered (danger)
0.00%
0 / 89
0.00% covered (danger)
0.00%
0 / 1
30
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Module: Comments
4 *
5 * @package automattic/jetpack
6 */
7
8require __DIR__ . '/base.php';
9use Automattic\Jetpack\Connection\Tokens;
10use Automattic\Jetpack\Status\Host;
11
12if ( ! defined( 'ABSPATH' ) ) {
13    exit( 0 );
14}
15
16/**
17 * Main Comments class
18 *
19 * @package automattic/jetpack
20 * @since   1.4
21 */
22class Jetpack_Comments extends Highlander_Comments_Base {
23
24    /** Variables *************************************************************/
25
26    /**
27     * Possible comment form sources - empty array as default
28     *
29     * @var array
30     */
31    public $id_sources = array();
32
33    /**
34     * Remote comment URL - empty string as default
35     *
36     * @var string
37     */
38    public $signed_url = '';
39
40    /**
41     * The default comment form color scheme - default is light
42     *
43     * @var string
44     * @see ::set_default_color_theme_based_on_theme_settings()
45     */
46    public $default_color_scheme = 'light';
47
48    /** Methods ***************************************************************/
49
50    /**
51     * Initialize class
52     */
53    public static function init() {
54        static $instance = false;
55
56        if ( ! $instance ) {
57            $instance = new Jetpack_Comments();
58        }
59
60        return $instance;
61    }
62
63    /**
64     * Main constructor for Comments
65     *
66     * @since 1.4
67     */
68    public function __construct() {
69        parent::__construct();
70
71        // Comments is loaded.
72
73        /**
74         * Fires after the Jetpack_Comments object has been instantiated
75         *
76         * @module comments
77         *
78         * @since  1.4.0
79         *
80         * @param array $jetpack_comments_loaded First element in array of type Jetpack_Comments
81         */
82        do_action_ref_array( 'jetpack_comments_loaded', array( $this ) );
83        add_action( 'after_setup_theme', array( $this, 'set_default_color_theme_based_on_theme_settings' ), 100 );
84    }
85
86    /**
87     * Set the default comments color theme based on theme settings
88     */
89    public function set_default_color_theme_based_on_theme_settings() {
90        if ( function_exists( 'twentyeleven_get_theme_options' ) ) {
91            $theme_options      = twentyeleven_get_theme_options();
92            $theme_color_scheme = $theme_options['color_scheme'] ?? 'transparent';
93        } else {
94            $theme_color_scheme = get_theme_mod( 'color_scheme', 'transparent' );
95        }
96        // Default for $theme_color_scheme is 'transparent' just so it doesn't match 'light' or 'dark'.
97        // The default for Jetpack's color scheme is still defined above as 'light'.
98
99        if ( false !== stripos( $theme_color_scheme, 'light' ) ) {
100            $this->default_color_scheme = 'light';
101        } elseif ( false !== stripos( $theme_color_scheme, 'dark' ) ) {
102            $this->default_color_scheme = 'dark';
103        }
104    }
105
106    /** Private Methods *******************************************************/
107
108    /**
109     * Set any global variables or class variables
110     *
111     * This is primarily defining the comment form sources.
112     *
113     * @since 1.4
114     */
115    protected function setup_globals() {
116        parent::setup_globals();
117
118        // Sources.
119        $this->id_sources = array(
120            'guest',
121            'jetpack',
122            'wordpress',
123            'facebook',
124        );
125    }
126
127    /**
128     * Whether the rebuilt Jetpack Comments form has taken over from this one.
129     *
130     * Guarded because this file and the jetpack-comments package can land in
131     * either order on a staged deploy.
132     *
133     * @return bool
134     */
135    private static function new_comments_enabled() {
136        return class_exists( '\Automattic\Jetpack\Comments\Comments' )
137            && \Automattic\Jetpack\Comments\Comments::is_enabled();
138    }
139
140    /**
141     * Setup actions for methods in this class
142     *
143     * @since 1.4
144     */
145    protected function setup_actions() {
146        if ( self::new_comments_enabled() ) {
147            return;
148        }
149
150        parent::setup_actions();
151
152        // Selfishly remove everything from the existing comment form.
153        remove_all_actions( 'comment_form_before' );
154
155        // Selfishly add only our actions back to the comment form.
156        add_action( 'comment_form_before', array( $this, 'manage_post_cookie' ) );
157        add_action( 'comment_form_before', array( $this, 'comment_form_before' ) );
158        add_action( 'comment_form_after', array( $this, 'comment_form_after' ), 1 ); // Set very early since we remove everything outputed before our action.
159
160        // Before a comment is posted.
161        add_action( 'pre_comment_on_post', array( $this, 'pre_comment_on_post' ), 1 );
162
163        // After a comment is posted.
164        add_action( 'comment_post', array( $this, 'add_comment_meta' ) );
165    }
166
167    /**
168     * Setup filters for methods in this class
169     *
170     * @since 1.6.2
171     */
172    protected function setup_filters() {
173        if ( self::new_comments_enabled() ) {
174            return;
175        }
176
177        parent::setup_filters();
178
179        add_filter( 'comment_post_redirect', array( $this, 'capture_comment_post_redirect_to_reload_parent_frame' ), 100 );
180        add_filter( 'comment_duplicate_trigger', array( $this, 'capture_comment_duplicate_trigger' ), 100 );
181        add_filter( 'get_avatar', array( $this, 'get_avatar' ), 10, 4 );
182        // Fix comment reply link when `comment_registration` is required.
183        add_filter( 'comment_reply_link', array( $this, 'comment_reply_link' ), 10, 4 );
184    }
185
186    /**
187     * In order for comments to work properly for password-protected posts we need to set `wp-postpass` cookie to SameSite none.
188     */
189    public function manage_post_cookie() {
190        if ( headers_sent() ) {
191            return;
192        }
193
194        $postpass_cookie_key = 'wp-postpass_' . COOKIEHASH;
195
196        if ( empty( $_COOKIE[ $postpass_cookie_key ] ) ) {
197            return;
198        }
199
200        $postpass_cookie_value = sanitize_text_field( wp_unslash( $_COOKIE[ $postpass_cookie_key ] ) );
201
202        if ( empty( $_COOKIE['verbum-wp-postpass'] ) || ( $_COOKIE['verbum-wp-postpass'] !== $postpass_cookie_value ) ) {
203            $expire = apply_filters( 'post_password_expires', time() + 10 * DAY_IN_SECONDS );
204
205            setcookie(
206                $postpass_cookie_key,
207                $postpass_cookie_value,
208                array(
209                    'expires'  => $expire,
210                    'samesite' => 'None',
211                    'path'     => '/',
212                    'domain'   => COOKIE_DOMAIN,
213                    'secure'   => is_ssl(),
214                    'httponly' => false, // phpcs:ignore Jetpack.Functions.SetCookie.FoundNonHTTPOnlyFalse -- @todo Can this be set true?
215                )
216            );
217
218            setcookie(
219                'verbum-wp-postpass',
220                $postpass_cookie_value,
221                array(
222                    'expires'  => $expire,
223                    'samesite' => 'None',
224                    'path'     => '/',
225                    'domain'   => COOKIE_DOMAIN,
226                    'secure'   => is_ssl(),
227                    'httponly' => false, // phpcs:ignore Jetpack.Functions.SetCookie.FoundNonHTTPOnlyFalse -- @todo Can this be set true?
228                )
229            );
230        }
231    }
232
233    /**
234     * Get the comment avatar from Gravatar or Twitter/Facebook.
235     *
236     * Leaving the Twitter reference for legacy comments even though support is no longer offered.
237     *
238     * @since 1.4
239     *
240     * @param string $avatar  Current avatar URL.
241     * @param string $comment Comment for the avatar.
242     * @param int    $size    Size of the avatar.
243     *
244     * @return string New avatar
245     */
246    public function get_avatar( $avatar, $comment, $size ) {
247        if ( ! isset( $comment->comment_post_ID ) || ! isset( $comment->comment_ID ) ) {
248            // it's not a comment - bail.
249            return $avatar;
250        }
251
252        // Detect whether it's a Facebook avatar.
253        $foreign_avatar          = get_comment_meta( $comment->comment_ID, 'hc_avatar', true );
254        $foreign_avatar_hostname = wp_parse_url( $foreign_avatar, PHP_URL_HOST );
255        if ( ! $foreign_avatar_hostname ||
256            ! preg_match( '/\.?(graph\.facebook\.com|twimg\.com)$/', $foreign_avatar_hostname ) ) {
257            return $avatar;
258        }
259
260        // Return the Facebook or Twitter avatar.
261        return preg_replace( '#src=([\'"])[^\'"]+\\1#', 'src=\\1' . esc_url( set_url_scheme( $this->photon_avatar( $foreign_avatar, $size ), 'https' ) ) . '\\1', $avatar );
262    }
263
264    /**
265     * Set comment reply link.
266     * This is to fix the reply link when comment registration is required.
267     *
268     * @param string     $reply_link The HTML markup for the comment reply link.
269     * @param array      $args An array of arguments overriding the defaults.
270     * @param WP_Comment $comment The object of the comment being replied.
271     * @param WP_Post    $post    The WP_Post object.
272     *
273     * @return string New reply link.
274     */
275    public function comment_reply_link( $reply_link, $args, $comment, $post ) {
276        // This is only necessary if comment_registration is required to post comments
277        if ( ! get_option( 'comment_registration' ) ) {
278            return $reply_link;
279        }
280
281        $respond_id = esc_attr( $args['respond_id'] );
282        $add_below  = esc_attr( $args['add_below'] );
283        /* This is to accommodate some themes that add an SVG to the Reply link like twenty-seventeen. */
284        $reply_text  = wp_kses(
285            $args['reply_text'],
286            array(
287                'svg' => array(
288                    'class'           => true,
289                    'aria-hidden'     => true,
290                    'aria-labelledby' => true,
291                    'role'            => true,
292                    'xmlns'           => true,
293                    'width'           => true,
294                    'height'          => true,
295                    'viewbox'         => true,
296                ),
297                'use' => array(
298                    'href'       => true,
299                    'xlink:href' => true,
300                ),
301            )
302        );
303        $before_link = wp_kses( $args['before'], wp_kses_allowed_html( 'post' ) );
304        $after_link  = wp_kses( $args['after'], wp_kses_allowed_html( 'post' ) );
305
306        $reply_url = esc_url( add_query_arg( 'replytocom', $comment->comment_ID . '#' . $respond_id ) );
307
308        return <<<HTML
309            $before_link
310            <a class="comment-reply-link" href="$reply_url" onclick="return addComment.moveForm( '$add_below-$comment->comment_ID', '$comment->comment_ID', '$respond_id', '$post->ID' )">$reply_text</a>
311            $after_link
312HTML;
313    }
314
315    /**
316     * Get the site's blog token.
317     * This can be used to bypass Comments entirely if Jetpack is not properly connected.
318     *
319     * @since 11.2
320     *
321     * @return bool|object False if not properly connected. Object with the blog token if connected.
322     */
323    private function get_blog_token() {
324        $blog_token = ( new Tokens() )->get_access_token();
325        // If we have no token, bail.
326        if ( ! $blog_token || is_wp_error( $blog_token ) ) {
327            return false;
328        }
329
330        return $blog_token;
331    }
332
333    /** Output Methods ********************************************************/
334
335    /**
336     * Start capturing the core comment_form() output
337     *
338     * Comment form output will only be captured if comments are enabled - we return otherwise.
339     *
340     * @since 1.4
341     */
342    public function comment_form_before() {
343        /**
344         * Filters the setting that determines if Jetpack comments should be enabled for
345         * the current post type.
346         *
347         * @module comments
348         *
349         * @since  3.8.1
350         *
351         * @param boolean $return Should comments be enabled?
352         */
353        if ( ! apply_filters( 'jetpack_comment_form_enabled_for_' . get_post_type(), true ) ) {
354            return;
355        }
356
357        // If the Jetpack connection is not healthy, bail.
358        if ( ! $this->get_blog_token() ) {
359            return;
360        }
361
362        // Add some JS to the footer.
363        add_action( 'wp_footer', array( $this, 'watch_comment_parent' ), 100 );
364
365        ob_start();
366    }
367
368    /**
369     * Noop the default comment form output, get some options, and output our
370     * tricked out totally radical comment form.
371     *
372     * @since 1.4
373     */
374    public function comment_form_after() {
375        /** This filter is documented in modules/comments/comments.php */
376        if ( ! apply_filters( 'jetpack_comment_form_enabled_for_' . get_post_type(), true ) ) {
377            return;
378        }
379
380        $blog_token = $this->get_blog_token();
381        // If the Jetpack connection is not healthy, bail.
382        if ( ! $blog_token ) {
383            return;
384        }
385
386        // Throw it all out and drop in our replacement.
387        ob_end_clean();
388
389        if ( in_array( 'subscriptions', Jetpack::get_active_modules(), true ) ) {
390            $stb_enabled = get_option( 'stb_enabled', 1 );
391            $stb_enabled = empty( $stb_enabled ) ? 0 : 1;
392
393            $stc_enabled = get_option( 'stc_enabled', 1 );
394            $stc_enabled = empty( $stc_enabled ) ? 0 : 1;
395        } else {
396            $stb_enabled = 0;
397            $stc_enabled = 0;
398        }
399
400        $params = array(
401            'blogid'                 => Jetpack_Options::get_option( 'id' ),
402            'postid'                 => get_the_ID(),
403            'comment_registration'   => ( get_option( 'comment_registration' ) ? '1' : '0' ), // Need to explicitly send a '1' or a '0' for these.
404            'require_name_email'     => ( get_option( 'require_name_email' ) ? '1' : '0' ),
405            'stc_enabled'            => $stc_enabled,
406            'stb_enabled'            => $stb_enabled,
407            'show_avatars'           => ( get_option( 'show_avatars' ) ? '1' : '0' ),
408            'avatar_default'         => get_option( 'avatar_default' ),
409            'greeting'               => get_option( 'highlander_comment_form_prompt', __( 'Leave a Reply', 'jetpack' ) ),
410            'jetpack_comments_nonce' => wp_create_nonce( 'jetpack_comments_nonce-' . get_the_ID() ),
411            /**
412             * Changes the comment form prompt.
413             *
414             * @module comments
415             *
416             * @since  2.3.0
417             *
418             * @param string $var Default is "Leave a Reply to %s."
419             */
420            'greeting_reply'         => apply_filters(
421                'jetpack_comment_form_prompt_reply',
422                /* translators: %s is the displayed username of the post (or comment) author */
423                __( 'Leave a Reply to %s', 'jetpack' )
424            ),
425            'color_scheme'           => get_option( 'jetpack_comment_form_color_scheme', $this->default_color_scheme ),
426            'lang'                   => get_locale(),
427            'jetpack_version'        => JETPACK__VERSION,
428            'iframe_unique_id'       => wp_unique_id(),
429        );
430
431        // Extra parameters for logged in user.
432        if ( is_user_logged_in() ) {
433            $current_user           = wp_get_current_user();
434            $params['hc_post_as']   = 'jetpack';
435            $params['hc_userid']    = $current_user->ID;
436            $params['hc_username']  = $current_user->display_name;
437            $params['hc_userurl']   = $current_user->user_url;
438            $params['hc_useremail'] = md5( strtolower( trim( $current_user->user_email ) ) );
439            if ( current_user_can( 'unfiltered_html' ) ) {
440                $params['_wp_unfiltered_html_comment'] = wp_create_nonce( 'unfiltered-html-comment_' . get_the_ID() );
441            }
442        } else {
443            $commenter                     = wp_get_current_commenter();
444            $params['show_cookie_consent'] = (int) has_action( 'set_comment_cookies', 'wp_set_comment_cookies' );
445            $params['has_cookie_consent']  = (int) ! empty( $commenter['comment_author_email'] );
446            // Jetpack_Memberships for logged out users only checks for the wp-jp-premium-content-session cookie
447            $params['is_current_user_subscribed'] = class_exists( '\Jetpack_Memberships' ) ? (int) Jetpack_Memberships::is_current_user_subscribed() : 0;
448        }
449
450        list( $token_key ) = explode( '.', $blog_token->secret, 2 );
451        // Prophylactic check: anything else should never happen.
452        if ( $token_key && $token_key !== $blog_token->secret ) {
453            // Is the token a Special Token (@see class.tokens.php)?
454            if ( preg_match( '/^;.\d+;\d+;$/', $token_key, $matches ) ) {
455                // The token key for a Special Token is public.
456                $params['token_key'] = $token_key;
457            } else {
458                /*
459                 * The token key for a Normal Token is public but
460                 * looks like sensitive data. Since there can only be
461                 * one Normal Token per site, avoid concern by
462                 * sending the magic "use the Normal Token" token key.
463                 */
464                $params['token_key'] = Tokens::MAGIC_NORMAL_TOKEN_KEY;
465            }
466        }
467
468        $signature = self::sign_remote_comment_parameters( $params, $blog_token->secret );
469        if ( is_wp_error( $signature ) ) {
470            $signature = 'error';
471        }
472
473        $params['sig'] = $signature;
474        $url_origin    = 'https://jetpack.wordpress.com';
475        $url           = "{$url_origin}/jetpack-comment/?" . http_build_query( $params );
476        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sniff misses the esc_url_raw.
477        $url              = "{$url}#parent=" . rawurlencode( esc_url_raw( set_url_scheme( 'http://' . ( isset( $_SERVER['HTTP_HOST'] ) ? wp_unslash( $_SERVER['HTTP_HOST'] ) : '' ) . ( isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '' ) ) ) );
478        $this->signed_url = $url;
479        $height           = $params['comment_registration'] || is_user_logged_in() ? '315' : '430'; // Iframe can be shorter if we're not allowing guest commenting.
480        $transparent      = ( 'transparent' === $params['color_scheme'] ) ? 'true' : 'false';
481
482        if ( isset( $_GET['replytocom'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
483            $url .= '&replytocom=' . (int) $_GET['replytocom']; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
484        }
485
486        /**
487         * Filter whether the comment title can be displayed.
488         *
489         * @module comments
490         *
491         * @since  4.7.0
492         *
493         * @param bool $show Can the comment be displayed? Default to true.
494         */
495        $show_greeting = apply_filters( 'jetpack_comment_form_display_greeting', true );
496
497        /**
498         * Filter the comment title tag.
499         *
500         * @module comments
501         * @since 12.4
502         *
503         * @param string $comment_reply_title_tag The comment title tag. Default to h3.
504         */
505        $comment_reply_title_tag = apply_filters( 'jetpack_comment_reply_title_tag', 'h3' );
506
507        // The actual iframe (loads comment form from Jetpack server).
508
509        $is_amp = class_exists( Jetpack_AMP_Support::class ) && Jetpack_AMP_Support::is_amp_request();
510        ?>
511
512        <div id="respond" class="comment-respond">
513            <?php
514            if ( true === $show_greeting ) :
515                printf(
516                    '<%1$s id="reply-title" class="comment-reply-title">',
517                    esc_html( $comment_reply_title_tag )
518                );
519
520                comment_form_title(
521                    esc_html( $params['greeting'] ),
522                    esc_html( $params['greeting_reply'] )
523                );
524                echo '<small>';
525                cancel_comment_reply_link( esc_html__( 'Cancel reply', 'jetpack' ) );
526                echo '</small>';
527
528                printf(
529                    '</%1$s>',
530                    esc_html( $comment_reply_title_tag )
531                );
532            endif;
533            ?>
534            <form id="commentform" class="comment-form">
535                <iframe
536                    title="<?php esc_attr_e( 'Comment Form', 'jetpack' ); ?>"
537                    src="<?php echo esc_url( $url ); ?>"
538                    <?php if ( $is_amp ) : ?>
539                        resizable
540                        layout="fixed-height"
541                        height="<?php echo esc_attr( $height ); ?>"
542                    <?php else : ?>
543                        name="jetpack_remote_comment"
544                        style="width:100%; height: <?php echo esc_attr( $height ); ?>px; border:0;"
545                    <?php endif; ?>
546                    class="jetpack_remote_comment"
547                    id="jetpack_remote_comment"
548                    sandbox="allow-same-origin allow-top-navigation allow-scripts allow-forms allow-popups"
549                >
550                    <?php if ( $is_amp ) : ?>
551                        <button overflow><?php esc_html_e( 'Show more', 'jetpack' ); ?></button>
552                    <?php endif; ?>
553                </iframe>
554                <?php if ( ! $is_amp ) : ?>
555                    <!--[if !IE]><!-->
556                    <script>
557                        document.addEventListener('DOMContentLoaded', function () {
558                            var commentForms = document.getElementsByClassName('jetpack_remote_comment');
559                            for (var i = 0; i < commentForms.length; i++) {
560                                commentForms[i].allowTransparency = <?php echo esc_html( $transparent ); ?>;
561                                commentForms[i].scrolling = 'no';
562                            }
563                        });
564                    </script>
565                    <!--<![endif]-->
566                <?php endif; ?>
567            </form>
568        </div>
569
570        <?php // Below is required for comment reply JS to work. ?>
571
572        <input type="hidden" name="comment_parent" id="comment_parent" value="" />
573
574        <?php
575    }
576
577    /**
578     * Add some JS to wp_footer to watch for hierarchical reply parent change
579     *
580     * If AMP is enabled, we don't make any changes.
581     *
582     * @since 1.4
583     */
584    public function watch_comment_parent() {
585        if ( class_exists( Jetpack_AMP_Support::class ) && Jetpack_AMP_Support::is_amp_request() ) {
586            // @todo Implement AMP support.
587            return;
588        }
589        ?>
590        <script type="text/javascript">
591            (function () {
592                const iframe = document.getElementById( 'jetpack_remote_comment' );
593                <?php if ( get_option( 'thread_comments' ) && get_option( 'thread_comments_depth' ) ) : ?>
594                const watchReply = function() {
595                    // Check addComment._Jetpack_moveForm to make sure we don't monkey-patch twice.
596                    if ( 'undefined' !== typeof addComment && ! addComment._Jetpack_moveForm ) {
597                        // Cache the Core function.
598                        addComment._Jetpack_moveForm = addComment.moveForm;
599                        const commentParent = document.getElementById( 'comment_parent' );
600                        const cancel = document.getElementById( 'cancel-comment-reply-link' );
601
602                        function tellFrameNewParent ( commentParentValue ) {
603                            const url = new URL( iframe.src );
604                            if ( commentParentValue ) {
605                                url.searchParams.set( 'replytocom', commentParentValue )
606                            } else {
607                                url.searchParams.delete( 'replytocom' );
608                            }
609                            if( iframe.src !== url.href ) {
610                                iframe.src = url.href;
611                            }
612                        };
613
614                        cancel.addEventListener( 'click', function () {
615                            tellFrameNewParent( false );
616                        } );
617
618                        addComment.moveForm = function ( _, parentId ) {
619                            tellFrameNewParent( parentId );
620                            return addComment._Jetpack_moveForm.apply( null, arguments );
621                        };
622                    }
623                }
624                document.addEventListener( 'DOMContentLoaded', watchReply );
625                // In WP 6.4+, the script is loaded asynchronously, so we need to wait for it to load before we monkey-patch the functions it introduces.
626                document.querySelector('#comment-reply-js')?.addEventListener( 'load', watchReply );
627
628                <?php endif; ?>
629                
630                const commentIframes = document.getElementsByClassName('jetpack_remote_comment');
631
632                window.addEventListener('message', function(event) {
633                    if (event.origin !== 'https://jetpack.wordpress.com') {
634                        return;
635                    }
636
637                    if (!event?.data?.iframeUniqueId && !event?.data?.height) {
638                        return;
639                    }
640
641                    const eventDataUniqueId = event.data.iframeUniqueId;
642
643                    // Change height for the matching comment iframe
644                    for (let i = 0; i < commentIframes.length; i++) {
645                        const iframe = commentIframes[i];
646                        const url = new URL(iframe.src);
647                        const iframeUniqueIdParam = url.searchParams.get('iframe_unique_id');
648                        if (iframeUniqueIdParam == event.data.iframeUniqueId) {
649                            iframe.style.height = event.data.height + 'px';
650                            return;
651                        }
652                    }
653                });
654            })();
655        </script>
656        <?php
657    }
658
659    /**
660     * Verify the hash included in remote comments.
661     *
662     * If the Jetpack token is missing we return nothing,
663     * and if the token is unknown or invalid, or comments not allowed, an error is returned.
664     *
665     * @since 1.4
666     */
667    public function pre_comment_on_post() {
668        $post_array = stripslashes_deep( $_POST );
669
670        // Bail if missing the Jetpack token.
671        if ( ! isset( $post_array['sig'] ) || ! isset( $post_array['token_key'] ) || ! is_string( $post_array['sig'] ) ) {
672            unset( $_POST['hc_post_as'] );
673            return;
674        }
675
676        if ( empty( $post_array['jetpack_comments_nonce'] ) || ! wp_verify_nonce( $post_array['jetpack_comments_nonce'], "jetpack_comments_nonce-{$post_array['comment_post_ID']}" ) ) {
677            if ( ! isset( $_GET['only_once'] ) ) {
678                self::retry_submit_comment_form_locally();
679            }
680            wp_die( esc_html__( 'Nonce verification failed.', 'jetpack' ), 400 );
681        }
682
683        if ( is_string( $post_array['hc_avatar'] ) && str_contains( $post_array['hc_avatar'], '.gravatar.com' ) ) {
684            $post_array['hc_avatar'] = htmlentities( $post_array['hc_avatar'], ENT_COMPAT );
685        }
686
687        $blog_token = ( new Tokens() )->get_access_token( false, $post_array['token_key'] );
688        if ( ! $blog_token || is_wp_error( $blog_token ) ) {
689            wp_die( esc_html__( 'Unknown security token.', 'jetpack' ), 400 );
690        }
691        $check = self::sign_remote_comment_parameters( $post_array, $blog_token->secret );
692        if ( is_wp_error( $check ) ) {
693            wp_die( esc_html( $check ) );
694        }
695
696        // Bail if token is expired or not valid.
697        if ( ! hash_equals( $check, $post_array['sig'] ) ) {
698            wp_die( esc_html__( 'Invalid security token.', 'jetpack' ), 400 );
699        }
700
701        /** This filter is documented in modules/comments/comments.php */
702        if ( ! apply_filters( 'jetpack_comment_form_enabled_for_' . get_post_type( $post_array['comment_post_ID'] ), true ) ) {
703            // In case the comment POST is legit, but the comments are
704            // now disabled, we don't allow the comment.
705
706            wp_die( esc_html__( 'Comments are not allowed.', 'jetpack' ), 403 );
707        }
708    }
709
710    /**
711     * Handle Jetpack Comments POST requests: process the comment form, then client-side POST the results to the self-hosted blog
712     *
713     * This function exists because when we submit the form via the jetpack.wordpress.com iframe
714     * in Chrome the request comes in to Jetpack but for some reason the request doesn't have access to cookies yet.
715     * By submitting the form again locally with the same data the process works as expected.
716     *
717     * @return never
718     */
719    public function retry_submit_comment_form_locally() {
720        // We are not doing any validation here since all the validation will be done again by pre_comment_on_post().
721        // phpcs:ignore WordPress.Security.NonceVerification.Missing
722        $comment_data = stripslashes_deep( $_POST );
723        ?>
724        <!DOCTYPE html>
725        <html>
726        <head>
727        <meta charset="utf-8">
728        <title><?php echo esc_html__( 'Submitting Comment', 'jetpack' ); ?></title>
729        <style type="text/css">
730            body {
731                display: table;
732                width: 100%;
733                height: 60%;
734                position: absolute;
735                top: 0;
736                left: 0;
737                overflow: hidden;
738                color: #333;
739            }
740            .jetpack-comment-spinner {
741                display: table-cell;
742                vertical-align: middle;
743                text-align: center;
744            }
745        </style>
746        </head>
747        <body>
748        <div class="jetpack-comment-spinner">
749            <?php
750            require_once JETPACK__PLUGIN_DIR . '_inc/lib/class-jetpack-spinner.php';
751            echo Jetpack_Spinner::render( 28 ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- static SVG markup.
752            ?>
753        </div>
754        <form id="jetpack-remote-comment-post-form" action="<?php echo esc_url( get_site_url() ); ?>/wp-comments-post.php?for=jetpack&only_once=true" method="POST">
755            <?php foreach ( $comment_data as $key => $val ) : ?>
756                <input type="hidden" name="<?php echo esc_attr( $key ); ?>" value="<?php echo esc_attr( $val ); ?>" />
757            <?php endforeach; ?>
758        </form>
759
760        <script type="text/javascript">
761            document.getElementById("jetpack-remote-comment-post-form").submit();
762        </script>
763        </body>
764        </html>
765        <?php
766        exit( 0 );
767    }
768
769    /** Capabilities **********************************************************/
770
771    /**
772     * Add some additional comment meta after comment is saved about what
773     * service the comment is from, the avatar, user_id, etc...
774     *
775     * @since 1.4
776     *
777     * @param int $comment_id The comment ID.
778     */
779    public function add_comment_meta( $comment_id ) {
780        $comment_meta = array();
781
782        // phpcs:disable WordPress.Security.NonceVerification.Missing
783        switch ( $this->is_highlander_comment_post() ) {
784            case 'facebook':
785                $comment_meta['hc_post_as']         = 'facebook';
786                $comment_meta['hc_avatar']          = isset( $_POST['hc_avatar'] ) ? filter_var( wp_unslash( $_POST['hc_avatar'] ) ) : null;
787                $comment_meta['hc_foreign_user_id'] = isset( $_POST['hc_userid'] ) ? filter_var( wp_unslash( $_POST['hc_userid'] ) ) : null;
788                break;
789
790            // phpcs:ignore WordPress.WP.CapitalPDangit
791            case 'wordpress':
792                // phpcs:ignore WordPress.WP.CapitalPDangit
793                $comment_meta['hc_post_as']         = 'wordpress';
794                $comment_meta['hc_avatar']          = isset( $_POST['hc_avatar'] ) ? filter_var( wp_unslash( $_POST['hc_avatar'] ) ) : null;
795                $comment_meta['hc_foreign_user_id'] = isset( $_POST['hc_userid'] ) ? filter_var( wp_unslash( $_POST['hc_userid'] ) ) : null;
796                $comment_meta['hc_wpcom_id_sig']    = isset( $_POST['hc_wpcom_id_sig'] ) ? filter_var( wp_unslash( $_POST['hc_wpcom_id_sig'] ) ) : null; // since 1.9.
797                break;
798
799            case 'jetpack':
800                $comment_meta['hc_post_as']         = 'jetpack';
801                $comment_meta['hc_avatar']          = isset( $_POST['hc_avatar'] ) ? filter_var( wp_unslash( $_POST['hc_avatar'] ) ) : null;
802                $comment_meta['hc_foreign_user_id'] = isset( $_POST['hc_userid'] ) ? filter_var( wp_unslash( $_POST['hc_userid'] ) ) : null;
803                break;
804
805        }
806        // phpcs:enable WordPress.Security.NonceVerification.Missing
807
808        // Bail if no extra comment meta.
809        if ( empty( $comment_meta ) ) {
810            return;
811        }
812
813        // Loop through extra meta and add values.
814        foreach ( $comment_meta as $key => $value ) {
815            add_comment_meta( $comment_id, $key, $value, true );
816        }
817    }
818
819    /**
820     * Should show the subscription modal
821     *
822     * @return boolean
823     */
824    public function should_show_subscription_modal() {
825
826        // Not allow it to run on self-hosted or simple sites
827        if ( ! ( new Host() )->is_wpcom_platform() || ( new Host() )->is_wpcom_simple() ) {
828            return false;
829        }
830
831        // phpcs:disable WordPress.Security.NonceVerification.Missing
832        $is_current_user_subscribed = isset( $_POST['is_current_user_subscribed'] ) ? filter_var( wp_unslash( $_POST['is_current_user_subscribed'] ) ) : null;
833
834        // Atomic sites with jetpack_verbum_subscription_modal option enabled
835        $modal_enabled = ( new Host() )->is_woa_site() && get_option( 'jetpack_verbum_subscription_modal', true );
836
837        return $modal_enabled && ! $is_current_user_subscribed;
838    }
839
840    /**
841     * Get the data to send as an event to the parent window on subscription modal
842     *
843     * @param string $url url to redirect to.
844     *
845     * @return array
846     */
847    public function get_subscription_modal_data_to_parent( $url ) {
848        // phpcs:ignore WordPress.Security.NonceVerification.Missing
849        $current_user_email = isset( $_POST['email'] ) ? filter_var( wp_unslash( $_POST['email'] ) ) : null;
850        // phpcs:ignore WordPress.Security.NonceVerification.Missing
851        $post_id = isset( $_POST['comment_post_ID'] ) ? filter_var( wp_unslash( $_POST['comment_post_ID'] ) ) : null;
852        return array(
853            'url'          => $url,
854            'email'        => $current_user_email,
855            'blog_id'      => esc_attr( \Jetpack_Options::get_option( 'id' ) ),
856            'post_id'      => esc_attr( $post_id ),
857            'lang'         => esc_attr( get_locale() ),
858            'is_logged_in' => isset( $_POST['hc_userid'] ),
859        );
860    }
861
862    /**
863     * Track the hidden event for the subscription modal
864     */
865    public function subscription_modal_status_track_event() {
866        $tracking_event = 'hidden_disabled';
867        // Not allow it to run on self-hosted or simple sites
868        if ( ! ( new Host() )->is_wpcom_platform() || ( new Host() )->is_wpcom_simple() ) {
869            $tracking_event = 'hidden_self_hosted';
870        }
871
872        // phpcs:disable WordPress.Security.NonceVerification.Missing
873        $is_current_user_subscribed = isset( $_POST['is_current_user_subscribed'] ) ? filter_var( wp_unslash( $_POST['is_current_user_subscribed'] ) ) : null;
874
875        if ( $is_current_user_subscribed ) {
876            $tracking_event = 'hidden_already_subscribed';
877        }
878
879        $jetpack = Jetpack::init();
880        // $jetpack->stat automatically prepends the stat group with 'jetpack-'
881        $jetpack->stat( 'subscribe-modal-comm', $tracking_event );
882        $jetpack->do_stats( 'server_side' );
883    }
884
885    /**
886     * Catch the duplicated comment error and show a custom error page
887     *
888     * @return never
889     */
890    public function capture_comment_duplicate_trigger() {
891        if ( ! isset( $_GET['for'] ) || 'jetpack' !== $_GET['for'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
892            exit( 0 );
893        }
894
895        ?>
896        <!DOCTYPE html>
897        <html <?php language_attributes(); ?>>
898        <!--<![endif]-->
899        <head>
900            <meta charset="<?php bloginfo( 'charset' ); ?>" />
901            <title>
902                <?php
903                    wp_kses_post(
904                        printf(
905                            /* translators: %s is replaced by an ellipsis */
906                            __( 'Submitting Comment%s', 'jetpack' ), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
907                            '&hellip;'
908                        )
909                    );
910                ?>
911                </title>
912            <style type="text/css">
913                body {
914                    display: table;
915                    width: 100%;
916                    height: 60%;
917                    position: absolute;
918                    top: 0;
919                    left: 0;
920                    overflow: hidden;
921                    color: #333;
922                    padding-top: 3%;
923                }
924                div {
925                    text-align: left;
926                    margin: 0;
927                    padding: 0;
928                    display: table-cell;
929                    vertical-align: top;
930                    font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", sans-serif;
931                    font-weight: normal;
932                }
933
934                h3 {
935                    margin: 0;
936                    padding-bottom: 3%;
937                    font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", sans-serif;
938                    font-weight: normal;
939                }
940                a {
941                    text-decoration: underline;
942                    color: #333 !important;
943                }
944            </style>
945        </head>
946        <body>
947        <div>
948            <h3>
949                <?php
950                    esc_html_e( 'Duplicate comment detected; it looks as though you’ve already said that!', 'jetpack' );
951                ?>
952            </h3>
953            <a href="javascript:backToComments()"><?php esc_html_e( '&laquo; Back', 'jetpack' ); ?></a>
954        </div>
955        <script type="text/javascript">
956            function backToComments() {
957                const test = regexp => {
958                        return regexp.test(navigator.userAgent);
959                };
960                if (test(/chrome|chromium|crios|safari|edg/i)) {
961                        history.go(-2);
962                        return;
963                }
964                history.back();
965            }
966        </script>
967
968        </body>
969        </html>
970        <?php
971        exit( 0 );
972    }
973
974    /**
975     * POST the submitted comment to the iframe
976     *
977     * @param string $url The comment URL origin.
978     */
979    public function capture_comment_post_redirect_to_reload_parent_frame( $url ) {
980        if ( ! isset( $_GET['for'] ) || 'jetpack' !== $_GET['for'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
981            return $url;
982        }
983
984        $should_show_subscription_modal = $this->should_show_subscription_modal();
985
986        // Track event when not showing the subscription modal
987        if ( ! $should_show_subscription_modal ) {
988            $this->subscription_modal_status_track_event();
989        }
990        ?>
991        <!DOCTYPE html>
992        <html <?php language_attributes(); ?>>
993        <!--<![endif]-->
994        <head>
995            <meta charset="<?php bloginfo( 'charset' ); ?>" />
996            <title>
997                <?php
998                    wp_kses_post(
999                        printf(
1000                            /* translators: %s is replaced by an ellipsis */
1001                            __( 'Submitting Comment%s', 'jetpack' ), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
1002                            '&hellip;'
1003                        )
1004                    );
1005                ?>
1006                </title>
1007            <style type="text/css">
1008                body {
1009                    display: table;
1010                    width: 100%;
1011                    height: 60%;
1012                    position: absolute;
1013                    top: 0;
1014                    left: 0;
1015                    overflow: hidden;
1016                    color: #333;
1017                    padding-top: 3%;
1018                }
1019
1020                h3 {
1021                    text-align: center;
1022                    margin: 0;
1023                    padding: 0;
1024                    display: table-cell;
1025                    vertical-align: top;
1026                    font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", sans-serif;
1027                    font-weight: normal;
1028                }
1029
1030                .hidden {
1031                    opacity: 0;
1032                }
1033
1034                h3 span {
1035                    -moz-transition-property: opacity;
1036                    -moz-transition-duration: 1s;
1037                    -moz-transition-timing-function: ease-in-out;
1038
1039                    -webkit-transition-property: opacity;
1040                    -webkit-transition-duration: 1s;
1041                    -webbit-transition-timing-function: ease-in-out;
1042
1043                    -o-transition-property: opacity;
1044                    -o-transition-duration: 1s;
1045                    -o-transition-timing-function: ease-in-out;
1046
1047                    -ms-transition-property: opacity;
1048                    -ms-transition-duration: 1s;
1049                    -ms-transition-timing-function: ease-in-out;
1050
1051                    transition-property: opacity;
1052                    transition-duration: 1s;
1053                    transition-timing-function: ease-in-out;
1054                }
1055            </style>
1056        </head>
1057        <body>
1058        <?php if ( ! $should_show_subscription_modal ) { ?>
1059        <h3>
1060            <?php
1061                wp_kses_post(
1062                    printf(
1063                        /* translators: %s is replaced by HTML markup to include an ellipsis */
1064                        __( 'Submitting Comment%s', 'jetpack' ), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
1065                        '<span id="ellipsis" class="hidden">&hellip;</span>'
1066                    )
1067                );
1068            ?>
1069        </h3>
1070        <script type="text/javascript">
1071            try {
1072                window.parent.location.href = <?php echo wp_json_encode( $url, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?>;
1073                window.parent.location.reload( true );
1074            } catch (e) {
1075                window.location.href = <?php echo wp_json_encode( $url, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?>;
1076                window.location.reload( true );
1077            }
1078            ellipsis = document.getElementById('ellipsis');
1079
1080            function toggleEllipsis() {
1081                ellipsis.className = ellipsis.className ? '' : 'hidden';
1082            }
1083
1084            setInterval(toggleEllipsis, 1200);
1085        </script>
1086        <?php } else { ?>
1087        <h3>
1088            <?php
1089                wp_kses_post(
1090                    print __( 'Comment sent', 'jetpack' ) // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
1091                );
1092            ?>
1093        </h3>
1094        <script type="text/javascript">
1095            if ( window.parent && window.parent !== window ) {
1096
1097                window.parent.postMessage(
1098                    {
1099                        type: 'subscriptionModalShow',
1100                        data: <?php echo wp_json_encode( $this->get_subscription_modal_data_to_parent( $url ), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?>,
1101                    },
1102                    window.location.origin
1103                );
1104            }
1105        </script>
1106        <?php } ?>
1107        </body>
1108        </html>
1109        <?php
1110        exit( 0 );
1111    }
1112}
1113
1114Jetpack_Comments::init();