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