Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
76.98% covered (warning)
76.98%
311 / 404
33.33% covered (danger)
33.33%
9 / 27
CRAP
0.00% covered (danger)
0.00%
0 / 1
Help_Center
76.98% covered (warning)
76.98%
311 / 404
33.33% covered (danger)
33.33%
9 / 27
348.78
0.00% covered (danger)
0.00%
0 / 1
 __construct
77.78% covered (warning)
77.78%
14 / 18
0.00% covered (danger)
0.00%
0 / 1
6.40
 calypso_preferences_update
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
42
 determine_iso_639_locale
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
3.14
 jetpack_remove_core_help_tab
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 is_proxied
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 init
53.33% covered (warning)
53.33%
8 / 15
0.00% covered (danger)
0.00%
0 / 1
11.98
 get_instance
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_script
82.67% covered (warning)
82.67%
62 / 75
0.00% covered (danger)
0.00%
0 / 1
16.17
 should_show_get_help_label
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 resolve_get_help_label
93.10% covered (success)
93.10%
27 / 29
0.00% covered (danger)
0.00%
0 / 1
10.03
 get_current_site
93.33% covered (success)
93.33%
28 / 30
0.00% covered (danger)
0.00%
0 / 1
5.01
 get_help_center_data
94.59% covered (success)
94.59%
35 / 37
0.00% covered (danger)
0.00%
0 / 1
13.03
 register_rest_api
