Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 347
0.00% covered (danger)
0.00%
0 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
Verbum_Comments
0.00% covered (danger)
0.00%
0 / 343
0.00% covered (danger)
0.00%
0 / 15
7482
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
12
 get_form_action
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 verbum_render_element
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 get_color_scheme
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 enqueue_assets
0.00% covered (danger)
0.00%
0 / 154
0.00% covered (danger)
0.00%
0 / 1
600
 comment_form_defaults
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
12
 comment_reply_link
0.00% covered (danger)
0.00%
0 / 33
0.00% covered (danger)
0.00%
0 / 1
6
 comment_form_default_fields
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 check_comment_allowed
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
90
 add_verbum_meta_data
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
240
 hidden_fields
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
56
 should_load_gutenberg_comments
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 should_show_subscription_modal
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 subscription_modal_status
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 add_jetpack_script_data
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2/**
3 * Plugin Name: Verbum Comments Experience
4 * Description: Preact app for commenting on WordPress.com sites
5 * Author: Vertex
6 * Text Domain: jetpack-mu-wpcom
7 *
8 * @package automattic/jetpack-mu-wpcom
9 */
10
11namespace Automattic\Jetpack;
12
13require_once __DIR__ . '/assets/class-wpcom-rest-api-v2-verbum-auth.php';
14require_once __DIR__ . '/assets/class-wpcom-rest-api-v2-verbum-oembed.php';
15require_once __DIR__ . '/assets/class-verbum-gutenberg-editor.php';
16require_once __DIR__ . '/assets/class-verbum-block-utils.php';
17
18/**
19 * Verbum Comments Experience
20 *
21 * This file loads the Verbum Comment user experience on WordPress.com and Jetpack sites.
22 *
23 * @phan-constructor-used-for-side-effects
24 */
25class Verbum_Comments {
26    /**
27     * Internal reference for the current blog id.
28     *
29     * @var int
30     */
31    public $blog_id;
32
33    /**
34     * Comment forms can appear anywhere (page, post, query loop, etc), there is no reliable way to determine if there are comments on the page,
35     * So we hook into `comment_form_before` and set this flag to true when a comment form is found.
36     *
37     * @var bool
38     */
39    public $should_enqueue_assets = false;
40
41    /**
42     * Class constructor
43     */
44    public function __construct() {
45        $this->blog_id = get_current_blog_id();
46
47        // Jetpack loads the app via an iframe, so we need to get the blog id from the query string.
48        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
49        if ( isset( $_GET['blogid'] ) ) {
50            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
51            $this->blog_id = intval( $_GET['blogid'] );
52        }
53
54        add_action(
55            'comment_form_before',
56            function () {
57                $this->should_enqueue_assets = true;
58            }
59        );
60
61        // Selfishly remove everything from the existing comment form
62        add_filter( 'comment_form_field_comment', '__return_false', 11 );
63        add_filter( 'comment_form_logged_in', '__return_empty_string' );
64        add_filter( 'comment_form_defaults', array( $this, 'comment_form_defaults' ), 20 );
65        remove_action( 'comment_form', 'subscription_comment_form' );
66        remove_all_filters( 'comment_form_default_fields' );
67        add_filter( 'comment_form_default_fields', array( $this, 'comment_form_default_fields' ) );
68
69        // Fix comment reply link when `comment_registration` is required.
70        add_filter( 'comment_reply_link', array( $this, 'comment_reply_link' ), 10, 4 );
71
72        // Add Verbum.
73        add_action( 'comment_form_must_log_in_after', array( $this, 'verbum_render_element' ) );
74        add_filter( 'comment_form_submit_field', array( $this, 'verbum_render_element' ) );
75        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
76
77        // Do things before the comment is accepted.
78        add_action( 'pre_comment_on_post', array( $this, 'check_comment_allowed' ), 10, 1 );
79
80        // After the comment is saved, we add meta data to the comment.
81        add_action( 'comment_post', array( $this, 'add_verbum_meta_data' ) );
82
83        // Load the Gutenberg editor for comments.
84        if (
85            $this->should_load_gutenberg_comments()
86        ) {
87            new \Verbum_Gutenberg_Editor();
88        }
89
90        // Filter to ensure JetpackScriptData.site.host and is_wpcom_platform is set, to ensure Jetpack blocks work as expected via Verbum Comments.
91        add_filter( 'jetpack_public_js_script_data', array( $this, 'add_jetpack_script_data' ), 10, 1 );
92    }
93
94    /**
95     * Get the comment form action url
96     */
97    public function get_form_action() {
98        return is_jetpack_comments() ?
99            esc_url_raw( http() . '://' . JETPACK_SERVER__DOMAIN . '/jetpack-comment/' ) : site_url( '/wp-comments-post.php' );
100    }
101
102    /**
103     * Load the div where Verbum app is rendered.
104     */
105    public function verbum_render_element() {
106        $comment_url = $this->get_form_action();
107        $verbum      = '<div class="comment-form__verbum ' . esc_attr( $this->get_color_scheme() ) . '"></div>' . $this->hidden_fields();
108
109        // If the blog requires login, Verbum need to be wrapped in a <form> to work.
110        // Verbum is given `mustLogIn` to handle the login flow.
111        if ( get_option( 'comment_registration' ) && ! is_user_logged_in() ) {
112            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
113            echo "<form action=\"$comment_url\" method=\"post\" id=\"commentform\" class=\"comment-form\">$verbum</form>";
114        } else {
115            return $verbum;
116        }
117    }
118
119    /**
120     * Get the comment form color scheme. The option is synced from Jetpack sites, so it is untrusted.
121     *
122     * @return string
123     */
124    private function get_color_scheme() {
125        $color_scheme = get_blog_option( $this->blog_id, 'jetpack_comment_form_color_scheme' );
126
127        // Default to transparent because it is more adaptable than white or dark.
128        return in_array( $color_scheme, array( 'light', 'dark', 'transparent' ), true ) ? $color_scheme : 'transparent';
129    }
130
131    /**
132     * Enqueue Assets
133     */
134    public function enqueue_assets() {
135        if ( ! \Verbum_Block_Utils::should_show_verbum_comments() && ! $this->should_enqueue_assets ) {
136            return;
137        }
138
139        $connect_url      = site_url( '/public.api/connect/?action=request' );
140        $primary_redirect = get_primary_redirect();
141
142        if ( strpos( $primary_redirect, '.wordpress.com' ) === false ) {
143            $connect_url = add_query_arg( 'domain', $primary_redirect, $connect_url );
144        } else {
145            $connect_url = add_query_arg( 'from_comments', 'yes', $connect_url );
146        }
147
148        // Enqueue styles and scripts
149        Assets::register_script(
150            'verbum',
151            '../../build/verbum-comments/verbum-comments.js',
152            __FILE__,
153            array(
154                'strategy'  => 'defer',
155                'in_footer' => true,
156            )
157        );
158
159        wp_enqueue_script( 'wp-i18n' );
160
161        wp_enqueue_style( 'verbum' );
162        \WP_Enqueue_Dynamic_Script::enqueue_script( 'verbum' );
163
164        // Enqueue settings separately since the main script is dynamic.
165        // We need the VerbumComments object to be available before the main script is loaded.
166        wp_register_script(
167            'verbum-settings',
168            false,
169            array(),
170            null, // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- No script, so no version needed.
171            array(
172                'strategy'  => 'defer',
173                'in_footer' => true,
174            )
175        );
176
177        $blog_details    = get_blog_details( $this->blog_id );
178        $is_blog_atomic  = is_blog_atomic( $blog_details );
179        $is_blog_jetpack = is_blog_jetpack( $blog_details );
180
181        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
182        $subscribe_to_blog = isset( $_GET['stb_enabled'] ) ? boolval( $_GET['stb_enabled'] ) : false;
183        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
184        $subscribe_to_comment = isset( $_GET['stc_enabled'] ) ? boolval( $_GET['stc_enabled'] ) : false;
185
186        // If it is simple, we set it to true. Simple sites return inconsistent results.
187        if ( ! $is_blog_atomic && ! $is_blog_jetpack ) {
188            $subscribe_to_blog    = true;
189            $subscribe_to_comment = true;
190        }
191
192        // Jetpack Comments client side logged in user data
193        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
194        $__get                        = stripslashes_deep( $_GET );
195        $email_hash                   = isset( $__get['hc_useremail'] ) && is_string( $__get['hc_useremail'] ) ? $__get['hc_useremail'] : '';
196        $jetpack_username             = isset( $__get['hc_username'] ) && is_string( $__get['hc_username'] ) ? $__get['hc_username'] : '';
197        $jetpack_user_id              = isset( $__get['hc_userid'] ) && is_numeric( $__get['hc_userid'] ) ? (int) $__get['hc_userid'] : 0;
198        $jetpack_signature            = isset( $__get['sig'] ) && is_string( $__get['sig'] ) ? $__get['sig'] : '';
199        $iframe_unique_id             = isset( $__get['iframe_unique_id'] ) && is_numeric( $__get['iframe_unique_id'] ) ? (int) $__get['iframe_unique_id'] : 0;
200        list( $jetpack_avatar )       = wpcom_get_avatar_url( "$email_hash@md5.gravatar.com" );
201        $comment_registration_enabled = boolval( get_blog_option( $this->blog_id, 'comment_registration' ) );
202        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
203        $post_id = isset( $_GET['postid'] ) ? intval( $_GET['postid'] ) : get_queried_object_id();
204        $locale  = get_locale();
205
206        $css_mtime        = filemtime( ABSPATH . '/widgets.wp.com/verbum-block-editor/block-editor.css' );
207        $js_mtime         = filemtime( ABSPATH . '/widgets.wp.com/verbum-block-editor/block-editor.min.js' );
208        $vbe_cache_buster = max( $js_mtime, $css_mtime );
209
210        // Only users with unfiltered_html get this signed nonce, the closest signed proxy for admin.
211        $retirement_notice_url = '';
212        if ( ! $is_blog_atomic && is_jetpack_comments() && ! empty( $__get['_wp_unfiltered_html_comment'] ) ) {
213            $retirement_notice_url = esc_url_raw( get_admin_url( $this->blog_id, 'plugins.php' ) );
214        }
215
216        $hovercard_i18n = array(
217            'Edit your profile â†’'      => __( 'Edit your profile â†’', 'jetpack-mu-wpcom' ),
218            'View profile â†’'           => __( 'View profile â†’', 'jetpack-mu-wpcom' ),
219            'Contact'                  => __( 'Contact', 'jetpack-mu-wpcom' ),
220            'Send money'               => __( 'Send money', 'jetpack-mu-wpcom' ),
221            'Gravatar not found.'      => __( 'Gravatar not found.', 'jetpack-mu-wpcom' ),
222            'This profile is private.' => __( 'This profile is private.', 'jetpack-mu-wpcom' ),
223            'Too Many Requests.'       => __( 'Too Many Requests.', 'jetpack-mu-wpcom' ),
224            'Internal Server Error.'   => __( 'Internal Server Error.', 'jetpack-mu-wpcom' ),
225            'Sorry, we are unable to load this Gravatar profile.' => __( 'Sorry, we are unable to load this Gravatar profile.', 'jetpack-mu-wpcom' ),
226        );
227
228        wp_add_inline_script(
229            'verbum-settings',
230            'window.VerbumComments = ' . wp_json_encode(
231                array(
232                    'Log in or provide your name and email to leave a reply.' => __( 'Log in or provide your name and email to leave a reply.', 'jetpack-mu-wpcom' ),
233                    'Log in or provide your name and email to leave a comment.' => __( 'Log in or provide your name and email to leave a comment.', 'jetpack-mu-wpcom' ),
234                    'Receive web and mobile notifications for posts on this site.' => __( 'Receive web and mobile notifications for posts on this site.', 'jetpack-mu-wpcom' ),
235                    'Name'                               => __( 'Name', 'jetpack-mu-wpcom' ),
236                    'Email (address never made public)'  => __( 'Email (address never made public)', 'jetpack-mu-wpcom' ),
237                    'Website (optional)'                 => __( 'Website (optional)', 'jetpack-mu-wpcom' ),
238                    'Leave a reply. (log in optional)'   => __( 'Leave a reply. (log in optional)', 'jetpack-mu-wpcom' ),
239                    'Leave a comment. (log in optional)' => __( 'Leave a comment. (log in optional)', 'jetpack-mu-wpcom' ),
240                    'Log in to leave a reply.'           => __( 'Log in to leave a reply.', 'jetpack-mu-wpcom' ),
241                    'Log in to leave a comment.'         => __( 'Log in to leave a comment.', 'jetpack-mu-wpcom' ),
242                    /* translators: %s is the name of the provider (WordPress, Facebook, Twitter) */
243                    'Logged in via %s'                   => __( 'Logged in via %s', 'jetpack-mu-wpcom' ),
244                    'Log out'                            => __( 'Log out', 'jetpack-mu-wpcom' ),
245                    'Your browser is blocking the cookies needed to log in and comment here. Allow cookies in your privacy settings, then reload the page.' => __( 'Your browser is blocking the cookies needed to log in and comment here. Allow cookies in your privacy settings, then reload the page.', 'jetpack-mu-wpcom' ),
246                    'Email'                              => __( 'Email', 'jetpack-mu-wpcom' ),
247                    '(Address never made public)'        => __( '(Address never made public)', 'jetpack-mu-wpcom'), // phpcs:ignore PEAR.Functions.FunctionCallSignature.SpaceBeforeCloseBracket
248                    'Instantly'                          => __( 'Instantly', 'jetpack-mu-wpcom' ),
249                    'Daily'                              => __( 'Daily', 'jetpack-mu-wpcom' ),
250                    'Reply'                              => __( 'Reply', 'jetpack-mu-wpcom' ),
251                    'Comment'                            => __( 'Comment', 'jetpack-mu-wpcom' ),
252                    'WordPress'                          => __( 'WordPress', 'jetpack-mu-wpcom' ),
253                    'Weekly'                             => __( 'Weekly', 'jetpack-mu-wpcom' ),
254                    'Notify me of new posts'             => __( 'Notify me of new posts', 'jetpack-mu-wpcom' ),
255                    'Email me new posts'                 => __( 'Email me new posts', 'jetpack-mu-wpcom' ),
256                    'Email me new comments'              => __( 'Email me new comments', 'jetpack-mu-wpcom' ),
257                    'Cancel'                             => __( 'Cancel', 'jetpack-mu-wpcom' ),
258                    'Write a comment...'                 => __( 'Write a comment...', 'jetpack-mu-wpcom' ),
259                    'Write a reply...'                   => __( 'Write a reply...', 'jetpack-mu-wpcom' ),
260                    'Website'                            => __( 'Website', 'jetpack-mu-wpcom' ),
261                    'Optional'                           => __( 'Optional', 'jetpack-mu-wpcom' ),
262                    /* translators: Success message of a modal when user subscribes */
263                    'We\'ll keep you in the loop!'       => __( 'We\'ll keep you in the loop!', 'jetpack-mu-wpcom' ),
264                    'Loading your comment...'            => __( 'Loading your comment...', 'jetpack-mu-wpcom' ),
265                    /* translators: %s is the name of the site */
266                    'Discover more from'                 => sprintf( __( 'Discover more from %s', 'jetpack-mu-wpcom' ), html_entity_decode( get_bloginfo( 'name' ), ENT_QUOTES ) ),
267                    'Subscribe now to keep reading and get access to the full archive.' => __( 'Subscribe now to keep reading and get access to the full archive.', 'jetpack-mu-wpcom' ),
268                    'Continue reading'                   => __( 'Continue reading', 'jetpack-mu-wpcom' ),
269                    'Never miss a beat!'                 => __( 'Never miss a beat!', 'jetpack-mu-wpcom' ),
270                    'Interested in getting blog post updates? Simply click the button below to stay in the loop!' => __( 'Interested in getting blog post updates? Simply click the button below to stay in the loop!', 'jetpack-mu-wpcom' ),
271                    'Enter your email address'           => __( 'Enter your email address', 'jetpack-mu-wpcom' ),
272                    'Subscribe'                          => __( 'Subscribe', 'jetpack-mu-wpcom' ),
273                    'Comment sent successfully'          => __( 'Comment sent successfully', 'jetpack-mu-wpcom' ),
274                    'This comment form is being retired. Update Jetpack to keep comments working on your site.' => __( 'This comment form is being retired. Update Jetpack to keep comments working on your site.', 'jetpack-mu-wpcom' ),
275                    'Update Jetpack'                     => __( 'Update Jetpack', 'jetpack-mu-wpcom' ),
276                    'Save my name, email, and website in this browser for the next time I comment.' => __( 'Save my name, email, and website in this browser for the next time I comment.', 'jetpack-mu-wpcom' ),
277                    'hovercardi18n'                      => $hovercard_i18n,
278                    'siteId'                             => $this->blog_id,
279                    'postId'                             => $post_id,
280                    'mustLogIn'                          => $comment_registration_enabled && ! is_user_logged_in(),
281                    'requireNameEmail'                   => boolval( get_blog_option( $this->blog_id, 'require_name_email' ) ),
282                    'commentRegistration'                => $comment_registration_enabled,
283                    'connectURL'                         => $connect_url,
284                    'logoutURL'                          => html_entity_decode( wp_logout_url(), ENT_COMPAT ),
285                    'homeURL'                            => home_url( '/' ),
286                    'subscribeToBlog'                    => $subscribe_to_blog,
287                    'subscribeToComment'                 => $subscribe_to_comment,
288                    'isJetpackCommentsLoggedIn'          => is_jetpack_comments() && is_jetpack_comments_user_logged_in(),
289                    'jetpackUsername'                    => $jetpack_username,
290                    'jetpackUserId'                      => $jetpack_user_id,
291                    'jetpackSignature'                   => $jetpack_signature,
292                    'jetpackAvatar'                      => $jetpack_avatar,
293                    'enableBlocks'                       => boolval( $this->should_load_gutenberg_comments() ),
294                    'enableSubscriptionModal'            => boolval( $this->should_show_subscription_modal() ),
295                    'currentLocale'                      => $locale,
296                    'isJetpackComments'                  => is_jetpack_comments(),
297                    'allowedBlocks'                      => \Verbum_Block_Utils::get_allowed_blocks(),
298                    'embedNonce'                         => wp_create_nonce( 'embed_nonce' ),
299                    'verbumBundleUrl'                    => plugins_url( 'dist/index.js', __FILE__ ),
300                    'isRTL'                              => is_rtl(),
301                    'vbeCacheBuster'                     => $vbe_cache_buster,
302                    'iframeUniqueId'                     => $iframe_unique_id,
303                    'colorScheme'                        => $this->get_color_scheme(),
304                    'retirementNoticeUrl'                => $retirement_notice_url,
305                ),
306                JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP
307            ),
308            'before'
309        );
310
311        wp_enqueue_script( 'verbum-settings' );
312
313        Assets::register_script(
314            'verbum-dynamic-loader',
315            '../../build/verbum-comments/assets/dynamic-loader.js',
316            __FILE__,
317            array(
318                'strategy'  => 'defer',
319                'in_footer' => true,
320                'enqueue'   => true,
321            )
322        );
323    }
324
325    /**
326     * Remove some of the default comment_form args because they are not needed.
327     *
328     * @param  array $args - The default comment form arguments.
329     */
330    public function comment_form_defaults( $args ) {
331        $title_reply_default = __( 'Leave a comment', 'jetpack-mu-wpcom' );
332        $title_reply         = get_option( 'highlander_comment_form_prompt', $title_reply_default );
333
334        if ( $title_reply === 'Leave a comment' || empty( $title_reply ) ) {
335            $title_reply = $title_reply_default;
336        }
337
338        return array_merge(
339            $args,
340            array(
341                'comment_field'        => '',
342                'must_log_in'          => '',
343                'logged_in_as'         => '',
344                'comment_notes_before' => '',
345                'comment_notes_after'  => '',
346                'title_reply'          => esc_html( $title_reply ),
347                /* translators: % is the original posters name */
348                'title_reply_to'       => __( 'Leave a reply to %s', 'jetpack-mu-wpcom' ),
349                'cancel_reply_link'    => __( 'Cancel reply', 'jetpack-mu-wpcom' ),
350                'action'               => $this->get_form_action(),
351            )
352        );
353    }
354
355    /**
356     * Set comment reply link.
357     * This is to fix the reply link when comment registration is required.
358     *
359     * @param  string $reply_link - HTML for reply link.
360     * @param  array  $args - Default options for reply link.
361     * @param  object $comment - Comment being replied to.
362     * @param  object $post - PostID or WP_Post object comment is going to be displayed on.
363     */
364    public function comment_reply_link( $reply_link, $args, $comment, $post ) {
365        // This is only necessary if comment_registration is required to post comments
366        if ( ! get_option( 'comment_registration' ) ) {
367            return $reply_link;
368        }
369
370        $comment    = get_comment( $comment );
371        $respond_id = esc_attr( $args['respond_id'] );
372        $add_below  = esc_attr( $args['add_below'] );
373        /* This is to accommodate some themes that add an SVG to the Reply link like twenty-seventeen. */
374        $reply_text  = wp_kses(
375            $args['reply_text'],
376            array(
377                'svg' => array(
378                    'class'           => true,
379                    'aria-hidden'     => true,
380                    'aria-labelledby' => true,
381                    'role'            => true,
382                    'xmlns'           => true,
383                    'width'           => true,
384                    'height'          => true,
385                    'viewbox'         => true,
386                ),
387                'use' => array(
388                    'href'       => true,
389                    'xlink:href' => true,
390                ),
391            )
392        );
393        $before_link = wp_kses( $args['before'], wp_kses_allowed_html( 'post' ) );
394        $after_link  = wp_kses( $args['after'], wp_kses_allowed_html( 'post' ) );
395
396        $reply_url = esc_url( add_query_arg( 'replytocom', $comment->comment_ID . '#' . $respond_id ) );
397
398        $link = <<<HTML
399            $before_link
400            <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>
401            $after_link
402HTML;
403
404        return $link;
405    }
406
407    /**
408     * Loop through all available fields and remove them.
409     *
410     * @param  array $fields - Default comment fields.
411     * @return array $fields with no HTML.
412     */
413    public function comment_form_default_fields( $fields ) {
414        foreach ( $fields as $field => $html ) {
415            remove_all_filters( "comment_form_field_{$field}" );
416            add_filter( "comment_form_field_{$field}", '__return_false', 100 );
417        }
418
419        return $fields;
420    }
421
422    /**
423     * Verify nonce before accepting comment.
424     *
425     * @param int $comment_id The comment ID.
426     * @return void
427     */
428    public function check_comment_allowed( int $comment_id ) {
429        // Don't check if we're using Jetpack Comments.
430        if ( is_jetpack_comments() ) {
431            return;
432        }
433
434        // Check for Highlander Nonce.
435        if ( isset( $_POST['highlander_comment_nonce'] ) ) {
436            $valid_nonce     = false;
437            $current_user_id = get_current_user_id();
438
439            if ( wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['highlander_comment_nonce'] ) ), 'highlander_comment' ) ) {
440                $valid_nonce = true;
441            } elseif ( function_exists( 'wp_set_current_user' ) ) {
442                // There randomly occurs a race condition between the logged in/out state of the user.
443                // Check if their nonce is a logged out nonce.
444                wp_set_current_user( 0 );
445                $valid_nonce = wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['highlander_comment_nonce'] ) ), 'highlander_comment' );
446                wp_set_current_user( $current_user_id );
447            }
448
449            // All good, proceed.
450            if ( $valid_nonce ) {
451                return;
452            }
453
454            // Log the error to Log2Logstash.
455            // Related to https://github.com/Automattic/wp-calypso/issues/99436
456            if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
457                require_once WP_CONTENT_DIR . '/lib/log2logstash/log2logstash.php';
458
459                $headers = getallheaders();
460                $data    = array(
461                    'session_token' => wp_get_session_token(),
462                    'editor_type'   => isset( $_POST['verbum_loaded_editor'] ) ? sanitize_text_field( wp_unslash( $_POST['verbum_loaded_editor'] ) ) : '',
463                    'user_agent'    => sanitize_text_field( $headers['User-Agent'] ?? '' ),
464                    'referrer'      => esc_url_raw( $headers['Referer'] ?? '' ),
465                );
466
467                log2logstash(
468                    array(
469                        'feature'    => 'verbum-comments',
470                        'message'    => 'Pre-comment nonce failed',
471                        'blog_id'    => get_current_blog_id(),
472                        'user_id'    => $current_user_id,
473                        'host'       => sanitize_text_field( $headers['Host'] ?? '' ),
474                        'comment_id' => $comment_id,
475                        'extra'      => wp_json_encode( $data, JSON_UNESCAPED_SLASHES ),
476                    )
477                );
478            }
479        }
480
481        wp_die( esc_html__( 'Sorry, this comment could not be posted.', 'jetpack-mu-wpcom' ) );
482    }
483
484    /**
485     * Add all our custom fields to the comment meta after it is saved.
486     *
487     * @param int $comment_id The comment ID.
488     */
489    public function add_verbum_meta_data( $comment_id ) {
490        $comment_meta = array();
491        // phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce checked before saving comment
492        $allowed_subscription_modal_statuses = array( 'showed', 'hidden_is_blog_member', 'hidden_jetpack', 'hidden_disabled', 'hidden_cookies_disabled', 'hidden_subscribe_not_enabled', 'hidden_already_subscribed', 'hidden_views_limit' );
493        $service                             = isset( $_POST['hc_post_as'] ) ? sanitize_text_field( wp_unslash( $_POST['hc_post_as'] ) ) : '';
494        $verbum_loaded_editor                = isset( $_POST['verbum_loaded_editor'] ) ? sanitize_text_field( wp_unslash( $_POST['verbum_loaded_editor'] ) ) : '';
495        $verbum_subscription_modal_show      = isset( $_POST['verbum_show_subscription_modal'] ) && in_array( $_POST['verbum_show_subscription_modal'], $allowed_subscription_modal_statuses, true ) ? sanitize_text_field( wp_unslash( $_POST['verbum_show_subscription_modal'] ) ) : '';
496        // phpcs:enable WordPress.Security.NonceVerification.Missing -- nonce checked before saving comment
497        $allowed_comments_sources = array( 'gutenberg', 'textarea', 'textarea-slow-connection' );
498        if ( in_array( $verbum_loaded_editor, $allowed_comments_sources, true ) ) {
499            bump_stats_extras( 'verbum-comment-editor', $verbum_loaded_editor );
500        }
501        if ( $verbum_subscription_modal_show ) {
502            bump_stats_extras( 'verbum-subscription-modal', $verbum_subscription_modal_show );
503        }
504        switch ( $service ) {
505            case 'wordpress': // phpcs:ignore WordPress.WP.CapitalPDangit.MisspelledInText
506                if ( 'wpcom' === wpcom_blog_site_id_label() ) {
507                    do_action( 'highlander_wpcom_post_comment_bump_stat', $comment_id );
508                }
509                bump_stats_extras( 'verbum-comment-posted', 'wordpress' ); // phpcs:ignore WordPress.WP.CapitalPDangit.MisspelledInText
510                break;
511
512            case 'jetpack':
513                if ( is_jetpack_comments() && is_jetpack_comments_user_logged_in() ) {
514                    $comment_meta['hc_post_as']         = 'jetpack';
515                    $comment_meta['hc_avatar']          = check_and_return_post_string( 'hc_avatar' );
516                    $comment_meta['hc_foreign_user_id'] = check_and_return_post_string( 'hc_userid' );
517
518                    bump_stats_extras( 'verbum-comment-posted', 'jetpack' );
519                } else {
520                    jetpack_comments_die( 'JPC_HIGHLANDER_ADD_COMMENT_META' );
521                }
522
523                break;
524            default:
525                if ( is_user_logged_in() ) {
526                    bump_stats_extras( 'verbum-comment-posted', 'guest-logged-in' );
527                } else {
528                    bump_stats_extras( 'verbum-comment-posted', 'guest' );
529                }
530                break;
531        }
532
533        foreach ( $comment_meta as $key => $value ) {
534            add_comment_meta( $comment_id, $key, $value, true );
535        }
536    }
537
538    /**
539     * Get the hidden fields for the comment form.
540     */
541    public function hidden_fields() {
542        // Ironically, get_queried_post_id doesn't work inside query loop.
543        // See: https://github.com/Automattic/wp-calypso/issues/98136
544        $queried_post    = get_post();
545        $queried_post_id = $queried_post ? $queried_post->ID : 0;
546        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
547        $post_id = isset( $_GET['postid'] ) ? intval( $_GET['postid'] ) : $queried_post_id;
548        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
549        $is_current_user_subscribed = isset( $_GET['is_current_user_subscribed'] ) ? intval( $_GET['is_current_user_subscribed'] ) : 0;
550        $nonce                      = wp_create_nonce( 'highlander_comment' );
551        $hidden_fields              = get_comment_id_fields( $post_id ) . '
552            <input type="hidden" name="highlander_comment_nonce" id="highlander_comment_nonce" value="' . esc_attr( $nonce ) . '" />
553            <input type="hidden" name="verbum_show_subscription_modal" value="' . $this->subscription_modal_status() . '" />';
554
555        if ( is_jetpack_comments() ) {
556            $hidden_fields .= '
557                <input type="hidden" name="jetpack-remote-blogid" value="' . $this->blog_id . '" />
558                <input type="hidden" name="jetpack-remote-action" value="comment-post" />
559                <input type="hidden" name="is_current_user_subscribed" value="' . $is_current_user_subscribed . '" />';
560
561            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
562            $jetpack_nonce = isset( $_GET['jetpack_comments_nonce'] ) ? sanitize_text_field( wp_unslash( $_GET['jetpack_comments_nonce'] ) ) : false;
563            if ( $jetpack_nonce ) {
564                $hidden_fields .= '<input type="hidden" name="jetpack_comments_nonce" value="' . esc_attr( $jetpack_nonce ) . '" />';
565            }
566        }
567
568        return '<div class="verbum-form-meta">' . $hidden_fields . '</div>';
569    }
570
571    /***
572     * Check if we should load the Gutenberg comments.
573     *
574     * Block should be carefully loaded to avoid Forums, P2, etc.
575     */
576    public function should_load_gutenberg_comments() {
577        // Don't load when jetpack or atomic for now, it does not look cool on dark themes.
578        $is_jetpack_site = 522232 === get_current_blog_id();
579        if ( $is_jetpack_site ) {
580            return false;
581        }
582
583        // Blocks in comments have been disabled on a simple site
584        if ( empty( get_option( 'enable_blocks_comments', true ) ) ) {
585            return false;
586        }
587
588        return true;
589    }
590
591    /**
592     * Check if we should show the subscription modal.
593     */
594    public function should_show_subscription_modal() {
595        $modal_enabled = boolval( get_blog_option( $this->blog_id, 'jetpack_verbum_subscription_modal', true ) );
596
597        $is_jetpack_site = 522232 === get_current_blog_id(); // Disable if verbum is served via 'jetpack.wordpress.com'
598        return ! $is_jetpack_site && ! is_user_member_of_blog( '', $this->blog_id ) && $modal_enabled;
599    }
600
601    /**
602     * Get the status of the subscription modal.
603     */
604    public function subscription_modal_status() {
605        if ( is_user_member_of_blog( '', $this->blog_id ) ) {
606            return 'hidden_is_blog_member';
607        }
608        if ( is_jetpack_comments() ) {
609            return 'hidden_jetpack';
610        }
611        if ( ! get_option( 'jetpack_verbum_subscription_modal', true ) ) {
612            return 'hidden_disabled';
613        }
614        return '';
615    }
616
617    /**
618     * Add Jetpack script data.
619     *
620     * @param array $data - The Jetpack script data.
621     * @return array - The modified Jetpack script data.
622     */
623    public function add_jetpack_script_data( $data ) {
624        if ( \Verbum_Block_Utils::should_show_verbum_comments() ) {
625            if ( ! isset( $data['site']['host'] ) ) {
626                $data['site']['host'] = ( new \Automattic\Jetpack\Status\Host() )->get_known_host_guess();
627            }
628            if ( ! isset( $data['site']['is_wpcom_platform'] ) ) {
629                $data['site']['is_wpcom_platform'] = ( new \Automattic\Jetpack\Status\Host() )->is_wpcom_platform();
630            }
631        }
632        return $data;
633    }
634}