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