100.00% covered (success)
100.00%
54 / 54
100.00% covered (success)
100.00%
1 / 1
1
 is_admin_bar
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_block_editor
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 is_wc_admin_home_page
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 is_jetpack_disconnected
83.33% covered (warning)
83.33%
5 / 6
0.00% covered (danger)
0.00%
0 / 1
4.07
 is_loading_on_frontend
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
4
 get_help_center_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 opens_help_center_in_place
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
3
 get_assets_json
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 enqueue_customizer_scripts
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
 add_help_center_container
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 get_active_variant
72.73% covered (warning)
72.73%
16 / 22
0.00% covered (danger)
0.00%
0 / 1
29.95
 add_admin_bar_node
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
6
 get_admin_bar_icons
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_wp_admin_scripts
58.33% covered (warning)
58.33%
7 / 12
0.00% covered (danger)
0.00%
0 / 1
6.81
1<?php
2/**
3 * Help center
4 *
5 * @package automattic/jetpack-help-center
6 */
7
8namespace Automattic\Jetpack\Help_Center;
9
10use Automattic\Jetpack\Status\Host;
11
12/**
13 * Class Help_Center
14 */
15class Help_Center {
16    /**
17     * The package version of the Help Center package.
18     *
19     * @var string
20     */
21    const PACKAGE_VERSION = '0.3.2';
22
23    /**
24     * ExPlat experiment behind the "Get Help" label and the chat-forward opening.
25     *
26     * @var string
27     */
28    const GET_HELP_EXPERIMENT = 'calypso_help_center_get_help_chat_forward';
29
30    /**
31     * Variation of GET_HELP_EXPERIMENT that gets both changes.
32     *
33     * @var string
34     */
35    const GET_HELP_VARIATION = 'treatment';
36
37    /**
38     * Class instance.
39     *
40     * @var Help_Center|null
41     */
42    private static $instance = null;
43
44    /**
45     * WP.com request client.
46     *
47     * @var Wpcom_Request_Client
48     */
49    private $wpcom_request_client;
50
51    /**
52     * Bot slug for new interactions.
53     *
54     * @var string|null
55     */
56    private $new_interactions_bot_slug;
57
58    /**
59     * Bot slug for new logged-out interactions.
60     *
61     * @var string|null
62     */
63    private $new_logged_out_interactions_bot_slug;
64
65    /**
66     * Memoized result of should_show_get_help_label() for this request.
67     *
68     * @var bool|null
69     */
70    private $show_get_help_label = null;
71
72    /**
73     * Whether the current site is a support site.
74     *
75     * @var bool
76     */
77    private $is_support_site = false;
78
79    /**
80     * Whether the current site is a forum site.
81     *
82     * @var bool
83     */
84    private $is_forum_site = false;
85
86    /**
87     * The purchases of the current site.
88     *
89     * @var array
90     */
91    private $purchases = array();
92
93    /**
94     * Help_Center constructor.
95     *
96     * @param Wpcom_Request_Client|null $wpcom_request_client                 WP.com request client.
97     * @param string|null               $new_interactions_bot_slug            Bot slug for new interactions.
98     * @param string|null               $new_logged_out_interactions_bot_slug Bot slug for new logged-out interactions.
99     */
100    public function __construct( ?Wpcom_Request_Client $wpcom_request_client = null, ?string $new_interactions_bot_slug = null, ?string $new_logged_out_interactions_bot_slug = null ) {
101        $this->wpcom_request_client                 = $wpcom_request_client ?? new Jetpack_Wpcom_Request_Client();
102        $this->new_interactions_bot_slug            = $new_interactions_bot_slug;
103        $this->new_logged_out_interactions_bot_slug = $new_logged_out_interactions_bot_slug;
104
105        if ( function_exists( 'wpcom_get_site_purchases' ) ) {
106            $this->purchases = wp_list_filter( wpcom_get_site_purchases(), array( 'product_type' => 'bundle' ) );
107        }
108
109        $blog_id               = get_current_blog_id();
110        $this->is_forum_site   = defined( 'WPCOM_FORUM_BLOG_IDS' ) && in_array( $blog_id, (array) WPCOM_FORUM_BLOG_IDS, true );
111        $this->is_support_site = ( defined( 'WPCOM_SUPPORT_BLOG_IDS' ) && in_array( $blog_id, (array) WPCOM_SUPPORT_BLOG_IDS, true ) ) || $this->is_forum_site;
112
113        // Always register REST API endpoints.
114        add_action( 'rest_api_init', array( $this, 'register_rest_api' ) );
115        add_filter( 'calypso_preferences_update', array( $this, 'calypso_preferences_update' ) );
116
117        // Handle customizer separately.
118        if ( is_customize_preview() ) {
119            add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_customizer_scripts' ) );
120            add_action( 'customize_controls_print_footer_scripts', array( $this, 'add_help_center_container' ) );
121            return;
122        }
123
124        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_wp_admin_scripts' ), 100 );
125        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_wp_admin_scripts' ), 100 );
126        add_filter( 'in_admin_header', array( $this, 'jetpack_remove_core_help_tab' ) );
127        add_action( 'admin_bar_menu', array( $this, 'add_admin_bar_node' ), 12 );
128    }
129
130    /**
131     * Update the calypso preferences.
132     *
133     * @param \stdClass $preferences The preferences.
134     * @return \stdClass The preferences.
135     */
136    public function calypso_preferences_update( $preferences ) {
137        // Check if help_center_router_history exists and is a valid array structure
138        if ( ! isset( $preferences->help_center_router_history ) ||
139            ! is_array( $preferences->help_center_router_history ) ) {
140            return $preferences;
141        }
142
143        $router_history = $preferences->help_center_router_history;
144
145        // Check if entries exist and is an array
146        if ( ! isset( $router_history['entries'] ) ||
147            ! is_array( $router_history['entries'] ) ) {
148            return $preferences;
149        }
150
151        $entries = $router_history['entries'];
152
153        // Limit entries to 50 to prevent spamming entries in the router history.
154        if ( count( $entries ) > 50 ) {
155            // Keep only the last 49 entries and add the root entry at the beginning.
156            $entries = array_slice( $entries, -49 );
157            // Keep the start at root so the back button always works.
158            array_unshift(
159                $entries,
160                array(
161                    'pathname' => '/',
162                    'search'   => '',
163                    'hash'     => '',
164                    'key'      => 'default',
165                    'state'    => null,
166                )
167            );
168
169            // Update the preferences object directly
170            $preferences->help_center_router_history['entries'] = $entries;
171            $preferences->help_center_router_history['index']   = 49;
172        }
173
174        return $preferences;
175    }
176
177    /**
178     * Returns ISO 639 conforming locale string of the current user.
179     *
180     * @return string ISO 639 locale string e.g. "en"
181     */
182    public static function determine_iso_639_locale() {
183        $language = get_user_locale();
184        $language = strtolower( $language );
185
186        if ( in_array( $language, array( 'pt_br', 'pt-br', 'zh_tw', 'zh-tw', 'zh_cn', 'zh-cn' ), true ) ) {
187            $language = str_replace( '_', '-', $language );
188        } else {
189            $language = preg_replace( '/([-_].*)$/i', '', $language );
190        }
191
192        if ( empty( $language ) ) {
193            return 'en';
194        }
195
196        return $language;
197    }
198
199    /**
200     * We prefer to use the Help Center instead of the Help tab.
201     */
202    public function jetpack_remove_core_help_tab() {
203        ?>
204            <style>#contextual-help-link-wrap { display: none; }</style>
205        <?php
206    }
207
208    /**
209     * Returns whether the current request is coming from the a8c proxy.
210     */
211    private static function is_proxied() {
212        return isset( $_SERVER['A8C_PROXIED_REQUEST'] )
213            ? sanitize_text_field( wp_unslash( $_SERVER['A8C_PROXIED_REQUEST'] ) )
214            : defined( 'A8C_PROXIED_REQUEST' ) && A8C_PROXIED_REQUEST;
215    }
216
217    /**
218     * Creates instance.
219     *
220     * @param Wpcom_Request_Client|null $wpcom_request_client                 WP.com request client.
221     * @param string|null               $new_interactions_bot_slug            Bot slug for new interactions.
222     * @param string|null               $new_logged_out_interactions_bot_slug Bot slug for new logged-out interactions.
223     * @return self|null
224     */
225    public static function init( ?Wpcom_Request_Client $wpcom_request_client = null, ?string $new_interactions_bot_slug = null, ?string $new_logged_out_interactions_bot_slug = null ) {
226        $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
227
228        if ( str_contains( $request_uri, 'wp-content/plugins/gutenberg-core' ) || str_contains( $request_uri, 'preview=true' ) ) {
229            return null;
230        }
231
232        if ( self::$instance === null ) {
233            if ( null === $wpcom_request_client ) {
234                /**
235                 * Filters the client used for authenticated WordPress.com requests.
236                 *
237                 * @since 0.1.0
238                 *
239                 * @param Wpcom_Request_Client $wpcom_request_client WP.com request client.
240                 */
241                $wpcom_request_client = apply_filters( 'jetpack_help_center_wpcom_request_client', new Jetpack_Wpcom_Request_Client() );
242
243                if ( ! $wpcom_request_client instanceof Wpcom_Request_Client ) {
244                    _doing_it_wrong(
245                        __METHOD__,
246                        esc_html__( 'The jetpack_help_center_wpcom_request_client filter must return a Wpcom_Request_Client instance.', 'jetpack-help-center' ),
247                        esc_html( self::PACKAGE_VERSION )
248                    );
249                    $wpcom_request_client = new Jetpack_Wpcom_Request_Client();
250                }
251            }
252
253            self::$instance = new self( $wpcom_request_client, $new_interactions_bot_slug, $new_logged_out_interactions_bot_slug );
254        }
255
256        return self::$instance;
257    }
258
259    /**
260     * Returns the singleton instance, or null if init() hasn't run or short-circuited.
261     *
262     * @return self|null
263     */
264    public static function get_instance(): ?self {
265        return self::$instance;
266    }
267
268    /**
269     * Enqueue Help Center assets.
270     *
271     * @param string $variant The variant of the asset file to get.
272     * @param array  $dependencies The asset file to get.
273     * @param string $version The version of the asset file to get.
274     */
275    public function enqueue_script( $variant, $dependencies, $version ) {
276        $script_dependencies = $dependencies ?? array();
277
278        if ( $variant !== 'wp-admin-disconnected' && $variant !== 'gutenberg-disconnected' ) {
279            $locale = self::determine_iso_639_locale();
280
281            if ( 'en' !== $locale ) {
282                // Load translations directly from widgets.wp.com.
283                wp_enqueue_script(
284                    'help-center-translations',
285                    'https://widgets.wp.com/help-center/languages/' . $locale . '-v1.js',
286                    array( 'wp-i18n' ),
287                    $version,
288                    true
289                );
290
291                $script_dependencies[] = 'help-center-translations';
292            }
293        }
294
295        // If the user is not connected, the Help Center icon will link to the support page.
296        // The disconnected version is significantly smaller than the connected version.
297        wp_enqueue_script(
298            'help-center',
299            'https://widgets.wp.com/help-center/help-center-' . $variant . '.min.js',
300            $script_dependencies,
301            $version,
302            true
303        );
304
305        // The node carries an href so the keyboard can reach it, but where the panel opens
306        // in place the click must not navigate. Registered here so a Jetpack-only deploy
307        // behaves, rather than relying on the bundle to cancel it.
308        if ( $this->opens_help_center_in_place() ) {
309            wp_add_inline_script(
310                'help-center',
311                "document.addEventListener( 'click', function ( event ) {"
312                . "if ( event.target.closest( '#wp-admin-bar-help-center > .ab-item' ) ) { event.preventDefault(); }"
313                . '} );',
314                'before'
315            );
316        }
317
318        wp_enqueue_style(
319            'help-center-' . $variant . '-style',
320            'https://widgets.wp.com/help-center/help-center-' . $variant . ( is_rtl() ? '.rtl.css' : '.css' ),
321            array(),
322            $version
323        );
324
325        // The bundle stylesheet sizes the item for an icon alone; a labelled item lays out as a row.
326        wp_add_inline_style(
327            'help-center-' . $variant . '-style',
328            '#wpadminbar #wp-toolbar #wp-admin-bar-help-center .help-center-entry-label{display:none;padding-inline-start:6px;white-space:nowrap;}'
329            . '@media (min-width:783px){'
330            . '#wpadminbar #wp-toolbar #wp-admin-bar-help-center .help-center-entry-label{display:block;}'
331            . '#wpadminbar #wp-toolbar #wp-admin-bar-help-center.has-help-entry-label{width:auto;}'
332            . '#wpadminbar #wp-toolbar #wp-admin-bar-help-center.has-help-entry-label>.ab-item{display:flex;align-items:center;padding:0 11px;}'
333            . '#wpadminbar #wp-toolbar #wp-admin-bar-help-center.has-help-entry-label>.ab-item>span:first-child{display:flex;}'
334            . '#wpadminbar #wp-toolbar #wp-admin-bar-help-center.has-help-entry-label svg{position:static;float:none;margin:0;padding:4px 0;}'
335            . '}'
336        );
337
338        // Core recolours admin bar icons through `.ab-icon::before`, which only reaches the
339        // dashicon font. This icon is an SVG, so it has to follow the item's colour itself.
340        wp_add_inline_style(
341            'help-center-' . $variant . '-style',
342            '#wpadminbar #wp-toolbar #wp-admin-bar-help-center>.ab-item:hover .ab-icon,'
343            . '#wpadminbar #wp-toolbar #wp-admin-bar-help-center>.ab-item:focus .ab-icon{color:inherit;}'
344        );
345
346        // In the block editor the Help Center is already present in the editor toolbar
347        // via SlotFill at viewports >= 600px. Hide the admin bar item at those widths
348        // to avoid showing it in two places; keep it visible on mobile where the admin
349        // bar is the primary navigation and the SlotFill button is hidden.
350        if ( $variant === 'gutenberg' || $variant === 'gutenberg-disconnected' ) {
351            wp_add_inline_style(
352                'help-center-' . $variant . '-style',
353                '@media (min-width:600px){#wpadminbar #wp-admin-bar-help-center{display:none!important;}}'
354            );
355        }
356
357        // This information is only needed for the connected version of the help center.
358        if ( $variant !== 'wp-admin-disconnected' && $variant !== 'gutenberg-disconnected' ) {
359            wp_add_inline_script(
360                'help-center',
361                'if ( typeof helpCenterData === "undefined" ) { var helpCenterData = ' . wp_json_encode(
362                    $this->get_help_center_data( $variant ),
363                    JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP
364                ) . '; }',
365                'before'
366            );
367        }
368
369        $should_enqueue_wp_components = ! is_admin() || ( is_customize_preview() && ( new Host() )->is_wpcom_simple() );
370
371        if ( $should_enqueue_wp_components ) {
372            $stylesheet     = is_rtl() ? 'build/components/style-rtl.css' : 'build/components/style.css';
373            $stylesheet_url = plugins_url( 'gutenberg/' . $stylesheet );
374
375            if ( function_exists( 'gutenberg_url' ) ) {
376                // @phan-suppress-next-line PhanUndeclaredFunction
377                $stylesheet_url = gutenberg_url( $stylesheet );
378            }
379            // Enqueue wp-component styles because they're not enqueued in wp-admin outside of the editor.
380            wp_enqueue_style(
381                'wp-components',
382                $stylesheet_url,
383                array( 'dashicons' ),
384                $version
385            );
386        }
387    }
388
389    /**
390     * Whether the current user is in the treatment of the "Get Help" label experiment.
391     *
392     * Assigns (rendering the entry point is the exposure) and caches per user for an hour.
393     *
394     * @return bool
395     */
396    private function should_show_get_help_label() {
397        if ( null !== $this->show_get_help_label ) {
398            return $this->show_get_help_label;
399        }
400
401        $this->show_get_help_label = $this->resolve_get_help_label();
402
403        return $this->show_get_help_label;
404    }
405
406    /**
407     * Resolves the experiment arm once per request.
408     *
409     * @return bool
410     */
411    private function resolve_get_help_label() {
412        $experiment_name      = self::GET_HELP_EXPERIMENT;
413        $experiment_variation = self::GET_HELP_VARIATION;
414
415        /**
416         * Forces the variation, for QA. Return a variation name, or null to use ExPlat.
417         *
418         * @param string|null $override The forced variation, or null.
419         */
420        $override = apply_filters( 'wpcom_help_center_get_help_label_variation', null );
421        if ( null !== $override ) {
422            return $experiment_variation === $override;
423        }
424
425        $user_id = get_current_user_id();
426        if ( ! $user_id ) {
427            return false;
428        }
429
430        $cache_key     = 'help-center-get-help-label-' . $user_id . '-' . $experiment_name;
431        $cached_result = get_transient( $cache_key );
432        if ( false !== $cached_result ) {
433            return (bool) $cached_result;
434        }
435
436        // Null until ExPlat answers: an unanswered assignment must not be cached as the control.
437        $variation = null;
438
439        if ( ( new Host() )->is_wpcom_simple() ) {
440            $variation = \ExPlat\assign_current_user( $experiment_name );
441        } elseif ( $this->wpcom_request_client->is_user_connected() ) {
442            $request_path = '/experiments/0.1.0/assignments/wpcom';
443            $response     = $this->wpcom_request_client->request(
444                add_query_arg( array( 'experiment_names' => $experiment_name ), $request_path ),
445                'v2'
446            );
447
448            if ( ! is_wp_error( $response ) && 200 === wp_remote_retrieve_response_code( $response ) ) {
449                $data      = json_decode( wp_remote_retrieve_body( $response ), true );
450                $variation = $data['variations'][ $experiment_name ] ?? null;
451            }
452        }
453
454        if ( null === $variation ) {
455            return false;
456        }
457
458        $result = $experiment_variation === $variation;
459        set_transient( $cache_key, $result ? 1 : 0, HOUR_IN_SECONDS );
460
461        return $result;
462    }
463
464    /**
465     * Get current site details.
466     */
467    public function get_current_site() {
468        if ( $this->is_support_site ) {
469            return null;
470        }
471
472        /*
473        * Atomic sites have the WP.com blog ID stored as a Jetpack option. This code deliberately
474        * doesn't use `Jetpack_Options::get_option` so it works even when Jetpack has not been loaded.
475        */
476        $jetpack_options = get_option( 'jetpack_options' );
477        if ( is_array( $jetpack_options ) && isset( $jetpack_options['id'] ) ) {
478            $site = (int) $jetpack_options['id'];
479        } else {
480            $site = get_current_blog_id();
481        }
482
483        $logo_id = get_option( 'site_logo' );
484        $bundles = $this->purchases;
485        $plan    = array_pop( $bundles );
486
487        $return_data = array(
488            'ID'              => $site,
489            'name'            => get_bloginfo( 'name' ),
490            'URL'             => get_bloginfo( 'url' ),
491            'plan'            => array(
492                'product_slug' => $plan->product_slug ?? null,
493            ),
494            'is_wpcom_atomic' => defined( 'IS_ATOMIC' ) && IS_ATOMIC,
495            'jetpack'         => true === apply_filters( 'is_jetpack_site', false, $site ),
496            'logo'            => array(
497                'id'    => $logo_id,
498                'sizes' => array(),
499                'url'   => wp_get_attachment_image_src( $logo_id, 'thumbnail' )[0] ?? '',
500            ),
501            'options'         => array(
502                'launchpad_screen' => get_option( 'launchpad_screen' ),
503                'site_intent'      => get_option( 'site_intent' ),
504                'admin_url'        => get_admin_url(),
505            ),
506        );
507
508        return $return_data;
509    }
510
511    /**
512     * Build the helpCenterData payload for the connected Help Center bundles.
513     *
514     * Exposed so frontend consumers can mount Help Center outside the
515     * admin-only enqueue path without re-implementing the payload
516     * field-for-field.
517     *
518     * Note: this is the payload for the *connected* bundles. The disconnected
519     * variants ('wp-admin-disconnected', 'gutenberg-disconnected') do not
520     * consume helpCenterData and are not valid input here.
521     *
522     * @param string $variant   Bundle variant driving the default sectionName.
523     *                          One of 'wp-admin', 'logged-out', 'customizer',
524     *                          'gutenberg'.
525     * @param array  $overrides Shallow-merged onto the result via array_replace
526     *                          (e.g. array( 'sectionName' => 'landpack' )).
527     *                          Replacing a sub-array (e.g. 'currentUser')
528     *                          replaces it whole â€” no deep merge.
529     * @return array            JSON-ready associative array.
530     */
531    public function get_help_center_data( string $variant = 'wp-admin', array $overrides = array() ): array {
532        $user_id            = get_current_user_id();
533        $user_data          = get_userdata( $user_id );
534        $username           = $user_data ? $user_data->user_login : null;
535        $user_email         = $user_data ? $user_data->user_email : null;
536        $display_name       = $user_data ? $user_data->display_name : null;
537        $avatar_url         = $user_data ? ( function_exists( 'wpcom_get_avatar_url' ) ? wpcom_get_avatar_url( $user_email, 64, '', true )[0] : get_avatar_url( $user_id ) ) : null;
538        $is_commerce_garden = defined( 'IS_COMMERCE_GARDEN' );
539
540        if ( $this->is_forum_site ) {
541            $section_name = 'wp.com/forums';
542        } elseif ( $this->is_support_site ) {
543            $section_name = 'wp.com/support';
544        } else {
545            $section_name = $variant;
546        }
547
548        $data = array(
549            'isProxied'        => boolval( self::is_proxied() ),
550            'isSU'             => defined( 'WPCOM_SUPPORT_SESSION' ) && WPCOM_SUPPORT_SESSION,
551            'isSSP'            => isset( $_COOKIE['ssp'] ),
552            'sectionName'      => $section_name,
553            'isCommerceGarden' => $is_commerce_garden,
554            'currentUser'      => array(
555                'ID'           => $user_id,
556                'username'     => $username,
557                'display_name' => $display_name,
558                'avatar_URL'   => $avatar_url,
559                'email'        => $user_email,
560                'is_a11n'      => function_exists( '\is_automattician' ) && \is_automattician( $user_id ),
561            ),
562            'site'             => $this->get_current_site(),
563            'locale'           => self::determine_iso_639_locale(),
564        );
565
566        if ( null !== $this->new_interactions_bot_slug ) {
567            $data['newInteractionsBotSlug'] = $this->new_interactions_bot_slug;
568        }
569
570        if ( null !== $this->new_logged_out_interactions_bot_slug ) {
571            $data['newLoggedOutInteractionsBotSlug'] = $this->new_logged_out_interactions_bot_slug;
572        }
573
574        // The editor toolbar draws its own entry point.
575        if ( $this->should_show_get_help_label() ) {
576            $data['entryLabel'] = __( 'Get Help', 'jetpack-help-center' );
577            // The Help Center reads the variation from here and opens on the AI chat.
578            $data['experimentVariations'] = array( self::GET_HELP_EXPERIMENT => self::GET_HELP_VARIATION );
579        }
580
581        return array_replace( $data, $overrides );
582    }
583
584    /**
585     * Register the Help Center endpoints.
586     */
587    public function register_rest_api() {
588        require_once __DIR__ . '/class-wp-rest-help-center-authenticate.php';
589        $controller = new WP_REST_Help_Center_Authenticate( $this->wpcom_request_client );
590        $controller->register_rest_route();
591
592        require_once __DIR__ . '/class-wp-rest-help-center-sibyl.php';
593        $controller = new WP_REST_Help_Center_Sibyl( $this->wpcom_request_client );
594        $controller->register_rest_route();
595
596        require_once __DIR__ . '/class-wp-rest-help-center-support-status.php';
597        $controller = new WP_REST_Help_Center_Support_Status( $this->wpcom_request_client );
598        $controller->register_rest_route();
599
600        require_once __DIR__ . '/class-wp-rest-help-center-search.php';
601        $controller = new WP_REST_Help_Center_Search( $this->wpcom_request_client );
602        $controller->register_rest_route();
603
604        require_once __DIR__ . '/class-wp-rest-help-center-jetpack-search-ai.php';
605        $controller = new WP_REST_Help_Center_Jetpack_Search_AI( $this->wpcom_request_client );
606        $controller->register_rest_route();
607
608        require_once __DIR__ . '/class-wp-rest-help-center-jetpack-connection-health.php';
609        $controller = new WP_REST_Help_Center_Jetpack_Connection_Health( $this->wpcom_request_client );
610        $controller->register_rest_route();
611
612        require_once __DIR__ . '/class-wp-rest-help-center-fetch-post.php';
613        $controller = new WP_REST_Help_Center_Fetch_Post( $this->wpcom_request_client );
614        $controller->register_rest_route();
615
616        require_once __DIR__ . '/class-wp-rest-help-center-article-rating.php';
617        $controller = new WP_REST_Help_Center_Article_Rating( $this->wpcom_request_client );
618        $controller->register_rest_route();
619
620        require_once __DIR__ . '/class-wp-rest-help-center-ticket.php';
621        $controller = new WP_REST_Help_Center_Ticket( $this->wpcom_request_client );
622        $controller->register_rest_route();
623
624        require_once __DIR__ . '/class-wp-rest-help-center-forum.php';
625        $controller = new WP_REST_Help_Center_Forum( $this->wpcom_request_client );
626        $controller->register_rest_route();
627
628        require_once __DIR__ . '/class-wp-rest-help-center-support-activity.php';
629        $controller = new WP_REST_Help_Center_Support_Activity( $this->wpcom_request_client );
630        $controller->register_rest_route();
631
632        require_once __DIR__ . '/class-wp-rest-help-center-support-interactions.php';
633        $controller = new WP_REST_Help_Center_Support_Interactions( $this->wpcom_request_client );
634        $controller->register_rest_route();
635
636        require_once __DIR__ . '/class-wp-rest-help-center-user-fields.php';
637        $controller = new WP_REST_Help_Center_User_Fields( $this->wpcom_request_client );
638        $controller->register_rest_route();
639
640        require_once __DIR__ . '/class-wp-rest-help-center-odie.php';
641        $controller = new WP_REST_Help_Center_Odie( $this->wpcom_request_client );
642        $controller->register_rest_route();
643
644        require_once __DIR__ . '/class-wp-rest-help-center-persisted-open-state.php';
645        $controller = new WP_REST_Help_Center_Persisted_Open_State( $this->wpcom_request_client );
646        $controller->register_rest_route();
647
648        require_once __DIR__ . '/class-wp-rest-help-center-email-support-enabled.php';
649        $controller = new WP_REST_Help_Center_Email_Support_Enabled( $this->wpcom_request_client );
650        $controller->register_rest_route();
651
652        require_once __DIR__ . '/class-wp-rest-help-center-ticket-csat.php';
653        $controller = new WP_REST_Help_Center_Ticket_CSAT( $this->wpcom_request_client );
654        $controller->register_rest_route();
655
656        require_once __DIR__ . '/class-wp-rest-help-center-cta.php';
657        $controller = new WP_REST_Help_Center_CTA( $this->wpcom_request_client );
658        $controller->register_rest_route();
659    }
660
661    /**
662     * Returns true if the admin bar is set.
663     */
664    public function is_admin_bar() {
665        global $wp_admin_bar;
666        return is_object( $wp_admin_bar );
667    }
668
669    /**
670     * Returns true if the current screen if the block editor.
671     */
672    public function is_block_editor() {
673        global $current_screen;
674
675        if ( ! $current_screen ) {
676            return false;
677        }
678
679        // widgets screen does have the block editor but also no Gutenberg top bar.
680        return $current_screen->is_block_editor() && $current_screen->id !== 'widgets';
681    }
682
683    /**
684     * Returns true if the current screen is the woo commerce admin home page.
685     */
686    private function is_wc_admin_home_page() {
687        global $current_screen;
688        return $current_screen && $current_screen->id === 'woocommerce_page_wc-admin';
689    }
690
691    /**
692     * Returns true if the current user is connected through Jetpack
693     */
694    public function is_jetpack_disconnected() {
695        $blog_id = get_current_blog_id();
696
697        if ( defined( 'IS_ATOMIC' ) && IS_ATOMIC ) {
698            return ! $this->wpcom_request_client->is_user_connected();
699        }
700
701        if ( true === apply_filters( 'is_jetpack_site', false, $blog_id ) ) {
702            return ! $this->wpcom_request_client->is_user_connected();
703        }
704
705        return false;
706    }
707
708    /**
709     * Returns true if...
710     * 1. The current user can edit posts.
711     * 2. The current user is a member of the blog.
712     * 3. The current request is not in the admin.
713     * 4. The current request is not in the block editor.
714     *
715     * @return bool True if the this is being loaded on the frontend.
716     */
717    public function is_loading_on_frontend() {
718        $can_edit_posts = current_user_can( 'edit_posts' ) && is_user_member_of_blog();
719
720        return ! is_admin() && ! $this->is_block_editor() && $can_edit_posts;
721    }
722
723    /**
724     * Returns the URL for the Help Center redirect.
725     *
726     * Always set on the admin bar node: without an href WordPress renders the item as a
727     * div, which the keyboard cannot reach and the admin bar's hover styles skip. Where
728     * the panel is available its bundle opens it and cancels the navigation, so this is
729     * the fallback for disconnected sites and for a failed script load.
730     *
731     * @return string
732     */
733    public function get_help_center_url() {
734        return 'https://wordpress.com/help?help-center=home';
735    }
736
737    /**
738     * Whether the Help Center panel opens in place instead of following the node's href.
739     *
740     * @return bool
741     */
742    public function opens_help_center_in_place() {
743        return ! $this->is_jetpack_disconnected()
744            && ! ( $this->is_loading_on_frontend() && ! $this->is_support_site );
745    }
746
747    /**
748     * Get the asset via file-system on wpcom and via network on Atomic sites.
749     *
750     * @param string $filepath The URL to download the asset file from.
751     */
752    private static function get_assets_json( $filepath ) {
753        $accessible_directly = file_exists( ABSPATH . '/' . $filepath );
754        if ( $accessible_directly ) {
755            return json_decode( file_get_contents( ABSPATH . '/' . $filepath ), true );
756        }
757        $request = wp_remote_get( 'https://' . $filepath );
758        if ( is_wp_error( $request ) ) {
759            return null;
760        }
761        return json_decode( wp_remote_retrieve_body( $request ), true );
762    }
763
764    /**
765     * Enqueue Help Center assets for the customizer.
766     */
767    public function enqueue_customizer_scripts() {
768        if ( $this->is_jetpack_disconnected() ) {
769            $variant = 'wp-admin-disconnected';
770        } else {
771            $variant = 'customizer';
772        }
773
774        $cache_key  = 'help-center-asset-' . $variant . '.asset.json';
775        $asset_file = get_transient( $cache_key );
776
777        if ( false === $asset_file ) {
778            $asset_file = self::get_assets_json( 'widgets.wp.com/help-center/help-center-' . $variant . '.asset.json' );
779            if ( null === $asset_file ) {
780                return;
781            }
782            set_transient( $cache_key, $asset_file, HOUR_IN_SECONDS );
783        }
784
785        // When the request is proxied, use a random cache buster as the version for easier debugging.
786        $version = self::is_proxied() ? wp_rand() : $asset_file['version'];
787
788        $this->enqueue_script( $variant, $asset_file['dependencies'], $version );
789    }
790
791    /**
792     * Add Help Center container div in customizer.
793     */
794    public function add_help_center_container() {
795        ?>
796        <div id="help-center-customizer"></div>
797        <?php
798    }
799
800    /**
801     * Which Help Center variant this request gets, or null when it gets none.
802     *
803     * @return string|null 'wp-admin', 'wp-admin-disconnected', 'gutenberg', 'gutenberg-disconnected', 'logged-out', or null.
804     */
805    private function get_active_variant() {
806        if ( $this->is_wc_admin_home_page() ) {
807            return null;
808        }
809
810        require_once ABSPATH . 'wp-admin/includes/screen.php';
811
812        $can_edit_posts = current_user_can( 'edit_posts' ) && is_user_member_of_blog();
813        $is_p2          = str_contains( get_stylesheet(), 'pub/p2' ) || function_exists( '\WPForTeams\is_wpforteams_site' ) && is_wpforteams_site( get_current_blog_id() );
814
815        /**
816         * Filters whether to load the logged-out Help Center bundle on the current frontend request.
817         *
818         * Consumers can use this filter to opt public-facing surfaces into the
819         * Help Center without taking ownership of its asset-loading logic.
820         *
821         * @since 0.2.0
822         *
823         * @param bool $should_load Whether to load the logged-out Help Center bundle.
824         */
825        $should_load_logged_out = ! is_admin()
826            && (bool) apply_filters( 'jetpack_help_center_should_load_logged_out', false );
827
828        // We will show the help center icon in the admin bar when;
829        // 1. On wp-admin
830        // 2. On the front end of the site if the current user can edit posts
831        // 3. On the front end of the site and the theme is not P2
832        // 4. If it is the frontend we show the disconnected version of the help center.
833        if ( ! is_admin() && ( ! $can_edit_posts || $is_p2 ) && ! $this->is_support_site && ! $should_load_logged_out ) {
834            return null;
835        }
836
837        // Do not load Help Center for logged-out users if we are not on support sites.
838        if ( ! is_user_logged_in() && ! $this->is_support_site && ! $should_load_logged_out ) {
839            return null;
840        }
841
842        $suffix = $this->is_jetpack_disconnected() ? '-disconnected' : '';
843
844        if ( $should_load_logged_out ) {
845            $variant = 'logged-out';
846        } elseif ( $this->is_support_site ) {
847            if ( ! is_user_logged_in() ) {
848                $variant = 'logged-out';
849            } else {
850                $variant = ( $this->is_block_editor() ? 'gutenberg' : 'wp-admin' ) . $suffix;
851            }
852        } elseif ( $this->is_loading_on_frontend() ) {
853            $variant = 'wp-admin-disconnected';
854        } else {
855            $variant = ( $this->is_block_editor() ? 'gutenberg' : 'wp-admin' ) . $suffix;
856        }
857
858        return $variant;
859    }
860
861    /**
862     * Add the Help Center "?" to the admin bar.
863     *
864     * Eligibility is resolved here, not at hook time: the admin-bar REST endpoints fire
865     * `admin_bar_menu` without enqueueing scripts.
866     *
867     * @param \WP_Admin_Bar $wp_admin_bar The WP_Admin_Bar instance.
868     */
869    public function add_admin_bar_node( $wp_admin_bar ) {
870        $variant = $this->get_active_variant();
871        if ( ! in_array( $variant, array( 'wp-admin', 'wp-admin-disconnected', 'gutenberg', 'gutenberg-disconnected' ), true ) ) {
872            return;
873        }
874
875        $show_label = $this->should_show_get_help_label();
876        // Calypso renders `menu_title` as the entry point's label, so it stays empty without one.
877        $menu_title = $show_label ? __( 'Get Help', 'jetpack-help-center' ) : '';
878        $tooltip    = $show_label ? $menu_title : __( 'Help Center', 'jetpack-help-center' );
879        $meta       = array(
880            'menu_title' => $menu_title,
881            'icon'       => 'help',
882            'html'       => '<div id="help-center-masterbar" />',
883            'class'      => 'menupop',
884            'target'     => '_blank',
885        );
886        if ( $show_label ) {
887            $meta['class'] .= ' has-help-entry-label';
888        }
889
890        $title = '<span title="' . esc_attr( $tooltip ) . '">' . self::get_admin_bar_icons() . '</span>';
891        if ( $show_label ) {
892            $title .= '<span class="help-center-entry-label" aria-hidden="true"><span>' . esc_html( $menu_title ) . '</span></span>';
893        }
894
895        $wp_admin_bar->add_menu(
896            array(
897                'id'     => 'help-center',
898                'title'  => $title,
899                'parent' => 'top-secondary',
900                'href'   => $this->get_help_center_url(),
901                'meta'   => $meta,
902            )
903        );
904    }
905
906    /**
907     * The entry point's icons: the default one, and the one the unread badge swaps in.
908     *
909     * Both are always rendered; the stylesheet shows one at a time.
910     *
911     * @return string
912     */
913    private static function get_admin_bar_icons() {
914        return '<svg id="help-center-icon" class="ab-icon" width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">'
915            . '<path fill="currentColor" fill-rule="evenodd" clip-rule="evenodd" d="M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10 10-4.477 10-10S17.523 2 12 2zm-1 16v-2h2v2h-2zm2-3v-1.141A3.991 3.991 0 0016 10a4 4 0 00-8 0h2c0-1.103.897-2 2-2s2 .897 2 2-.897 2-2 2a1 1 0 00-1 1v2h2z" />'
916            . '</svg>'
917            . '<svg id="help-center-icon-with-notification" class="ab-icon" width="24" height="24" viewBox="0 0 25 24" fill="none" xmlns="http://www.w3.org/2000/svg">'
918            . '<path d="M12 2C6.477 2 2 6.477 2 12C2 17.523 6.477 22 12 22C17.523 22 22 17.523 22 12C22 6.477 17.523 2 12 2ZM13 18H11V16H13V18ZM13 13.859V15H11V13C11 12.448 11.448 12 12 12C13.103 12 14 11.103 14 10C14 8.897 13.103 8 12 8C10.897 8 10 8.897 10 10H8C8 7.791 9.791 6 12 6C14.209 6 16 7.791 16 10C16 11.862 14.722 13.413 13 13.859Z" fill="currentColor"/>'
919            . '<circle cx="20" cy="3.5" r="4.3" fill="#e65054" stroke="#1d2327" stroke-width="2"/>'
920            . '</svg>';
921    }
922
923    /**
924     * Enqueue the Help Center bundle for this request's variant.
925     */
926    public function enqueue_wp_admin_scripts() {
927        $variant = $this->get_active_variant();
928        if ( null === $variant ) {
929            return;
930        }
931
932        $cache_key  = 'help-center-asset-' . $variant . '.asset.json';
933        $asset_file = get_transient( $cache_key );
934
935        if ( false === $asset_file ) {
936            $asset_file = self::get_assets_json( 'widgets.wp.com/help-center/help-center-' . $variant . '.asset.json' );
937            if ( null === $asset_file ) {
938                return;
939            }
940            set_transient( $cache_key, $asset_file, HOUR_IN_SECONDS );
941        }
942
943        // When the request is proxied, use a random cache buster as the version for easier debugging.
944        $version = self::is_proxied() ? wp_rand() : $asset_file['version'];
945
946        $this->enqueue_script( $variant, $asset_file['dependencies'], $version );
947    }
948}