Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 606
0.00% covered (danger)
0.00%
0 / 28
CRAP
0.00% covered (danger)
0.00%
0 / 1
Action_Bar
0.00% covered (danger)
0.00%
0 / 606
0.00% covered (danger)
0.00%
0 / 28
32220
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 load
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 enqueue_scripts
0.00% covered (danger)
0.00%
0 / 82
0.00% covered (danger)
0.00%
0 / 1
812
 footer
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
30
 is_vip
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 localized_url
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 is_folded
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 set_folded
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 logged_out_follow_disabled
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 switch_to_user_locale
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 restore_locale
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 email_default
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 icon_markup
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
12
 icon
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 menu_item
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
20
 menu_group
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 blavatar
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 site_title
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 follow_links
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 html
0.00% covered (danger)
0.00%
0 / 325
0.00% covered (danger)
0.00%
0 / 1
6162
 can_reblog
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
20
 gdpr_applies
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
42
 bump_stat
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
20
 fold
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 unfold
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 ajax_stats
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 settings_field
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 settings_field_display
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * WordPress.com Action Bar.
4 *
5 * The floating bar in the bottom corner of a site's front end. Visitors can subscribe, comment,
6 * reblog and report from it; site members get Edit and Stats shortcuts.
7 *
8 * @package automattic/jetpack-newsletter
9 */
10
11namespace Automattic\Jetpack\Newsletter;
12
13use Automattic\Jetpack\Assets;
14use Automattic\Jetpack\Status;
15use Automattic\Jetpack\Status\Host;
16
17/**
18 * The floating Action Bar on the front end of WordPress.com Simple sites. Ported from wpcom `wp-content/mu-plugins/actionbar.php`.
19 */
20class Action_Bar {
21    /**
22     * Whether the class has been initialized.
23     *
24     * @var bool
25     */
26    private static $initialized = false;
27
28    /**
29     * Queue the Action Bar to load once all plugins are available.
30     *
31     * Simple only for now. Yields to the copy wpcom still ships in mu-plugins, so the two never load together.
32     *
33     * @since $$next-version$$
34     */
35    public static function init() {
36        if ( self::$initialized ) {
37            return;
38        }
39        self::$initialized = true;
40
41        if ( ! ( new Host() )->is_wpcom_simple() ) {
42            return;
43        }
44
45        // A callback added to the hook that is currently running never fires.
46        if ( did_action( 'plugins_loaded' ) ) {
47            self::load();
48        } else {
49            add_action( 'plugins_loaded', array( __CLASS__, 'load' ) );
50        }
51    }
52
53    /**
54     * Register the bar's hooks unless wpcom's mu-plugin copy is loaded.
55     *
56     * @since $$next-version$$
57     */
58    public static function load() {
59        if ( function_exists( 'wpcom_actionbar_enqueue_scripts' ) ) {
60            return;
61        }
62
63        add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ), 101 );
64        add_action( 'admin_init', array( __CLASS__, 'settings_field' ) );
65
66        add_action( 'wp_ajax_fold_actionbar', array( __CLASS__, 'fold' ) );
67        add_action( 'wp_ajax_nopriv_fold_actionbar', array( __CLASS__, 'fold' ) );
68        add_action( 'wp_ajax_unfold_actionbar', array( __CLASS__, 'unfold' ) );
69        add_action( 'wp_ajax_nopriv_unfold_actionbar', array( __CLASS__, 'unfold' ) );
70        add_action( 'wp_ajax_actionbar_stats', array( __CLASS__, 'ajax_stats' ) );
71        add_action( 'wp_ajax_nopriv_actionbar_stats', array( __CLASS__, 'ajax_stats' ) );
72    }
73
74    /**
75     * Decide whether the bar renders on this request and, if so, queue its data and footer output.
76     */
77    public static function enqueue_scripts() {
78        if ( get_option( 'wpcom_hide_action_bar' ) ) {
79            return;
80        }
81
82        $current_user = wp_get_current_user();
83
84        /**
85         * Filters whether the Action Bar loads on this request.
86         *
87         * WordPress.com hooks this to keep the bar off its internal sites and off sites marked deleted, spam, archived, or parked.
88         *
89         * @since $$next-version$$
90         *
91         * @param bool $enabled Whether to load the bar. Default true.
92         */
93        if ( ! apply_filters( 'jetpack_action_bar_enabled', true ) ) {
94            return;
95        }
96
97        $site_id = get_current_blog_id();
98
99        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only checks on preview query args.
100        // Don't show on theme previews and block patterns source sites.
101        $is_theme_demo = function_exists( 'wpcom_is_theme_demo_site' ) && wpcom_is_theme_demo_site();
102        // @phan-suppress-next-line PhanUndeclaredFunction -- Defined by jetpack-mu-wpcom, which is not a dependency; guarded by function_exists().
103        $is_pattern_source = function_exists( 'wpcom_has_blog_sticker' ) && wpcom_has_blog_sticker( 'block-patterns-source-site', $site_id );
104        if ( isset( $_GET['theme'] ) || $is_theme_demo || $is_pattern_source ) {
105            return;
106        }
107
108        // Don't show on Customizer previews.
109        if ( isset( $_GET['customize_theme'] ) || isset( $_GET['customize_changeset_uuid'] ) ) {
110            return;
111        }
112        // phpcs:enable
113
114        // Don't show on WordPress mobile apps.
115        $user_agent = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
116        if ( $user_agent && preg_match( '/wp-(android|iphone)/', $user_agent ) ) {
117            return;
118        }
119
120        // Don't show on Landpack blogs, unless user is a member of the blog.
121        if ( defined( 'WPCOM_LANDPACK_BLOG_IDS' ) && in_array( $site_id, (array) WPCOM_LANDPACK_BLOG_IDS, true ) && ! is_user_member_of_blog( $current_user->ID, $site_id ) ) {
122            return;
123        }
124
125        // Render this in the user's language.
126        self::switch_to_user_locale();
127
128        $status_message = false;
129        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Status flag set by the subscribe.wordpress.com redirect.
130        $blogsub = isset( $_GET['blogsub'] ) ? sanitize_key( wp_unslash( $_GET['blogsub'] ) ) : '';
131        switch ( $blogsub ) {
132            case 'confirming':
133                $status_message  = '<h3>' . __( 'Thanks', 'jetpack-newsletter' ) . '</h3>';
134                $status_message .= '<div>' .
135                    wp_kses(
136                        sprintf(
137                            /* translators: %s is the URL of the support contact page. */
138                            __( 'You’ll get an email with a link to confirm your subscription. If it doesn’t arrive, please <a href="%s">contact us</a>.', 'jetpack-newsletter' ),
139                            esc_url( self::localized_url( 'https://wordpress.com/support/contact/' ) )
140                        ),
141                        array(
142                            'a' => array(
143                                'href' => array(),
144                            ),
145                        )
146                    ) .
147                    '</div>';
148                break;
149            case 'subscribed':
150                $status_message = '<div>' . __( 'You’re already subscribed to this site!', 'jetpack-newsletter' ) . '</div>';
151                break;
152            case 'flooded':
153                $status_message =
154                    '<div>' .
155                    sprintf(
156                        /* translators: %s is a link with its text (Subscription Manager) translated separately */
157                        __( 'You already have several pending email subscriptions. Approve or delete a few through your %s before attempting to subscribe to more blogs.', 'jetpack-newsletter' ),
158                        '<a href="https://subscribe.wordpress.com/">' . __( 'Subscription Manager', 'jetpack-newsletter' ) . '</a>'
159                    ) .
160                    '</div>';
161                break;
162            case 'pending':
163                $status_message = '<div>' . __( 'You already have a pending subscription, we just sent you another email, click the link or <a href="https://en.support.wordpress.com/contact/">contact us</a> if you don’t get it', 'jetpack-newsletter' ) . '</div>';
164                break;
165            case 'confirmed':
166                $status_message = '<div>' . __( 'Congrats, you’re subscribed! You’ll get an email with the details of your subscription and an unsubscribe link', 'jetpack-newsletter' ) . '</div>';
167                break;
168        }
169
170        // VIP: Disable functionality on sites that have logged_out follow set to false.
171        if ( ! is_user_logged_in() && self::logged_out_follow_disabled() ) {
172            self::restore_locale();
173            return;
174        }
175
176        $http_host = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
177
178        // Data to pass to the JS.
179        $actionbar_info = array(
180            'siteID'           => $site_id,
181            'postID'           => is_singular() ? get_the_ID() : 0,
182            'siteURL'          => get_option( 'home' ),
183            'xhrURL'           => esc_url_raw( ( is_ssl() ? 'https://' : 'http://' ) . $http_host . '/wp-admin/admin-ajax.php' ),
184            'nonce'            => wp_create_nonce( 'manage_subscription' ),
185            'isLoggedIn'       => is_user_logged_in(),
186            'statusMessage'    => $status_message,
187            'subsEmailDefault' => self::email_default( $current_user ),
188            'proxyScriptUrl'   => 'https://s0.wp.com/wp-content/js/wpcom-proxy-request.js?ver=20211021',
189        );
190
191        if ( is_singular() ) {
192            $actionbar_info['shortlink'] = wp_get_shortlink( get_the_ID() );
193        }
194
195        $actionbar_info['i18n'] = array(
196            'followedText'    => __( 'New posts from this site will now appear in your <a href="https://wordpress.com/reader">Reader</a>', 'jetpack-newsletter' ),
197            'foldBar'         => __( 'Collapse this bar', 'jetpack-newsletter' ),
198            'unfoldBar'       => __( 'Expand this bar', 'jetpack-newsletter' ),
199            'shortLinkCopied' => __( 'Copied to clipboard.', 'jetpack-newsletter' ),
200        );
201
202        // Switch back to site language.
203        self::restore_locale();
204
205        // An alias handle with no src, so wp_localize_script() prints the data without a script tag.
206        // phpcs:disable WordPress.WP.EnqueuedResourceParameters.MissingVersion
207        wp_register_script( 'wpcom-actionbar-placeholder', '', array(), null, false );
208        wp_localize_script( 'wpcom-actionbar-placeholder', 'actionbardata', $actionbar_info );
209        wp_enqueue_script( 'wpcom-actionbar-placeholder' );
210        // phpcs:enable
211
212        // Defer loading the actionbar resources.
213        add_action( 'wp_footer', array( __CLASS__, 'footer' ) );
214    }
215
216    /**
217     * Print the bar's markup, then a loader that appends its CSS and JS after DOMContentLoaded.
218     */
219    public static function footer() {
220        $is_rtl = function_exists( 'wpcom_is_locale_rtl' ) ? wpcom_is_locale_rtl( get_user_locale() ) : is_rtl();
221        self::html( $is_rtl );
222
223        $asset_path = dirname( __DIR__ ) . '/build/action-bar.asset.php';
224        $asset_file = file_exists( $asset_path ) ? include $asset_path : array();
225        $version    = is_array( $asset_file ) && ! empty( $asset_file['version'] ) ? $asset_file['version'] : Settings::PACKAGE_VERSION;
226
227        // One stylesheet for both directions: it uses logical properties and the bar carries its own dir attribute.
228        $css_url = wp_json_encode( add_query_arg( 'ver', $version, plugins_url( '../build/action-bar.css', __FILE__ ) ), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT );
229        $js_url  = wp_json_encode( add_query_arg( 'ver', $version, plugins_url( '../build/action-bar.js', __FILE__ ) ), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT );
230
231        wp_print_inline_script_tag(
232            'window.addEventListener( "DOMContentLoaded", function () {
233                var link = document.createElement( "link" );
234                link.href = ' . $css_url . ';
235                link.rel = "stylesheet";
236                document.head.appendChild( link );
237
238                var script = document.createElement( "script" );
239                script.src = ' . $js_url . ';
240                document.body.appendChild( script );
241            } );'
242        );
243    }
244
245    /**
246     * Whether this is a WordPress.com VIP site. False anywhere the wpcom helper is missing.
247     *
248     * @return bool
249     */
250    private static function is_vip() {
251        return function_exists( 'wpcom_is_vip' ) && wpcom_is_vip();
252    }
253
254    /**
255     * Localize a WordPress.com URL for the current user where wpcom can; otherwise return it as is.
256     *
257     * @param string $url A wordpress.com URL.
258     * @return string
259     */
260    private static function localized_url( $url ) {
261        return function_exists( 'localized_wpcom_url' ) ? localized_wpcom_url( $url ) : $url;
262    }
263
264    /**
265     * Whether the user collapsed the bar. A wpcom user attribute on Simple, user meta elsewhere.
266     *
267     * @param int $user_id User ID.
268     * @return bool
269     */
270    private static function is_folded( $user_id ) {
271        if ( function_exists( 'get_user_attribute' ) ) {
272            return (bool) get_user_attribute( $user_id, 'is_actionbar_folded' );
273        }
274        return (bool) get_user_meta( $user_id, 'is_actionbar_folded', true );
275    }
276
277    /**
278     * Remember or forget that the user collapsed the bar.
279     *
280     * @param int  $user_id User ID.
281     * @param bool $folded  Whether the bar is collapsed.
282     */
283    private static function set_folded( $user_id, $folded ) {
284        if ( function_exists( 'update_user_attribute' ) && function_exists( 'delete_user_attribute' ) ) {
285            if ( $folded ) {
286                update_user_attribute( $user_id, 'is_actionbar_folded', 1 );
287            } else {
288                delete_user_attribute( $user_id, 'is_actionbar_folded' );
289            }
290            return;
291        }
292        if ( $folded ) {
293            update_user_meta( $user_id, 'is_actionbar_folded', 1 );
294        } else {
295            delete_user_meta( $user_id, 'is_actionbar_folded' );
296        }
297    }
298
299    /**
300     * Whether logged-out visitors should get no bar and no follow actions.
301     *
302     * @return bool
303     */
304    private static function logged_out_follow_disabled() {
305        $settings = get_option( 'subscription_options' );
306        $disabled = self::is_vip() && ( ! isset( $settings['loggedoutfollow'] ) || 'off' === $settings['loggedoutfollow'] );
307
308        /**
309         * Filters whether logged-out visitors get the bar and its follow actions.
310         *
311         * @since $$next-version$$
312         *
313         * @param bool $disabled Whether to disable. Defaults to true on VIP sites with logged-out follow off.
314         */
315        return (bool) apply_filters( 'wpcom_disable_logged_out_follow', $disabled );
316    }
317
318    /**
319     * Switch to the current user's locale, if logged in.
320     */
321    private static function switch_to_user_locale() {
322        if ( ! is_user_logged_in() ) {
323            return;
324        }
325        if ( function_exists( 'wpcom_switch_to_user_locale' ) ) {
326            wpcom_switch_to_user_locale( get_current_user_id() );
327        } else {
328            switch_to_user_locale( get_current_user_id() );
329        }
330    }
331
332    /**
333     * Undo switch_to_user_locale().
334     */
335    private static function restore_locale() {
336        if ( ! is_user_logged_in() ) {
337            return;
338        }
339        if ( function_exists( 'wpcom_restore_current_locale' ) ) {
340            wpcom_restore_current_locale();
341        } else {
342            restore_previous_locale();
343        }
344    }
345
346    /**
347     * The email delivery frequency a new subscription defaults to for this user.
348     *
349     * @param \WP_User $current_user The current user.
350     * @return string One of instantly, daily, weekly, never.
351     */
352    private static function email_default( $current_user ) {
353        if ( ! empty( $current_user->subs_email_default ) ) {
354            return $current_user->subs_email_default;
355        }
356        if ( function_exists( 'wpcom_subs_get_subscription_delivery_email_default' ) ) {
357            return wpcom_subs_get_subscription_delivery_email_default();
358        }
359        return 'instantly';
360    }
361
362    /**
363     * Markup for one of the WordPress icons the bar uses, inlined from @wordpress/icons.
364     *
365     * Icons inherit their color from CSS `color`, like the library's own Icon component.
366     *
367     * @param string $name Icon name from the WordPress icon library.
368     * @param int    $size Rendered width and height in pixels.
369     * @return string Empty for an unknown name.
370     */
371    private static function icon_markup( $name, $size = 24 ) {
372        $fill_icons = array(
373            'bell'            => '<path fill-rule="evenodd" clip-rule="evenodd" d="M17 11.5c0 1.353.17 2.368.976 3 .266.209.602.376 1.024.5v1H5v-1c.422-.124.757-.291 1.024-.5.806-.632.976-1.647.976-3V9c0-2.8 2.2-5 5-5s5 2.2 5 5v2.5ZM15.5 9v2.5c0 .93.066 1.98.515 2.897l.053.103H7.932a4.018 4.018 0 0 0 .053-.103c.449-.917.515-1.967.515-2.897V9c0-1.972 1.528-3.5 3.5-3.5s3.5 1.528 3.5 3.5Zm-5.492 9.008c0-.176.023-.346.065-.508h3.854A1.996 1.996 0 0 1 12 20c-1.1 0-1.992-.892-1.992-1.992Z"/>',
374            'copy'            => '<path fill-rule="evenodd" clip-rule="evenodd" d="M5 4.5h11a.5.5 0 0 1 .5.5v11a.5.5 0 0 1-.5.5H5a.5.5 0 0 1-.5-.5V5a.5.5 0 0 1 .5-.5ZM3 5a2 2 0 0 1 2-2h11a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5Zm17 3v10.75c0 .69-.56 1.25-1.25 1.25H6v1.5h12.75a2.75 2.75 0 0 0 2.75-2.75V8H20Z"/>',
375            'external'        => '<path d="M19.5 4.5h-7V6h4.44l-5.97 5.97 1.06 1.06L18 7.06v4.44h1.5v-7Zm-13 1a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-3H17v3a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h3V5.5h-3Z"/>',
376            'comment'         => '<path d="M18 4H6c-1.1 0-2 .9-2 2v12.9c0 .6.5 1.1 1.1 1.1.3 0 .5-.1.8-.3L8.5 17H18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm.5 11c0 .3-.2.5-.5.5H7.9l-2.4 2.4V6c0-.3.2-.5.5-.5h12c.3 0 .5.2.5.5v9z"/>',
377            'more-horizontal' => '<path d="M11 13h2v-2h-2v2zm-6 0h2v-2H5v2zm12-2v2h2v-2h-2z"/>',
378            'pencil'          => '<path d="m19 7-3-3-8.5 8.5-1 4 4-1L19 7Zm-7 11.5H5V20h7v-1.5Z"/>',
379            'reusable-block'  => '<path d="M7 7.2h8.2L13.5 9l1.1 1.1 3.6-3.6-3.5-4-1.1 1 1.9 2.3H7c-.9 0-1.7.3-2.3.9-1.4 1.5-1.4 4.2-1.4 5.6v.2h1.5v-.3c0-1.1 0-3.5 1-4.5.3-.3.7-.5 1.2-.5zm13.8 4V11h-1.5v.3c0 1.1 0 3.5-1 4.5-.3.3-.7.5-1.3.5H8.8l1.7-1.7-1.1-1.1L5.9 17l3.5 4 1.1-1-1.9-2.3H17c.9 0 1.7-.3 2.3-.9 1.5-1.4 1.5-4.2 1.5-5.6z"/>',
380            'shield'          => '<path fill-rule="evenodd" clip-rule="evenodd" d="M12 3.176l6.75 3.068v4.574c0 3.9-2.504 7.59-6.035 8.755a2.283 2.283 0 01-1.43 0c-3.53-1.164-6.035-4.856-6.035-8.755V6.244L12 3.176zM6.75 7.21v3.608c0 3.313 2.145 6.388 5.005 7.33.159.053.331.053.49 0 2.86-.942 5.005-4.017 5.005-7.33V7.21L12 4.824 6.75 7.21z"/>',
381        );
382        // These are drawn with strokes, not fills, in the library.
383        $stroke_icons = array(
384            'chart-bar' => '<path d="M6.75 20V10M12 20V5M17.25 20V14" vector-effect="non-scaling-stroke"/>',
385            'check'     => '<path d="M7 12L10 15L17 8" vector-effect="non-scaling-stroke"/>',
386        );
387
388        if ( isset( $fill_icons[ $name ] ) ) {
389            $attributes = 'fill="currentColor"';
390            $markup     = $fill_icons[ $name ];
391        } elseif ( isset( $stroke_icons[ $name ] ) ) {
392            $attributes = 'style="fill: none" stroke="currentColor" stroke-width="1.5"';
393            $markup     = $stroke_icons[ $name ];
394        } else {
395            return '';
396        }
397
398        return sprintf(
399            '<svg class="actnbr-icon actnbr-icon-%1$s" width="%2$d" height="%2$d" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" %3$s>%4$s</svg>',
400            esc_attr( $name ),
401            (int) $size,
402            $attributes,
403            $markup
404        );
405    }
406
407    /**
408     * Print one of the bar's icons.
409     *
410     * @param string $name Icon name from the WordPress icon library.
411     * @param int    $size Rendered width and height in pixels.
412     */
413    private static function icon( $name, $size = 24 ) {
414        echo self::icon_markup( $name, $size ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static SVG markup, name escaped in the builder.
415    }
416
417    /**
418     * Markup for one item of the â‹¯ menu.
419     *
420     * @param array $args Item arguments: href, label, class (stats hook), icon (right-edge icon name), blank (open in a new tab), before (trusted markup before the label), role (defaults to menuitem).
421     * @return string
422     */
423    private static function menu_item( $args ) {
424        $args = wp_parse_args(
425            $args,
426            array(
427                'href'   => '',
428                'label'  => '',
429                'class'  => '',
430                'icon'   => '',
431                'blank'  => false,
432                'before' => '',
433                'role'   => 'menuitem',
434            )
435        );
436
437        return sprintf(
438            '<a%1$s class="actnbr-menu__item %2$s" href="%3$s"%4$s>%5$s<span class="actnbr-menu__label">%6$s</span>%7$s</a>',
439            $args['role'] ? ' role="' . esc_attr( $args['role'] ) . '"' : '',
440            esc_attr( $args['class'] ),
441            esc_url( $args['href'] ),
442            $args['blank'] ? ' target="_blank" rel="noopener noreferrer"' : '',
443            $args['before'], // Caller-built markup, escaped at the source.
444            esc_html( $args['label'] ),
445            $args['icon'] ? '<span class="actnbr-menu__icon">' . self::icon_markup( $args['icon'], 18 ) . '</span>' : ''
446        );
447    }
448
449    /**
450     * Print a menu group if it has any items.
451     *
452     * @param string[] $items Rendered items; empty strings are skipped.
453     */
454    private static function menu_group( array $items ) {
455        $items = array_filter( $items );
456        if ( ! $items ) {
457            return;
458        }
459        echo '<div class="actnbr-menu__group" role="group">' . implode( '', $items ) . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Items are escaped where built.
460    }
461
462    /**
463     * The site's blavatar image markup, or an empty string.
464     *
465     * @return string
466     */
467    private static function blavatar() {
468        if ( ! function_exists( 'get_blavatar' ) ) {
469            return '';
470        }
471        $blavatar_img = get_blavatar( get_option( 'siteurl' ), 50, Assets::staticize_subdomain( 'https://en.wordpress.com/i/logo/wpcom-gray-white.png' ) ); // phpcs:ignore WPCOM.I18nRules.LocalizedUrl.UnlocalizedUrl
472        if ( str_starts_with( $blavatar_img, '<img alt' ) ) {
473            $blavatar_img = "<img loading='lazy' alt" . substr( $blavatar_img, 8 );
474        }
475        return $blavatar_img;
476    }
477
478    /**
479     * Print the site title row at the top of the Subscribe popover.
480     *
481     * @param string $site_url  Site home URL.
482     * @param string $site_name Site title.
483     * @param string $blavatar  Blavatar image markup, or empty.
484     */
485    private static function site_title( $site_url, $site_name, $blavatar ) {
486        $item = self::menu_item(
487            array(
488                'href'   => $site_url,
489                'label'  => $site_name,
490                'class'  => 'actnbr-sitename',
491                'before' => $blavatar,
492                'role'   => '',
493            )
494        );
495        echo '<div class="actnbr-panel__group">' . $item . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped where built.
496    }
497
498    /**
499     * Print the Subscribe and Subscribed links; only one is visible at a time.
500     *
501     * @param bool $is_following Whether the current user already subscribes to this site.
502     */
503    private static function follow_links( $is_following ) {
504        ?>
505            <a class="actnbr-action actnbr-actn-follow <?php echo $is_following ? ' no-display' : ''; ?>" href="" role="button" aria-haspopup="dialog" aria-expanded="false">
506                <?php self::icon( 'bell', 20 ); ?>
507                <span><?php esc_html_e( 'Subscribe', 'jetpack-newsletter' ); ?></span>
508            </a>
509            <a class="actnbr-action actnbr-actn-following <?php echo $is_following ? '' : ' no-display'; ?>" href="" role="button">
510                <?php self::icon( 'check', 20 ); ?>
511                <span><?php esc_html_e( 'Subscribed', 'jetpack-newsletter' ); ?></span>
512            </a>
513        <?php
514    }
515
516    /**
517     * Print the bar's markup. Hidden inline until the JS reveals it.
518     *
519     * @param bool $is_rtl Whether to render right-to-left.
520     */
521    private static function html( $is_rtl ) {
522        $current_user = wp_get_current_user();
523        $site_id      = get_current_blog_id();
524
525        global $current_blog;
526
527        $is_logged_in = is_user_logged_in();
528        $is_member    = $is_logged_in && is_user_member_of_blog( $current_user->ID, $site_id );
529
530        // Render this in the user's language.
531        self::switch_to_user_locale();
532
533        $is_suspended = function_exists( 'is_suspended' ) && is_suspended( $site_id );
534
535        /*
536         * Follow actions are dropped only on a "static" site (front page set, under two posts) viewed by
537         * someone who is not a member. Deleted, spam and archived sites never reach this function.
538         */
539        $can_follow = true;
540        if (
541            ! $is_suspended &&
542            ! in_array( $site_id, (array) apply_filters( 'loggedout_follow_disabled_blog_id', array( 1 ) ), true ) &&
543            ! apply_filters( 'loggedout_follow_disabled', false ) &&
544            ! self::logged_out_follow_disabled() &&
545            ( ! $is_member || function_exists( 'is_automattician' ) && is_automattician( $current_user->ID ) ) &&
546            ( 'page' === get_option( 'show_on_front' ) && get_option( 'post_count' ) < 2 )
547        ) {
548            $can_follow = false;
549        }
550
551        $login_url = add_query_arg( 'redirect_to', get_permalink(), 'https://wordpress.com/log-in' );
552        $login_url = add_query_arg( 'signup_flow', 'account', $login_url );
553        if (
554            ! empty( $current_blog->primary_redirect )
555            && ! str_contains( $current_blog->primary_redirect, '.wordpress.com' )
556        ) {
557            // phpcs:ignore WPCOM.I18nRules.LocalizedUrl.UnlocalizedUrl
558            $redirect_to = add_query_arg( 'back', rawurlencode( get_permalink() ? get_permalink() : home_url() ), 'https://r-login.wordpress.com/remote-login.php?action=link' );
559            $login_url   = add_query_arg( 'redirect_to', rawurlencode( $redirect_to ), 'https://wordpress.com/log-in' );
560        }
561
562        $site_name          = get_option( 'blogname' );
563        $site_url           = get_option( 'home' );
564        $site_host          = wp_parse_url( $site_url, PHP_URL_HOST );
565        $site_slug          = ( new Status() )->get_site_suffix();
566        $can_customize_site = $is_member && current_user_can( 'edit_theme_options' );
567        $subscription_id    = function_exists( 'wpcom_subs_is_subscribed' ) ? wpcom_subs_is_subscribed(
568            array(
569                'user_id' => get_current_user_id(),
570                'blog_id' => $site_id,
571            )
572        ) : false;
573        $is_following       = $subscription_id ? true : false;
574        $signup_url         = 'https://wordpress.com/start/';
575        $theme_slug         = get_stylesheet();
576        $theme_url          = function_exists( 'wpcom_get_theme_showcase_url' ) ? wpcom_get_theme_showcase_url( $theme_slug ) : 'https://wordpress.com/theme/' . $theme_slug;
577        $is_singular        = false;
578        $is_folded          = $is_logged_in && self::is_folded( $current_user->ID );
579        $feed_id            = false;
580        if ( class_exists( 'FeedBag' ) ) {
581            $feed_id = \FeedBag::get_feed_id_for_blog_id( $site_id );
582        }
583        $gdpr_applies = self::gdpr_applies();
584
585        // Fall back to the site's domain if the title is empty.
586        if ( empty( $site_name ) ) {
587            $site_name = function_exists( 'get_primary_redirect' ) ? get_primary_redirect() : $site_host;
588        }
589
590        $post_id       = 0;
591        $shortlink     = '';
592        $edit_link     = '';
593        $stats_link    = '';
594        $can_edit_post = false;
595        if ( is_singular() ) {
596            $is_singular   = true;
597            $post_id       = get_the_ID();
598            $shortlink     = wp_get_shortlink( $post_id );
599            $can_edit_post = $is_member && current_user_can( 'edit_post', $post_id );
600
601            /*
602             * Use the wp admin editor for VIPs (since they have custom editor
603             * plugins), or for super admins who are not members of the blog (until
604             * user-switching is implemented in Calypso).
605             */
606            $edit_link = add_query_arg(
607                array(
608                    'post'   => $post_id,
609                    'action' => 'edit',
610                ),
611                admin_url( 'post.php' )
612            );
613
614            $post_type = get_post_type();
615
616            // @phan-suppress-next-line PhanUndeclaredFunction -- Defined by jetpack-mu-wpcom, which is not a dependency; guarded by function_exists().
617            $should_use_calypso_links = empty( $post_type ) || function_exists( 'wpcom_should_disable_calypso_links' ) && ! wpcom_should_disable_calypso_links( 'edit.php?post_type=' . $post_type );
618
619            if ( $should_use_calypso_links && ! self::is_vip() && ( ! is_super_admin() || $is_member ) ) {
620                $path_prefix = null;
621                if ( in_array( $post_type, array( 'post', 'page' ), true ) ) {
622                    $path_prefix = $post_type;
623                } elseif ( in_array( $post_type, apply_filters( 'rest_api_allowed_post_types', array( 'post', 'page', 'revision' ) ), true ) ) {
624                    $path_prefix = sprintf( 'edit/%s', $post_type );
625                }
626
627                if ( $path_prefix ) {
628                    $edit_link = sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id );
629                }
630            }
631
632            if ( $should_use_calypso_links ) {
633                $stats_link = sprintf( 'https://wordpress.com/stats/post/%d/%s', $post_id, $site_slug );
634            } else {
635                $stats_link = admin_url( sprintf( 'admin.php?page=stats#!/stats/post/%d/%d', $post_id, $site_id ) );
636            }
637        }
638
639        $referer = '';
640        if ( isset( $_SERVER['HTTP_HOST'] ) && isset( $_SERVER['REQUEST_URI'] ) ) {
641            $referer = ( is_ssl() ? 'https' : 'http' ) . '://' . sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) . sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) );
642        }
643
644        $can_comment           = is_single() && ! post_password_required( $post_id ) && comments_open( $post_id );
645        $can_reblog            = is_single() && self::can_reblog( $site_id, $post_id );
646        $can_edit_current_view = $can_edit_post || $can_customize_site;
647        $show_follow           = $can_follow && ! $can_edit_current_view;
648
649        $followers = '';
650        if ( $show_follow && ! $is_logged_in ) {
651            $subscribers_total = function_exists( 'wpcom_subs_total_for_blog' ) ? wpcom_subs_total_for_blog() : 0;
652            if ( ! empty( $subscribers_total ) && $subscribers_total > 24 ) {
653                /* translators: %s: number of subscribers */
654                $followers = sprintf( _n( 'Join %s other subscriber', 'Join %s other subscribers', $subscribers_total, 'jetpack-newsletter' ), number_format_i18n( $subscribers_total ) );
655            }
656        }
657
658        $blavatar = self::blavatar();
659
660        $classes = 'actnbr-' . str_replace( '/', '-', $theme_slug );
661        if ( $is_folded ) {
662            $classes .= ' actnbr-folded';
663        }
664
665        $dir = $is_rtl ? 'rtl' : 'ltr';
666
667        ?>
668            <div id="actionbar" dir="<?php echo esc_attr( $dir ); ?>" style="display: none;"
669                class="<?php echo esc_attr( $classes ); ?>" role="region" aria-label="<?php esc_attr_e( 'Site actions', 'jetpack-newsletter' ); ?>">
670            <span class="actnbr-live" aria-live="polite"></span>
671            <ul>
672                <?php
673                if ( $can_edit_post ) {
674                    ?>
675                        <li class="actnbr-btn actnbr-edit">
676                            <a href="<?php echo esc_url( $edit_link ); ?>">
677                                <?php self::icon( 'pencil', 20 ); ?>
678                                <span><?php esc_html_e( 'Edit', 'jetpack-newsletter' ); ?></span>
679                            </a>
680                        </li>
681                        <li class="actnbr-btn actnbr-stats">
682                            <a href="<?php echo esc_url( $stats_link ); ?>">
683                                <?php self::icon( 'chart-bar', 20 ); ?>
684                                <span><?php esc_html_e( 'Stats', 'jetpack-newsletter' ); ?></span>
685                            </a>
686                        </li>
687                    <?php
688                }
689
690                if ( $can_comment && ! $can_edit_current_view ) {
691                    ?>
692                        <li class="actnbr-btn">
693                            <a class="actnbr-action actnbr-actn-comment" href="<?php echo esc_url( get_comments_link( $post_id ) ); ?>">
694                                <?php self::icon( 'comment', 20 ); ?>
695                                <span><?php esc_html_e( 'Comment', 'jetpack-newsletter' ); ?>
696                            </span>
697                            </a>
698                        </li>
699                    <?php
700                }
701
702                if ( $can_reblog && ! $can_edit_current_view ) {
703                    ?>
704                        <li class="actnbr-btn">
705                            <a class="actnbr-action actnbr-actn-reblog" href="" role="button">
706                                <?php self::icon( 'reusable-block', 20 ); ?><span><?php esc_html_e( 'Reblog', 'jetpack-newsletter' ); ?></span>
707                            </a>
708                        </li>
709                    <?php
710                }
711
712                if ( $show_follow ) {
713                    ?>
714                        <li class="actnbr-btn actnbr-hidden">
715                            <?php self::follow_links( $is_following ); ?>
716                            <div class="actnbr-popover actnbr-panel actnbr-notice" id="follow-bubble" role="dialog" aria-label="<?php echo esc_attr( sprintf( /* translators: %s: site name */ __( 'Subscribe to %s', 'jetpack-newsletter' ), $site_name ) ); ?>">
717                                <div class="actnbr-follow-bubble">
718                                <?php self::site_title( $site_url, $site_name, $blavatar ); ?>
719                                <?php
720                                if ( $is_logged_in ) {
721                                    ?>
722                                    <div class="actnbr-panel__group actnbr-site-settings">
723                                        <div class="actnbr-message no-display" aria-live="polite"></div>
724                                        <div class="actnbr-site-settings__setting">
725                                            <span class="actnbr-site-settings__toggle">
726                                                <input class="actnbr-site-settings__toggle__input" id="toggle-input-notify-posts" type="checkbox" role="switch" />
727                                                <span class="actnbr-site-settings__toggle__track"></span>
728                                                <span class="actnbr-site-settings__toggle__thumb"></span>
729                                            </span>
730                                            <label for="toggle-input-notify-posts" class="components-toggle-control__label">
731                                                <?php esc_html_e( 'Notify me of new posts', 'jetpack-newsletter' ); ?>
732                                            </label>
733                                        </div>
734                                        <p class="actnbr-site-settings__details">
735                                            <?php esc_html_e( 'Receive web and mobile notifications for new posts from this site.', 'jetpack-newsletter' ); ?>
736                                        </p>
737                                        <div class="actnbr-site-settings__setting">
738                                            <span class="actnbr-site-settings__toggle">
739                                                <input class="actnbr-site-settings__toggle__input" id="toggle-input-email-posts" type="checkbox" role="switch" />
740                                                <span class="actnbr-site-settings__toggle__track"></span>
741                                                <span class="actnbr-site-settings__toggle__thumb"></span>
742                                            </span>
743                                            <label for="toggle-input-email-posts" class="components-toggle-control__label">
744                                                <?php esc_html_e( 'Email me new posts', 'jetpack-newsletter' ); ?>
745                                            </label>
746                                        </div>
747                                        <div class="actnbr-site-settings__details" id="email-new-posts-details">
748                                            <ul class="segmented-control" role="radiogroup" aria-label="<?php esc_attr_e( 'Email frequency', 'jetpack-newsletter' ); ?>">
749                                                <li class="segmented-control__item">
750                                                    <a class="segmented-control__link frequency-instantly" data-frequency="instantly" role="radio" aria-checked="false" tabindex="0"><?php esc_html_e( 'Instantly', 'jetpack-newsletter' ); ?></a>
751                                                </li>
752                                                <li class="segmented-control__item">
753                                                    <a class="segmented-control__link frequency-daily" data-frequency="daily" role="radio" aria-checked="false" tabindex="0"><?php esc_html_e( 'Daily', 'jetpack-newsletter' ); ?></a>
754                                                </li>
755                                                <li class="segmented-control__item">
756                                                    <a class="segmented-control__link frequency-weekly" data-frequency="weekly" role="radio" aria-checked="false" tabindex="0"><?php esc_html_e( 'Weekly', 'jetpack-newsletter' ); ?></a>
757                                                </li>
758                                            </ul>
759                                        </div>
760                                        <div class="actnbr-site-settings__setting">
761                                            <span class="actnbr-site-settings__toggle">
762                                                <input class="actnbr-site-settings__toggle__input" id="toggle-input-email-comments" type="checkbox" role="switch" />
763                                                <span class="actnbr-site-settings__toggle__track"></span>
764                                                <span class="actnbr-site-settings__toggle__thumb"></span>
765                                            </span>
766                                            <label for="toggle-input-email-comments" class="components-toggle-control__label">
767                                                <?php esc_html_e( 'Email me new comments', 'jetpack-newsletter' ); ?>
768                                            </label>
769                                        </div>
770                                    </div>
771                                    <?php
772                                } else {
773                                    ?>
774                                    <div class="actnbr-panel__group">
775                                        <div class="actnbr-message no-display" aria-live="polite"></div>
776                                        <form method="post" action="https://subscribe.wordpress.com" accept-charset="utf-8" class="no-display">
777                                            <?php
778                                            if ( $followers ) {
779                                                ?>
780                                                <div class="actnbr-follow-count"><?php echo esc_html( $followers ); ?></div>
781                                                <?php
782                                            }
783                                            ?>
784                                            <input type="email" name="email" placeholder="<?php esc_attr_e( 'Want updates? Enter your email', 'jetpack-newsletter' ); ?>" class="actnbr-email-field" aria-label="<?php esc_attr_e( 'Email address', 'jetpack-newsletter' ); ?>" />
785                                            <input type="hidden" name="action" value="subscribe" />
786                                            <input type="hidden" name="blog_id" value="<?php echo esc_attr( (string) $site_id ); ?>" />
787                                            <input type="hidden" name="source" value="<?php echo esc_url( $referer ); ?>" />
788                                            <input type="hidden" name="sub-type" value="actionbar-follow" />
789                                            <?php wp_nonce_field( 'blogsub_subscribe_' . $site_id, '_wpnonce', false, true ); ?>
790                                            <button type="submit" class="actnbr-button"><?php esc_html_e( 'Sign me up', 'jetpack-newsletter' ); ?></button>
791                                        </form>
792                                        <p class="actnbr-login-nudge">
793                                            <?php
794                                            echo wp_kses(
795                                                /* translators: %s is a URL */
796                                                sprintf( __( 'Have a WordPress.com account? <a href="%s">Log in now.</a>', 'jetpack-newsletter' ), esc_url( $login_url ) ),
797                                                array(
798                                                    'a' => array(
799                                                        'href' => array(),
800                                                    ),
801                                                )
802                                            );
803                                            ?>
804                                        </p>
805                                    </div>
806                                    <?php
807                                }
808                                ?>
809                                </div>
810                            </div>
811                        </li>
812                    <?php
813                }
814
815                /*
816                 * The privacy/GDPR button is special as it relies on window.__tcfapi being in the browser window object as well.
817                 * no-display is removed by JS if window.__tcfapi is present.
818                 */
819                if ( $gdpr_applies ) {
820                    ?>
821                        <li class="actnbr-btn no-display" onclick="javascript:__tcfapi( 'showUi' );">
822                            <a class="actnbr-action actnbr-actn-privacy" href="#" role="button">
823                                <?php self::icon( 'shield', 20 ); ?>
824                                <span><?php esc_html_e( 'Privacy', 'jetpack-newsletter' ); ?>
825                            </span>
826                            </a>
827                        </li>
828                    <?php
829                }
830                ?>
831                <li class="actnbr-ellipsis actnbr-hidden">
832                    <button type="button" class="actnbr-more-toggle" aria-haspopup="true" aria-expanded="false" aria-label="<?php esc_attr_e( 'More options', 'jetpack-newsletter' ); ?>">
833                        <?php self::icon( 'more-horizontal', 24 ); ?>
834                    </button>
835                    <div class="actnbr-popover actnbr-menu" role="menu" aria-label="<?php esc_attr_e( 'Site options', 'jetpack-newsletter' ); ?>">
836                        <?php
837                        // Site.
838                        self::menu_group(
839                            array(
840                                self::menu_item(
841                                    array(
842                                        'href'   => $site_url,
843                                        'label'  => $site_name,
844                                        'class'  => 'actnbr-sitename',
845                                        'before' => $blavatar,
846                                    )
847                                ),
848                            )
849                        );
850
851                        // This post or site.
852                        $items = array();
853                        if ( $is_singular ) {
854                            $items[] = sprintf(
855                                '<a role="menuitem" class="actnbr-menu__item actnbr-shortlink" href="%1$s"><span class="actnbr-menu__label actnbr-shortlink__text">%2$s</span><span class="actnbr-menu__icon actnbr-shortlink__icon">%3$s</span><span class="actnbr-menu__icon actnbr-shortlink__icon-copied">%4$s</span></a>',
856                                esc_url( $shortlink ),
857                                esc_html__( 'Copy shortlink', 'jetpack-newsletter' ),
858                                self::icon_markup( 'copy', 18 ),
859                                self::icon_markup( 'check', 18 )
860                            );
861                        }
862                        if ( $can_follow && $is_singular ) {
863                            $items[] = self::menu_item(
864                                array(
865                                    'href'  => 'https://wordpress.com/reader/blogs/' . (int) $site_id . '/posts/' . (int) $post_id,
866                                    'label' => __( 'View post in Reader', 'jetpack-newsletter' ),
867                                    'class' => 'actnbr-reader',
868                                )
869                            );
870                        }
871                        if ( $can_follow && ! $is_singular ) {
872                            $items[] = self::menu_item(
873                                array(
874                                    'href'  => 'https://wordpress.com/reader/' . ( $feed_id ? 'feeds/' . (int) $feed_id : 'blogs/' . (int) $site_id ),
875                                    'label' => __( 'View site in Reader', 'jetpack-newsletter' ),
876                                    'class' => 'actnbr-reader',
877                                )
878                            );
879                        }
880                        if ( $is_logged_in && ! $can_customize_site ) {
881                            $items[] = self::menu_item(
882                                array(
883                                    'href'  => $theme_url,
884                                    'label' => __( 'Get theme', 'jetpack-newsletter' ) . ': ' . wp_get_theme()->get( 'Name' ),
885                                    'class' => 'actnbr-theme',
886                                )
887                            );
888                        }
889                        self::menu_group( $items );
890
891                        // Account.
892                        $items = array();
893                        if ( $is_logged_in && $is_following ) {
894                            $items[] = self::menu_item(
895                                array(
896                                    'href'  => 'https://wordpress.com/read/subscriptions/' . (int) $subscription_id,
897                                    'label' => __( 'Manage subscription', 'jetpack-newsletter' ),
898                                    'class' => 'actnbr-follows',
899                                )
900                            );
901                        }
902                        if ( $is_logged_in && ! $is_following ) {
903                            $items[] = self::menu_item(
904                                array(
905                                    'href'  => 'https://wordpress.com/read/subscriptions?s=' . rawurlencode( (string) $site_host ),
906                                    'label' => __( 'Manage subscriptions', 'jetpack-newsletter' ),
907                                    'class' => 'actnbr-follows',
908                                )
909                            );
910                        }
911                        if ( ! $is_logged_in ) {
912                            $items[] = self::menu_item(
913                                array(
914                                    'href'  => 'https://subscribe.wordpress.com/',
915                                    'label' => __( 'Manage subscriptions', 'jetpack-newsletter' ),
916                                    'class' => 'actnbr-subs',
917                                )
918                            );
919                            $items[] = self::menu_item(
920                                array(
921                                    'href'  => $signup_url,
922                                    'label' => __( 'Sign up', 'jetpack-newsletter' ),
923                                    'class' => 'actnbr-signup',
924                                )
925                            );
926                            $items[] = self::menu_item(
927                                array(
928                                    'href'  => $login_url,
929                                    'label' => __( 'Log in', 'jetpack-newsletter' ),
930                                    'class' => 'actnbr-login',
931                                )
932                            );
933                        }
934                        self::menu_group( $items );
935
936                        // Report.
937                        $items = array();
938                        if ( ! $can_customize_site ) {
939                            $report_url = add_query_arg(
940                                'report_url',
941                                $is_singular ? get_permalink( $post_id ) : $site_url,
942                                // phpcs:ignore WPCOM.I18nRules.LocalizedUrl.UnlocalizedUrl
943                                'https://wordpress.com/abuse/'
944                            );
945                            $items[] = self::menu_item(
946                                array(
947                                    'href'  => $report_url,
948                                    'label' => __( 'Report this content', 'jetpack-newsletter' ),
949                                    'class' => 'flb-report',
950                                    'icon'  => 'external',
951                                    'blank' => true,
952                                )
953                            );
954                        }
955                        self::menu_group( $items );
956
957                        // Bar.
958                        $items = array();
959                        if ( $is_logged_in || $can_follow ) {
960                            $items[] = self::menu_item(
961                                array(
962                                    'href'  => '',
963                                    'label' => $is_folded ? __( 'Expand this bar', 'jetpack-newsletter' ) : __( 'Collapse this bar', 'jetpack-newsletter' ),
964                                    'class' => 'actnbr-fold',
965                                )
966                            );
967                        }
968                        if ( current_user_can( 'manage_options' ) ) {
969                            $items[] = self::menu_item(
970                                array(
971                                    'href'  => self::localized_url( 'https://wordpress.com/support/action-bar/#show-or-hide-the-action-bar' ),
972                                    'label' => __( 'Turn off this bar', 'jetpack-newsletter' ),
973                                    'class' => 'actnbr-turn-off',
974                                    'icon'  => 'external',
975                                    'blank' => true,
976                                )
977                            );
978                        }
979                        self::menu_group( $items );
980                        ?>
981                    </div>
982                </li>
983            </ul>
984        </div>
985        <?php
986
987        // Switch back to site language.
988        self::restore_locale();
989    }
990
991    /**
992     * Whether the post can be reblogged and the viewer is allowed to reblog.
993     *
994     * @param int $site_id Blog ID.
995     * @param int $post_id Post ID.
996     * @return bool
997     */
998    private static function can_reblog( $site_id, $post_id ) {
999        if ( ! function_exists( 'wpr_can_reblog_post' ) || ! function_exists( 'wpcom_can_user_make_a_reblog' ) ) {
1000            return false;
1001        }
1002        $post_ok = (bool) wpr_can_reblog_post( $site_id, $post_id );
1003        $user_ok = (bool) wpcom_can_user_make_a_reblog();
1004        return $post_ok && $user_ok;
1005    }
1006
1007    /**
1008     * Whether the WordAds consent manager is on and the visitor is in a GDPR region.
1009     *
1010     * @return bool
1011     */
1012    private static function gdpr_applies() {
1013        if ( ! class_exists( 'WordAds_Consent_Management_Provider' ) && defined( 'WP_CONTENT_DIR' ) ) {
1014            $provider_file = WP_CONTENT_DIR . '/blog-plugins/wordads-classes/class-wordads-consent-management-provider.php';
1015            if ( file_exists( $provider_file ) ) {
1016                require_once $provider_file;
1017            }
1018        }
1019        if ( ! class_exists( 'WordAds_Consent_Management_Provider' ) ) {
1020            return false;
1021        }
1022        // @phan-suppress-next-line PhanUndeclaredClassMethod -- wpcom-only class, guarded by class_exists above.
1023        return \WordAds_Consent_Management_Provider::is_feature_enabled() && \WordAds_Consent_Management_Provider::does_gdpr_apply();
1024    }
1025
1026    /**
1027     * Bump one of the whitelisted action bar stats.
1028     *
1029     * Logged-in clicks land in the `actionbar` MC stat, logged-out clicks in `actionbar_logged_out`.
1030     *
1031     * @param string $stat_value The stat to bump.
1032     */
1033    private static function bump_stat( $stat_value ) {
1034        $whitelist = array(
1035            'clicked_login_link',
1036            'clicked_login_nudge',
1037            'clicked_manage_subs_link',
1038            'clicked_signup_link',
1039            'clicked_site_title',
1040            'clicked_stats',
1041            'copied_shortlink',
1042            'customized',
1043            'edited',
1044            'expanded',
1045            'explored_theme',
1046            'folded',
1047            'followed',
1048            'managed_following',
1049            'privacy_clicked',
1050            'reported_content',
1051            'show_follow_form',
1052            'show_more_menu',
1053            'submit_follow_form',
1054            'unfollowed',
1055            'view_reader',
1056            'comment_clicked',
1057        );
1058
1059        if ( ! in_array( $stat_value, $whitelist, true ) ) {
1060            return;
1061        }
1062
1063        if ( ! function_exists( 'bump_stats_extras' ) ) {
1064            return;
1065        }
1066
1067        $stat_name = 'actionbar';
1068
1069        if ( ! is_user_logged_in() ) {
1070            $stat_name .= '_logged_out';
1071        }
1072
1073        bump_stats_extras( $stat_name, $stat_value );
1074    }
1075
1076    /*
1077     * The three ajax handlers below deliberately skip nonce verification, as the wpcom original did.
1078     * Batcache can serve a logged-in visitor a page whose localized nonce was minted for user 0, so a
1079     * check would reject the request and the folded state would never save. The writes are limited to
1080     * the caller's own fold flag and anonymous counters.
1081     */
1082
1083    /**
1084     * Ajax: remember that the user collapsed the bar.
1085     *
1086     * @return never
1087     */
1088    public static function fold() {
1089        self::bump_stat( 'folded' );
1090
1091        if ( is_user_logged_in() ) {
1092            self::set_folded( get_current_user_id(), true );
1093        }
1094
1095        die;
1096    }
1097
1098    /**
1099     * Ajax: forget that the user collapsed the bar.
1100     *
1101     * @return never
1102     */
1103    public static function unfold() {
1104        self::bump_stat( 'expanded' );
1105
1106        if ( is_user_logged_in() ) {
1107            self::set_folded( get_current_user_id(), false );
1108        }
1109
1110        die;
1111    }
1112
1113    /**
1114     * Ajax: bump a click stat sent by the JS.
1115     *
1116     * @return never
1117     */
1118    public static function ajax_stats() {
1119        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Whitelisted counter bump; see the note above.
1120        $stat_value = isset( $_REQUEST['stat'] ) ? sanitize_key( wp_unslash( $_REQUEST['stat'] ) ) : '';
1121
1122        self::bump_stat( $stat_value );
1123
1124        die;
1125    }
1126
1127    /**
1128     * Add the Action Bar visibility setting to the General settings page.
1129     *
1130     * Stored in the `wpcom_hide_action_bar` option.
1131     */
1132    public static function settings_field() {
1133        add_settings_field( 'wpcom_hide_action_bar', __( 'Action Bar visibility', 'jetpack-newsletter' ), array( __CLASS__, 'settings_field_display' ), 'general', 'default', array( 'label_for' => 'wpcom_hide_action_bar' ) );
1134
1135        register_setting( 'general', 'wpcom_hide_action_bar' );
1136    }
1137
1138    /**
1139     * Render the `wpcom_hide_action_bar` checkbox.
1140     */
1141    public static function settings_field_display() {
1142        ?>
1143        <input type="checkbox" id="wpcom_hide_action_bar" name="wpcom_hide_action_bar" value="1" <?php checked( 1, get_option( 'wpcom_hide_action_bar' ) ); ?> />
1144
1145        <?php esc_html_e( 'Hide the Action Bar on the front end of the site.', 'jetpack-newsletter' ); ?>
1146
1147        <p class="description"><a href="<?php echo esc_url( self::localized_url( 'https://wordpress.com/support/action-bar/' ) ); ?>" data-target="wpcom-help-center"><?php esc_html_e( 'Learn more about the Action Bar', 'jetpack-newsletter' ); ?></a>.</p>
1148        <?php
1149    }
1150}