Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
57.02% covered (warning)
57.02%
199 / 349
13.64% covered (danger)
13.64%
3 / 22
CRAP
0.00% covered (danger)
0.00%
0 / 1
Help_Center
57.02% covered (warning)
57.02%
199 / 349
13.64% covered (danger)
13.64%
3 / 22
1386.49
0.00% covered (danger)
0.00%
0 / 1
 __construct
76.47% covered (warning)
76.47%
13 / 17
0.00% covered (danger)
0.00%
0 / 1
6.47
 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
52.00% covered (warning)
52.00%
39 / 75
0.00% covered (danger)
0.00%
0 / 1
69.77
 is_menu_panel_enabled
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
90
 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.12% covered (success)
94.12%
32 / 34
0.00% covered (danger)
0.00%
0 / 1
12.03
 register_rest_api
100.00% covered (success)
100.00%
48 / 48
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
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 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
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
20
 get_help_center_url
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
 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
 enqueue_wp_admin_scripts
53.33% covered (warning)
53.33%
16 / 30
0.00% covered (danger)
0.00%
0 / 1
82.54
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     * Class instance.
25     *
26     * @var Help_Center|null
27     */
28    private static $instance = null;
29
30    /**
31     * WP.com request client.
32     *
33     * @var Wpcom_Request_Client
34     */
35    private $wpcom_request_client;
36
37    /**
38     * Bot slug for new interactions.
39     *
40     * @var string|null
41     */
42    private $new_interactions_bot_slug;
43
44    /**
45     * Bot slug for new logged-out interactions.
46     *
47     * @var string|null
48     */
49    private $new_logged_out_interactions_bot_slug;
50
51    /**
52     * Whether the current site is a support site.
53     *
54     * @var bool
55     */
56    private $is_support_site = false;
57
58    /**
59     * Whether the current site is a forum site.
60     *
61     * @var bool
62     */
63    private $is_forum_site = false;
64
65    /**
66     * The purchases of the current site.
67     *
68     * @var array
69     */
70    private $purchases = array();
71
72    /**
73     * Help_Center constructor.
74     *
75     * @param Wpcom_Request_Client|null $wpcom_request_client                 WP.com request client.
76     * @param string|null               $new_interactions_bot_slug            Bot slug for new interactions.
77     * @param string|null               $new_logged_out_interactions_bot_slug Bot slug for new logged-out interactions.
78     */
79    public function __construct( ?Wpcom_Request_Client $wpcom_request_client = null, ?string $new_interactions_bot_slug = null, ?string $new_logged_out_interactions_bot_slug = null ) {
80        $this->wpcom_request_client                 = $wpcom_request_client ?? new Jetpack_Wpcom_Request_Client();
81        $this->new_interactions_bot_slug            = $new_interactions_bot_slug;
82        $this->new_logged_out_interactions_bot_slug = $new_logged_out_interactions_bot_slug;
83
84        if ( function_exists( 'wpcom_get_site_purchases' ) ) {
85            $this->purchases = wp_list_filter( wpcom_get_site_purchases(), array( 'product_type' => 'bundle' ) );
86        }
87
88        $blog_id               = get_current_blog_id();
89        $this->is_forum_site   = defined( 'WPCOM_FORUM_BLOG_IDS' ) && in_array( $blog_id, (array) WPCOM_FORUM_BLOG_IDS, true );
90        $this->is_support_site = ( defined( 'WPCOM_SUPPORT_BLOG_IDS' ) && in_array( $blog_id, (array) WPCOM_SUPPORT_BLOG_IDS, true ) ) || $this->is_forum_site;
91
92        // Always register REST API endpoints.
93        add_action( 'rest_api_init', array( $this, 'register_rest_api' ) );
94        add_filter( 'calypso_preferences_update', array( $this, 'calypso_preferences_update' ) );
95
96        // Handle customizer separately.
97        if ( is_customize_preview() ) {
98            add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_customizer_scripts' ) );
99            add_action( 'customize_controls_print_footer_scripts', array( $this, 'add_help_center_container' ) );
100            return;
101        }
102
103        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_wp_admin_scripts' ), 100 );
104        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_wp_admin_scripts' ), 100 );
105        add_filter( 'in_admin_header', array( $this, 'jetpack_remove_core_help_tab' ) );
106    }
107
108    /**
109     * Update the calypso preferences.
110     *
111     * @param \stdClass $preferences The preferences.
112     * @return \stdClass The preferences.
113     */
114    public function calypso_preferences_update( $preferences ) {
115        // Check if help_center_router_history exists and is a valid array structure
116        if ( ! isset( $preferences->help_center_router_history ) ||
117            ! is_array( $preferences->help_center_router_history ) ) {
118            return $preferences;
119        }
120
121        $router_history = $preferences->help_center_router_history;
122
123        // Check if entries exist and is an array
124        if ( ! isset( $router_history['entries'] ) ||
125            ! is_array( $router_history['entries'] ) ) {
126            return $preferences;
127        }
128
129        $entries = $router_history['entries'];
130
131        // Limit entries to 50 to prevent spamming entries in the router history.
132        if ( count( $entries ) > 50 ) {
133            // Keep only the last 49 entries and add the root entry at the beginning.
134            $entries = array_slice( $entries, -49 );
135            // Keep the start at root so the back button always works.
136            array_unshift(
137                $entries,
138                array(
139                    'pathname' => '/',
140                    'search'   => '',
141                    'hash'     => '',
142                    'key'      => 'default',
143                    'state'    => null,
144                )
145            );
146
147            // Update the preferences object directly
148            $preferences->help_center_router_history['entries'] = $entries;
149            $preferences->help_center_router_history['index']   = 49;
150        }
151
152        return $preferences;
153    }
154
155    /**
156     * Returns ISO 639 conforming locale string of the current user.
157     *
158     * @return string ISO 639 locale string e.g. "en"
159     */
160    public static function determine_iso_639_locale() {
161        $language = get_user_locale();
162        $language = strtolower( $language );
163
164        if ( in_array( $language, array( 'pt_br', 'pt-br', 'zh_tw', 'zh-tw', 'zh_cn', 'zh-cn' ), true ) ) {
165            $language = str_replace( '_', '-', $language );
166        } else {
167            $language = preg_replace( '/([-_].*)$/i', '', $language );
168        }
169
170        if ( empty( $language ) ) {
171            return 'en';
172        }
173
174        return $language;
175    }
176
177    /**
178     * We prefer to use the Help Center instead of the Help tab.
179     */
180    public function jetpack_remove_core_help_tab() {
181        ?>
182            <style>#contextual-help-link-wrap { display: none; }</style>
183        <?php
184    }
185
186    /**
187     * Returns whether the current request is coming from the a8c proxy.
188     */
189    private static function is_proxied() {
190        return isset( $_SERVER['A8C_PROXIED_REQUEST'] )
191            ? sanitize_text_field( wp_unslash( $_SERVER['A8C_PROXIED_REQUEST'] ) )
192            : defined( 'A8C_PROXIED_REQUEST' ) && A8C_PROXIED_REQUEST;
193    }
194
195    /**
196     * Creates instance.
197     *
198     * @param Wpcom_Request_Client|null $wpcom_request_client                 WP.com request client.
199     * @param string|null               $new_interactions_bot_slug            Bot slug for new interactions.
200     * @param string|null               $new_logged_out_interactions_bot_slug Bot slug for new logged-out interactions.
201     * @return self|null
202     */
203    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 ) {
204        $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
205
206        if ( str_contains( $request_uri, 'wp-content/plugins/gutenberg-core' ) || str_contains( $request_uri, 'preview=true' ) ) {
207            return null;
208        }
209
210        if ( self::$instance === null ) {
211            if ( null === $wpcom_request_client ) {
212                /**
213                 * Filters the client used for authenticated WordPress.com requests.
214                 *
215                 * @since 0.1.0
216                 *
217                 * @param Wpcom_Request_Client $wpcom_request_client WP.com request client.
218                 */
219                $wpcom_request_client = apply_filters( 'jetpack_help_center_wpcom_request_client', new Jetpack_Wpcom_Request_Client() );
220
221                if ( ! $wpcom_request_client instanceof Wpcom_Request_Client ) {
222                    _doing_it_wrong(
223                        __METHOD__,
224                        esc_html__( 'The jetpack_help_center_wpcom_request_client filter must return a Wpcom_Request_Client instance.', 'jetpack-help-center' ),
225                        esc_html( self::PACKAGE_VERSION )
226                    );
227                    $wpcom_request_client = new Jetpack_Wpcom_Request_Client();
228                }
229            }
230
231            self::$instance = new self( $wpcom_request_client, $new_interactions_bot_slug, $new_logged_out_interactions_bot_slug );
232        }
233
234        return self::$instance;
235    }
236
237    /**
238     * Returns the singleton instance, or null if init() hasn't run or short-circuited.
239     *
240     * @return self|null
241     */
242    public static function get_instance(): ?self {
243        return self::$instance;
244    }
245
246    /**
247     * Enqueue Help Center assets.
248     *
249     * @param string $variant The variant of the asset file to get.
250     * @param array  $dependencies The asset file to get.
251     * @param string $version The version of the asset file to get.
252     */
253    public function enqueue_script( $variant, $dependencies, $version ) {
254        $script_dependencies = $dependencies ?? array();
255
256        if ( $variant === 'wp-admin' || $variant === 'wp-admin-disconnected' || $variant === 'gutenberg' || $variant === 'gutenberg-disconnected' ) {
257            add_action(
258                'admin_bar_menu',
259                function ( $wp_admin_bar ) {
260                    $wp_admin_bar->add_menu(
261                        array(
262                            'id'     => 'help-center',
263                            'title'  => '<span title="' . __( 'Help Center', 'jetpack-help-center' ) . '"><svg id="help-center-icon" class="ab-icon" width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
264                                                <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" />
265                                            </svg>
266                                            <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">
267                                                <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"/>
268                                                <circle cx="20" cy="3.5" r="4.3" fill="#e65054" stroke="#1d2327" stroke-width="2"/>
269                                            </svg>
270                                        </span>',
271                            'parent' => 'top-secondary',
272                            'href'   => $this->get_help_center_url(),
273                            'meta'   => array(
274                                'html'   => '<div id="help-center-masterbar" />',
275                                'class'  => 'menupop',
276                                'target' => '_blank',
277                            ),
278                        )
279                    );
280                },
281                // Add the help center icon to the admin bar after the reader icon.
282                12
283            );
284
285            if ( is_user_logged_in() && $variant === 'wp-admin' && $this->is_menu_panel_enabled() ) {
286                // Initialize the help center menu panel
287                require_once __DIR__ . '/class-help-center-menu-panel.php';
288                Help_Center_Menu_Panel::init();
289            }
290        }
291
292        if ( $variant !== 'wp-admin-disconnected' && $variant !== 'gutenberg-disconnected' ) {
293            $locale = self::determine_iso_639_locale();
294
295            if ( 'en' !== $locale ) {
296                // Load translations directly from widgets.wp.com.
297                wp_enqueue_script(
298                    'help-center-translations',
299                    'https://widgets.wp.com/help-center/languages/' . $locale . '-v1.js',
300                    array( 'wp-i18n' ),
301                    $version,
302                    true
303                );
304
305                $script_dependencies[] = 'help-center-translations';
306            }
307        }
308
309        // If the user is not connected, the Help Center icon will link to the support page.
310        // The disconnected version is significantly smaller than the connected version.
311        wp_enqueue_script(
312            'help-center',
313            'https://widgets.wp.com/help-center/help-center-' . $variant . '.min.js',
314            $script_dependencies,
315            $version,
316            true
317        );
318
319        wp_enqueue_style(
320            'help-center-' . $variant . '-style',
321            'https://widgets.wp.com/help-center/help-center-' . $variant . ( is_rtl() ? '.rtl.css' : '.css' ),
322            array(),
323            $version
324        );
325
326        // In the block editor the Help Center is already present in the editor toolbar
327        // via SlotFill at viewports >= 600px. Hide the admin bar item at those widths
328        // to avoid showing it in two places; keep it visible on mobile where the admin
329        // bar is the primary navigation and the SlotFill button is hidden.
330        if ( $variant === 'gutenberg' || $variant === 'gutenberg-disconnected' ) {
331            wp_add_inline_style(
332                'help-center-' . $variant . '-style',
333                '@media (min-width:600px){#wpadminbar #wp-admin-bar-help-center{display:none!important;}}'
334            );
335        }
336
337        // This information is only needed for the connected version of the help center.
338        if ( $variant !== 'wp-admin-disconnected' && $variant !== 'gutenberg-disconnected' ) {
339            wp_add_inline_script(
340                'help-center',
341                'if ( typeof helpCenterData === "undefined" ) { var helpCenterData = ' . wp_json_encode(
342                    $this->get_help_center_data( $variant ),
343                    JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP
344                ) . '; }',
345                'before'
346            );
347        }
348
349        $should_enqueue_wp_components = ! is_admin() || ( is_customize_preview() && ( new Host() )->is_wpcom_simple() );
350
351        if ( $should_enqueue_wp_components ) {
352            $stylesheet     = is_rtl() ? 'build/components/style-rtl.css' : 'build/components/style.css';
353            $stylesheet_url = plugins_url( 'gutenberg/' . $stylesheet );
354
355            if ( function_exists( 'gutenberg_url' ) ) {
356                // @phan-suppress-next-line PhanUndeclaredFunction
357                $stylesheet_url = gutenberg_url( $stylesheet );
358            }
359            // Enqueue wp-component styles because they're not enqueued in wp-admin outside of the editor.
360            wp_enqueue_style(
361                'wp-components',
362                $stylesheet_url,
363                array( 'dashicons' ),
364                $version
365            );
366        }
367    }
368
369    /**
370     * Returns whether the menu panel experiment is enabled for the current user.
371     *
372     * @return boolean True if the menu panel experiment variation is enabled, false otherwise.
373     */
374    private function is_menu_panel_enabled() {
375        $experiment_name      = 'calypso_help_center_menu_popover_increase_exposure';
376        $experiment_variation = 'menu_popover';
377        $user_id              = get_current_user_id();
378        $cache_key            = 'help-center-menu-panel-enabled-' . $user_id . '-' . $experiment_name;
379
380        // Check cache first.
381        $cached_result = get_transient( $cache_key );
382        if ( false !== $cached_result ) {
383            return (bool) $cached_result;
384        }
385
386        $result = false;
387
388        if ( ( new Host() )->is_wpcom_simple() ) {
389            $result = $experiment_variation === \ExPlat\assign_current_user( $experiment_name );
390        } elseif ( $this->wpcom_request_client->is_user_connected() ) {
391            $request_path = '/experiments/0.1.0/assignments/calypso';
392            $response     = $this->wpcom_request_client->request(
393                add_query_arg( array( 'experiment_name' => $experiment_name ), $request_path ),
394                'v2'
395            );
396
397            if ( ! is_wp_error( $response ) ) {
398                $response_code = wp_remote_retrieve_response_code( $response );
399                if ( 200 === $response_code ) {
400                    $data = json_decode( wp_remote_retrieve_body( $response ), true );
401                    if ( isset( $data['variations'] ) && isset( $data['variations'][ $experiment_name ] ) ) {
402                        $variation = $data['variations'][ $experiment_name ];
403                        $result    = $experiment_variation === $variation;
404                    }
405                }
406            }
407        }
408
409        // Cache the result for 1 hour.
410        set_transient( $cache_key, $result ? 1 : 0, HOUR_IN_SECONDS );
411
412        return $result;
413    }
414
415    /**
416     * Get current site details.
417     */
418    public function get_current_site() {
419        if ( $this->is_support_site ) {
420            return null;
421        }
422
423        /*
424        * Atomic sites have the WP.com blog ID stored as a Jetpack option. This code deliberately
425        * doesn't use `Jetpack_Options::get_option` so it works even when Jetpack has not been loaded.
426        */
427        $jetpack_options = get_option( 'jetpack_options' );
428        if ( is_array( $jetpack_options ) && isset( $jetpack_options['id'] ) ) {
429            $site = (int) $jetpack_options['id'];
430        } else {
431            $site = get_current_blog_id();
432        }
433
434        $logo_id = get_option( 'site_logo' );
435        $bundles = $this->purchases;
436        $plan    = array_pop( $bundles );
437
438        $return_data = array(
439            'ID'              => $site,
440            'name'            => get_bloginfo( 'name' ),
441            'URL'             => get_bloginfo( 'url' ),
442            'plan'            => array(
443                'product_slug' => $plan->product_slug ?? null,
444            ),
445            'is_wpcom_atomic' => defined( 'IS_ATOMIC' ) && IS_ATOMIC,
446            'jetpack'         => true === apply_filters( 'is_jetpack_site', false, $site ),
447            'logo'            => array(
448                'id'    => $logo_id,
449                'sizes' => array(),
450                'url'   => wp_get_attachment_image_src( $logo_id, 'thumbnail' )[0] ?? '',
451            ),
452            'options'         => array(
453                'launchpad_screen' => get_option( 'launchpad_screen' ),
454                'site_intent'      => get_option( 'site_intent' ),
455                'admin_url'        => get_admin_url(),
456            ),
457        );
458
459        return $return_data;
460    }
461
462    /**
463     * Build the helpCenterData payload for the connected Help Center bundles.
464     *
465     * Exposed so frontend consumers can mount Help Center outside the
466     * admin-only enqueue path without re-implementing the payload
467     * field-for-field.
468     *
469     * Note: this is the payload for the *connected* bundles. The disconnected
470     * variants ('wp-admin-disconnected', 'gutenberg-disconnected') do not
471     * consume helpCenterData and are not valid input here.
472     *
473     * @param string $variant   Bundle variant driving the default sectionName.
474     *                          One of 'wp-admin', 'logged-out', 'customizer',
475     *                          'gutenberg'.
476     * @param array  $overrides Shallow-merged onto the result via array_replace
477     *                          (e.g. array( 'sectionName' => 'landpack' )).
478     *                          Replacing a sub-array (e.g. 'currentUser')
479     *                          replaces it whole â€” no deep merge.
480     * @return array            JSON-ready associative array.
481     */
482    public function get_help_center_data( string $variant = 'wp-admin', array $overrides = array() ): array {
483        $user_id            = get_current_user_id();
484        $user_data          = get_userdata( $user_id );
485        $username           = $user_data ? $user_data->user_login : null;
486        $user_email         = $user_data ? $user_data->user_email : null;
487        $display_name       = $user_data ? $user_data->display_name : null;
488        $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;
489        $is_commerce_garden = defined( 'IS_COMMERCE_GARDEN' );
490
491        if ( $this->is_forum_site ) {
492            $section_name = 'wp.com/forums';
493        } elseif ( $this->is_support_site ) {
494            $section_name = 'wp.com/support';
495        } else {
496            $section_name = $variant;
497        }
498
499        $data = array(
500            'isProxied'        => boolval( self::is_proxied() ),
501            'isSU'             => defined( 'WPCOM_SUPPORT_SESSION' ) && WPCOM_SUPPORT_SESSION,
502            'isSSP'            => isset( $_COOKIE['ssp'] ),
503            'sectionName'      => $section_name,
504            'isCommerceGarden' => $is_commerce_garden,
505            'currentUser'      => array(
506                'ID'           => $user_id,
507                'username'     => $username,
508                'display_name' => $display_name,
509                'avatar_URL'   => $avatar_url,
510                'email'        => $user_email,
511                'is_a11n'      => function_exists( '\is_automattician' ) && \is_automattician( $user_id ),
512            ),
513            'site'             => $this->get_current_site(),
514            'locale'           => self::determine_iso_639_locale(),
515        );
516
517        if ( null !== $this->new_interactions_bot_slug ) {
518            $data['newInteractionsBotSlug'] = $this->new_interactions_bot_slug;
519        }
520
521        if ( null !== $this->new_logged_out_interactions_bot_slug ) {
522            $data['newLoggedOutInteractionsBotSlug'] = $this->new_logged_out_interactions_bot_slug;
523        }
524
525        return array_replace( $data, $overrides );
526    }
527
528    /**
529     * Register the Help Center endpoints.
530     */
531    public function register_rest_api() {
532        require_once __DIR__ . '/class-wp-rest-help-center-authenticate.php';
533        $controller = new WP_REST_Help_Center_Authenticate( $this->wpcom_request_client );
534        $controller->register_rest_route();
535
536        require_once __DIR__ . '/class-wp-rest-help-center-sibyl.php';
537        $controller = new WP_REST_Help_Center_Sibyl( $this->wpcom_request_client );
538        $controller->register_rest_route();
539
540        require_once __DIR__ . '/class-wp-rest-help-center-support-status.php';
541        $controller = new WP_REST_Help_Center_Support_Status( $this->wpcom_request_client );
542        $controller->register_rest_route();
543
544        require_once __DIR__ . '/class-wp-rest-help-center-search.php';
545        $controller = new WP_REST_Help_Center_Search( $this->wpcom_request_client );
546        $controller->register_rest_route();
547
548        require_once __DIR__ . '/class-wp-rest-help-center-jetpack-search-ai.php';
549        $controller = new WP_REST_Help_Center_Jetpack_Search_AI( $this->wpcom_request_client );
550        $controller->register_rest_route();
551
552        require_once __DIR__ . '/class-wp-rest-help-center-jetpack-connection-health.php';
553        $controller = new WP_REST_Help_Center_Jetpack_Connection_Health( $this->wpcom_request_client );
554        $controller->register_rest_route();
555
556        require_once __DIR__ . '/class-wp-rest-help-center-fetch-post.php';
557        $controller = new WP_REST_Help_Center_Fetch_Post( $this->wpcom_request_client );
558        $controller->register_rest_route();
559
560        require_once __DIR__ . '/class-wp-rest-help-center-ticket.php';
561        $controller = new WP_REST_Help_Center_Ticket( $this->wpcom_request_client );
562        $controller->register_rest_route();
563
564        require_once __DIR__ . '/class-wp-rest-help-center-forum.php';
565        $controller = new WP_REST_Help_Center_Forum( $this->wpcom_request_client );
566        $controller->register_rest_route();
567
568        require_once __DIR__ . '/class-wp-rest-help-center-support-activity.php';
569        $controller = new WP_REST_Help_Center_Support_Activity( $this->wpcom_request_client );
570        $controller->register_rest_route();
571
572        require_once __DIR__ . '/class-wp-rest-help-center-support-interactions.php';
573        $controller = new WP_REST_Help_Center_Support_Interactions( $this->wpcom_request_client );
574        $controller->register_rest_route();
575
576        require_once __DIR__ . '/class-wp-rest-help-center-user-fields.php';
577        $controller = new WP_REST_Help_Center_User_Fields( $this->wpcom_request_client );
578        $controller->register_rest_route();
579
580        require_once __DIR__ . '/class-wp-rest-help-center-odie.php';
581        $controller = new WP_REST_Help_Center_Odie( $this->wpcom_request_client );
582        $controller->register_rest_route();
583
584        require_once __DIR__ . '/class-wp-rest-help-center-persisted-open-state.php';
585        $controller = new WP_REST_Help_Center_Persisted_Open_State( $this->wpcom_request_client );
586        $controller->register_rest_route();
587
588        require_once __DIR__ . '/class-wp-rest-help-center-email-support-enabled.php';
589        $controller = new WP_REST_Help_Center_Email_Support_Enabled( $this->wpcom_request_client );
590        $controller->register_rest_route();
591
592        require_once __DIR__ . '/class-wp-rest-help-center-ticket-csat.php';
593        $controller = new WP_REST_Help_Center_Ticket_CSAT( $this->wpcom_request_client );
594        $controller->register_rest_route();
595    }
596
597    /**
598     * Returns true if the admin bar is set.
599     */
600    public function is_admin_bar() {
601        global $wp_admin_bar;
602        return is_object( $wp_admin_bar );
603    }
604
605    /**
606     * Returns true if the current screen if the block editor.
607     */
608    public function is_block_editor() {
609        global $current_screen;
610
611        if ( ! $current_screen ) {
612            return false;
613        }
614
615        // widgets screen does have the block editor but also no Gutenberg top bar.
616        return $current_screen->is_block_editor() && $current_screen->id !== 'widgets';
617    }
618
619    /**
620     * Returns true if the current screen is the woo commerce admin home page.
621     */
622    private function is_wc_admin_home_page() {
623        global $current_screen;
624        return $current_screen && $current_screen->id === 'woocommerce_page_wc-admin';
625    }
626
627    /**
628     * Returns true if the current user is connected through Jetpack
629     */
630    public function is_jetpack_disconnected() {
631        $blog_id = get_current_blog_id();
632
633        if ( defined( 'IS_ATOMIC' ) && IS_ATOMIC ) {
634            return ! $this->wpcom_request_client->is_user_connected();
635        }
636
637        if ( true === apply_filters( 'is_jetpack_site', false, $blog_id ) ) {
638            return ! $this->wpcom_request_client->is_user_connected();
639        }
640
641        return false;
642    }
643
644    /**
645     * Returns true if...
646     * 1. The current user can edit posts.
647     * 2. The current user is a member of the blog.
648     * 3. The current request is not in the admin.
649     * 4. The current request is not in the block editor.
650     *
651     * @return bool True if the this is being loaded on the frontend.
652     */
653    public function is_loading_on_frontend() {
654        $can_edit_posts = current_user_can( 'edit_posts' ) && is_user_member_of_blog();
655
656        return ! is_admin() && ! $this->is_block_editor() && $can_edit_posts;
657    }
658
659    /**
660     * Returns the URL for the Help Center redirect.
661     * Used for the Help Center when disconnected.
662     */
663    public function get_help_center_url() {
664        $help_url = 'https://wordpress.com/help?help-center=home';
665
666        if ( $this->is_jetpack_disconnected() || ( $this->is_loading_on_frontend() && ! $this->is_support_site ) ) {
667            return $help_url;
668        }
669
670        return false;
671    }
672
673    /**
674     * Get the asset via file-system on wpcom and via network on Atomic sites.
675     *
676     * @param string $filepath The URL to download the asset file from.
677     */
678    private static function get_assets_json( $filepath ) {
679        $accessible_directly = file_exists( ABSPATH . '/' . $filepath );
680        if ( $accessible_directly ) {
681            return json_decode( file_get_contents( ABSPATH . '/' . $filepath ), true );
682        }
683        $request = wp_remote_get( 'https://' . $filepath );
684        if ( is_wp_error( $request ) ) {
685            return null;
686        }
687        return json_decode( wp_remote_retrieve_body( $request ), true );
688    }
689
690    /**
691     * Enqueue Help Center assets for the customizer.
692     */
693    public function enqueue_customizer_scripts() {
694        if ( $this->is_jetpack_disconnected() ) {
695            $variant = 'wp-admin-disconnected';
696        } else {
697            $variant = 'customizer';
698        }
699
700        $cache_key  = 'help-center-asset-' . $variant . '.asset.json';
701        $asset_file = get_transient( $cache_key );
702
703        if ( false === $asset_file ) {
704            $asset_file = self::get_assets_json( 'widgets.wp.com/help-center/help-center-' . $variant . '.asset.json' );
705            if ( null === $asset_file ) {
706                return;
707            }
708            set_transient( $cache_key, $asset_file, HOUR_IN_SECONDS );
709        }
710
711        // When the request is proxied, use a random cache buster as the version for easier debugging.
712        $version = self::is_proxied() ? wp_rand() : $asset_file['version'];
713
714        $this->enqueue_script( $variant, $asset_file['dependencies'], $version );
715    }
716
717    /**
718     * Add Help Center container div in customizer.
719     */
720    public function add_help_center_container() {
721        ?>
722        <div id="help-center-customizer"></div>
723        <?php
724    }
725
726    /**
727     * Add icon to WP-ADMIN admin bar.
728     */
729    public function enqueue_wp_admin_scripts() {
730        if ( $this->is_wc_admin_home_page() ) {
731            return;
732        }
733
734        require_once ABSPATH . 'wp-admin/includes/screen.php';
735
736        $can_edit_posts = current_user_can( 'edit_posts' ) && is_user_member_of_blog();
737        $is_p2          = str_contains( get_stylesheet(), 'pub/p2' ) || function_exists( '\WPForTeams\is_wpforteams_site' ) && is_wpforteams_site( get_current_blog_id() );
738
739        /**
740         * Filters whether to load the logged-out Help Center bundle on the current frontend request.
741         *
742         * Consumers can use this filter to opt public-facing surfaces into the
743         * Help Center without taking ownership of its asset-loading logic.
744         *
745         * @since 0.2.0
746         *
747         * @param bool $should_load Whether to load the logged-out Help Center bundle.
748         */
749        $should_load_logged_out = ! is_admin()
750            && (bool) apply_filters( 'jetpack_help_center_should_load_logged_out', false );
751
752        // We will show the help center icon in the admin bar when;
753        // 1. On wp-admin
754        // 2. On the front end of the site if the current user can edit posts
755        // 3. On the front end of the site and the theme is not P2
756        // 4. If it is the frontend we show the disconnected version of the help center.
757        if ( ! is_admin() && ( ! $can_edit_posts || $is_p2 ) && ! $this->is_support_site && ! $should_load_logged_out ) {
758            return;
759        }
760
761        // Do not load Help Center for logged-out users if we are not on support sites.
762        if ( ! is_user_logged_in() && ! $this->is_support_site && ! $should_load_logged_out ) {
763            return;
764        }
765
766        $suffix = $this->is_jetpack_disconnected() ? '-disconnected' : '';
767
768        if ( $should_load_logged_out ) {
769            $variant = 'logged-out';
770        } elseif ( $this->is_support_site ) {
771            if ( ! is_user_logged_in() ) {
772                $variant = 'logged-out';
773            } else {
774                $variant = ( $this->is_block_editor() ? 'gutenberg' : 'wp-admin' ) . $suffix;
775            }
776        } elseif ( $this->is_loading_on_frontend() ) {
777            $variant = 'wp-admin-disconnected';
778        } else {
779            $variant = ( $this->is_block_editor() ? 'gutenberg' : 'wp-admin' ) . $suffix;
780        }
781
782        $cache_key  = 'help-center-asset-' . $variant . '.asset.json';
783        $asset_file = get_transient( $cache_key );
784
785        if ( false === $asset_file ) {
786            $asset_file = self::get_assets_json( 'widgets.wp.com/help-center/help-center-' . $variant . '.asset.json' );
787            if ( null === $asset_file ) {
788                return;
789            }
790            set_transient( $cache_key, $asset_file, HOUR_IN_SECONDS );
791        }
792
793        // When the request is proxied, use a random cache buster as the version for easier debugging.
794        $version = self::is_proxied() ? wp_rand() : $asset_file['version'];
795
796        $this->enqueue_script( $variant, $asset_file['dependencies'], $version );
797    }
798}