Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
12.95% covered (danger)
12.95%
36 / 278
11.11% covered (danger)
11.11%
3 / 27
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Network
12.95% covered (danger)
12.95%
36 / 278
11.11% covered (danger)
11.11%
3 / 27
5079.87
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
72
 set_connection
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 do_automatically_add_new_site
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 body_class
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 init
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
3.33
 register_menubar
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 deactivate
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 add_to_menubar
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 get_url
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
8
 add_network_admin_menu
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 jetpack_sites_list
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
132
 set_multisite_disconnect_cap
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 show_jetpack_notice
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 do_subsitedisconnect
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 do_subsiteregister
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
56
 filter_register_user_token
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 filter_register_request_body
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
2
 admin_init_network_page
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 enqueue_network_admin_scripts
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
6
 wrap_network_admin_page
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 network_admin_page
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
12
 network_admin_page_header
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 save_network_settings_page
0.00% covered (danger)
0.00%
0 / 44
0.00% covered (danger)
0.00%
0 / 1
56
 wrap_render_network_admin_settings_page
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 render_network_admin_settings_page
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
12
 update_option
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 get_option
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
1<?php //phpcs:ignore WordPress.Files.FileName.InvalidClassFilename
2/**
3 * Jetpack Network Manager class file.
4 *
5 * @package automattic/jetpack
6 */
7
8use Automattic\Jetpack\Assets;
9use Automattic\Jetpack\Assets\Logo;
10use Automattic\Jetpack\Connection\Manager;
11use Automattic\Jetpack\Connection\Tokens;
12use Automattic\Jetpack\Status;
13use Automattic\Jetpack\Waf\Brute_Force_Protection\Brute_Force_Protection_Shared_Functions;
14
15/**
16 * Used to manage Jetpack installation on Multisite Network installs
17 *
18 * SINGLETON: To use call Jetpack_Network::init()
19 *
20 * DO NOT USE ANY STATIC METHODS IN THIS CLASS!!!!!!
21 *
22 * @since 2.9
23 */
24class Jetpack_Network {
25
26    /**
27     * Holds a static copy of Jetpack_Network for the singleton
28     *
29     * @since 2.9
30     * @var Jetpack_Network
31     */
32    private static $instance = null;
33
34    /**
35     * An instance of the connection manager object.
36     *
37     * @since 7.7
38     * @var Automattic\Jetpack\Connection\Manager
39     */
40    private $connection;
41
42    /**
43     * Name of the network wide settings
44     *
45     * @since 2.9
46     * @var string
47     */
48    private $settings_name = 'jetpack-network-settings';
49
50    /**
51     * Defaults for settings found on the Jetpack > Settings page
52     *
53     * @since 2.9
54     * @var array
55     */
56    private $setting_defaults = array(
57        'auto-connect'                 => 0,
58        'sub-site-connection-override' => 1,
59    );
60
61    /**
62     * Constructor
63     *
64     * @since 2.9
65     */
66    private function __construct() {
67        require_once ABSPATH . '/wp-admin/includes/plugin.php'; // For the is_plugin... check.
68
69        /**
70         * Sanity check to ensure the install is Multisite and we
71         * are in Network Admin
72         */
73        if ( is_multisite() && is_network_admin() ) {
74            add_action( 'network_admin_menu', array( $this, 'add_network_admin_menu' ) );
75            add_action( 'network_admin_edit_jetpack-network-settings', array( $this, 'save_network_settings_page' ), 10, 0 );
76            add_filter( 'admin_body_class', array( $this, 'body_class' ) );
77
78            if ( isset( $_GET['page'] ) && 'jetpack' === $_GET['page'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is view logic.
79                add_action( 'admin_init', array( $this, 'jetpack_sites_list' ) );
80            }
81        }
82
83        /*
84         * Things that should only run on multisite
85         */
86        if ( is_multisite() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
87            add_action( 'wp_before_admin_bar_render', array( $this, 'add_to_menubar' ) );
88            add_filter( 'jetpack_disconnect_cap', array( $this, 'set_multisite_disconnect_cap' ) );
89
90            /*
91             * If admin wants to automagically register new sites set the hook here
92             *
93             * This is a hacky way because xmlrpc is not available on wp_initialize_site
94             */
95            if ( 1 === $this->get_option( 'auto-connect' ) ) {
96                add_action( 'wp_initialize_site', array( $this, 'do_automatically_add_new_site' ) );
97            }
98        }
99    }
100
101    /**
102     * Sets a connection object.
103     *
104     * @param Automattic\Jetpack\Connection\Manager $connection the connection manager object.
105     */
106    public function set_connection( Manager $connection ) {
107        $this->connection = $connection;
108    }
109
110    /**
111     * Registers new sites upon creation
112     *
113     * @since 2.9
114     * @since 7.4.0 Uses a WP_Site object.
115     * @uses  wp_initialize_site
116     *
117     * @param WP_Site $site the WordPress site object.
118     **/
119    public function do_automatically_add_new_site( $site ) {
120        if ( is_a( $site, 'WP_Site' ) ) {
121            $this->do_subsiteregister( $site->id );
122        }
123    }
124
125    /**
126     * Adds .network-admin class to the body tag
127     * Helps distinguish network admin JP styles from regular site JP styles
128     *
129     * @since 2.9
130     *
131     * @param String $classes current assigned body classes.
132     * @return String amended class string.
133     */
134    public function body_class( $classes ) {
135        return trim( $classes ) . ' network-admin ';
136    }
137
138    /**
139     * Provides access to an instance of Jetpack_Network
140     *
141     * This is how the Jetpack_Network object should *always* be accessed
142     *
143     * @since 2.9
144     * @return Jetpack_Network
145     */
146    public static function init() {
147        if ( ! self::$instance || ! is_a( self::$instance, 'Jetpack_Network' ) ) {
148            self::$instance = new Jetpack_Network();
149        }
150
151        return self::$instance;
152    }
153
154    /**
155     * Registers the Multisite admin bar menu item shortcut.
156     * This shortcut helps users quickly and easily navigate to the Jetpack Network Admin
157     * menu from anywhere in their network.
158     *
159     * @since 2.9
160     */
161    public function register_menubar() {
162        add_action( 'wp_before_admin_bar_render', array( $this, 'add_to_menubar' ) );
163    }
164
165    /**
166     * Runs when Jetpack is deactivated from the network admin plugins menu.
167     * Each individual site will need to have Jetpack::disconnect called on it.
168     * Site that had Jetpack individually enabled will not be disconnected as
169     * on Multisite individually activated plugins are still activated when
170     * a plugin is deactivated network wide.
171     *
172     * @since 2.9
173     **/
174    public function deactivate() {
175        // Only fire if in network admin.
176        if ( ! is_network_admin() ) {
177            return;
178        }
179
180        $sites = get_sites();
181
182        foreach ( $sites as $s ) {
183            switch_to_blog( (int) $s->blog_id );
184            $active_plugins = get_option( 'active_plugins' );
185
186            /*
187             * If this plugin was activated in the subsite individually
188             * we do not want to call disconnect. Plugins activated
189             * individually (before network activation) stay activated
190             * when the network deactivation occurs
191             */
192            if ( ! in_array( 'jetpack/jetpack.php', $active_plugins, true ) ) {
193                Jetpack::disconnect();
194                Jetpack_Options::delete_option( 'version' );
195            }
196            restore_current_blog();
197        }
198    }
199
200    /**
201     * Adds a link to the Jetpack Network Admin page in the network admin menu bar.
202     *
203     * @since 2.9
204     **/
205    public function add_to_menubar() {
206        global $wp_admin_bar;
207        // Don't show for logged out users or single site mode.
208        if ( ! is_user_logged_in() || ! is_multisite() ) {
209            return;
210        }
211
212        $wp_admin_bar->add_node(
213            array(
214                'parent' => 'network-admin',
215                'id'     => 'network-admin-jetpack',
216                'title'  => 'Jetpack',
217                'href'   => $this->get_url( 'network_admin_page' ),
218            )
219        );
220    }
221
222    /**
223     * Returns various URL strings. Factory like
224     *
225     * $args can be a string or an array.
226     * If $args is an array there must be an element called name for the switch statement
227     *
228     * Currently supports:
229     * - subsiteregister: Pass array( 'name' => 'subsiteregister', 'site_id' => SITE_ID )
230     * - network_admin_page: Provides link to /wp-admin/network/JETPACK
231     * - subsitedisconnect: Pass array( 'name' => 'subsitedisconnect', 'site_id' => SITE_ID )
232     *
233     * @since 2.9
234     *
235     * @param Mixed $args URL parameters.
236     *
237     * @return String
238     **/
239    public function get_url( $args ) {
240        $url = null; // Default url value.
241
242        if ( is_string( $args ) ) {
243            $name = $args;
244        } elseif ( is_array( $args ) ) {
245            $name = $args['name'];
246        } else {
247            return $url;
248        }
249
250        switch ( $name ) {
251            case 'subsiteregister':
252                if ( ! isset( $args['site_id'] ) ) {
253                    break; // If there is not a site id present we cannot go further.
254                }
255                $url = network_admin_url(
256                    'admin.php?page=jetpack&action=subsiteregister&site_id='
257                    . $args['site_id']
258                );
259                break;
260
261            case 'network_admin_page':
262                $url = network_admin_url( 'admin.php?page=jetpack' );
263                break;
264
265            case 'subsitedisconnect':
266                if ( ! isset( $args['site_id'] ) ) {
267                    break; // If there is not a site id present we cannot go further.
268                }
269                $url = network_admin_url(
270                    'admin.php?page=jetpack&action=subsitedisconnect&site_id='
271                    . $args['site_id']
272                );
273                break;
274        }
275
276        return $url;
277    }
278
279    /**
280     * Adds the Jetpack  menu item to the Network Admin area
281     *
282     * @since 2.9
283     */
284    public function add_network_admin_menu() {
285        $logo = new Logo();
286        // Another plugin may load an older Logo class before all Jetpack autoloaders register.
287        if ( method_exists( $logo, 'get_base64_admin_menu_logo' ) ) {
288            $icon = $logo->get_base64_admin_menu_logo();
289        } else {
290            $icon = $logo->get_base64_logo();
291        }
292        add_menu_page( 'Jetpack', 'Jetpack', 'jetpack_network_admin_page', 'jetpack', array( $this, 'wrap_network_admin_page' ), $icon, 3 );
293        $jetpack_sites_page_hook    = add_submenu_page( 'jetpack', __( 'Jetpack Sites', 'jetpack' ), __( 'Sites', 'jetpack' ), 'jetpack_network_sites_page', 'jetpack', array( $this, 'wrap_network_admin_page' ) );
294        $jetpack_settings_page_hook = add_submenu_page( 'jetpack', __( 'Settings', 'jetpack' ), __( 'Settings', 'jetpack' ), 'jetpack_network_settings_page', 'jetpack-settings', array( $this, 'wrap_render_network_admin_settings_page' ) );
295        add_action( "load-$jetpack_sites_page_hook", array( $this, 'admin_init_network_page' ) );
296        add_action( "load-$jetpack_settings_page_hook", array( $this, 'admin_init_network_page' ) );
297    }
298
299    /**
300     * Provides functionality for the Jetpack > Sites page.
301     * Does not do the display!
302     *
303     * @since 2.9
304     */
305    public function jetpack_sites_list() {
306        Jetpack::init();
307
308        if ( isset( $_GET['action'] ) ) {
309            switch ( $_GET['action'] ) {
310                case 'subsiteregister':
311                    check_admin_referer( 'jetpack-subsite-register' );
312                    Jetpack::log( 'subsiteregister' );
313
314                    // If no site_id, stop registration and error.
315                    if ( ! isset( $_GET['site_id'] ) || empty( $_GET['site_id'] ) ) {
316                        /**
317                         * Log error to state cookie for display later.
318                         *
319                         * @todo Make state messages show on Jetpack NA pages
320                         */
321                        Jetpack::state( 'missing_site_id', esc_html__( 'Site ID must be provided to register a sub-site.', 'jetpack' ) );
322                        break;
323                    }
324
325                    // Send data to register endpoint and retrieve shadow blog details.
326                    $result = $this->do_subsiteregister();
327                    $url    = $this->get_url( 'network_admin_page' );
328
329                    if ( is_wp_error( $result ) ) {
330                        $url = add_query_arg( 'action', 'connection_failed', $url );
331                    } else {
332                        $url = add_query_arg( 'action', 'connected', $url );
333                    }
334
335                    wp_safe_redirect( $url );
336                    exit( 0 );
337
338                case 'subsitedisconnect':
339                    check_admin_referer( 'jetpack-subsite-disconnect' );
340                    Jetpack::log( 'subsitedisconnect' );
341
342                    if ( ! isset( $_GET['site_id'] ) || empty( $_GET['site_id'] ) ) {
343                        Jetpack::state( 'missing_site_id', esc_html__( 'Site ID must be provided to disconnect a sub-site.', 'jetpack' ) );
344                        break;
345                    }
346
347                    $this->do_subsitedisconnect();
348                    break;
349
350                case 'connected':
351                case 'connection_failed':
352                    add_action( 'jetpack_notices', array( $this, 'show_jetpack_notice' ) );
353                    break;
354            }
355        }
356    }
357
358    /**
359     * Set the disconnect capability for multisite.
360     *
361     * @param array $caps The capabilities array.
362     */
363    public function set_multisite_disconnect_cap( $caps ) {
364        // Can individual site admins manage their own connection?
365        if ( ! is_super_admin() && ! $this->get_option( 'sub-site-connection-override' ) ) {
366            /*
367             * We need to update the option name -- it's terribly unclear which
368             * direction the override goes.
369             *
370             * @todo: Update the option name to `sub-sites-can-manage-own-connections`
371             */
372            return array( 'do_not_allow' );
373        }
374
375        return $caps;
376    }
377
378    /**
379     * Shows the Jetpack plugin notices.
380     */
381    public function show_jetpack_notice() {
382        if ( isset( $_GET['action'] ) && 'connected' === $_GET['action'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is view logic.
383            $notice    = __( 'Site successfully connected.', 'jetpack' );
384            $classname = 'updated';
385        } elseif ( isset( $_GET['action'] ) && 'connection_failed' === $_GET['action'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is view logic.
386            $notice    = __( 'Site connection failed!', 'jetpack' );
387            $classname = 'error';
388        }
389        ?>
390        <div id="message" class="<?php echo esc_attr( $classname ?? '' ); ?> jetpack-message jp-connect" style="display:block !important;">
391            <p><?php echo esc_html( $notice ?? '' ); ?></p>
392        </div>
393        <?php
394    }
395
396    /**
397     * Disconnect functionality for an individual site
398     *
399     * @since 2.9
400     * @see   Jetpack_Network::jetpack_sites_list()
401     *
402     * @param int $site_id the site identifier.
403     */
404    public function do_subsitedisconnect( $site_id = null ) {
405        if ( ! current_user_can( 'jetpack_disconnect' ) ) {
406            return;
407        }
408        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Caller (i.e. `$this->jetpack_sites_list()`) should check.
409        $site_id = ( $site_id === null ) ? ( isset( $_GET['site_id'] ) ? (int) $_GET['site_id'] : null ) : $site_id;
410        switch_to_blog( $site_id );
411        Jetpack::disconnect();
412        restore_current_blog();
413    }
414
415    /**
416     * Registers a subsite with the Jetpack servers
417     *
418     * @since 2.9
419     * @todo  Break apart into easier to manage chunks that can be unit tested
420     * @see   Jetpack_Network::jetpack_sites_list();
421     *
422     * @param int $site_id the site identifier.
423     */
424    public function do_subsiteregister( $site_id = null ) {
425        if ( ! current_user_can( 'jetpack_disconnect' ) ) {
426            return;
427        }
428
429        if ( ( new Status() )->is_offline_mode() ) {
430            return;
431        }
432
433        // Figure out what site we are working on.
434        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Caller (i.e. `$this->jetpack_sites_list()`) should check.
435        $site_id = ( $site_id === null ) ? ( isset( $_GET['site_id'] ) ? (int) $_GET['site_id'] : null ) : $site_id;
436
437        /*
438         * Here we need to switch to the subsite
439         * For the registration process we really only hijack how it
440         * works for an individual site and pass in some extra data here
441         */
442        switch_to_blog( $site_id );
443
444        add_filter( 'jetpack_register_request_body', array( $this, 'filter_register_request_body' ) );
445        add_action( 'jetpack_site_registered_user_token', array( $this, 'filter_register_user_token' ) );
446
447        // Save the secrets in the subsite so when the wpcom server does a pingback it
448        // will be able to validate the connection.
449        $result = $this->connection->register( 'subsiteregister' );
450
451        if ( is_wp_error( $result ) || ! $result ) {
452            restore_current_blog();
453            return $result;
454        }
455
456        Jetpack::activate_default_modules( false, false, array(), false );
457
458        restore_current_blog();
459    }
460
461    /**
462     * Receives the registration response token.
463     *
464     * @param Object $token the received token.
465     */
466    public function filter_register_user_token( $token ) {
467        $is_connection_owner = ! $this->connection->has_connected_owner();
468        ( new Tokens() )->update_user_token(
469            get_current_user_id(),
470            sprintf( '%s.%d', $token->secret, get_current_user_id() ),
471            $is_connection_owner
472        );
473    }
474
475    /**
476     * Filters the registration request body to include additional properties.
477     *
478     * @param array $properties standard register request body properties.
479     * @return array amended properties.
480     */
481    public function filter_register_request_body( $properties ) {
482        $blog_details = get_blog_details();
483
484        $network = get_network();
485
486        switch_to_blog( (int) $network->blog_id );
487        // The blog id on WordPress.com of the primary network site.
488        $network_wpcom_blog_id = Jetpack_Options::get_option( 'id' );
489        restore_current_blog();
490
491        /**
492         * Both `state` and `user_id` need to be sent in the request, even though they are the same value.
493         * Connecting via the network admin combines `register()` and `authorize()` methods into one step,
494         * because we assume the main site is already authorized. `state` is used to verify the `register()`
495         * request, while `user_id()` is used to create the token in the `authorize()` request.
496         */
497        return array_merge(
498            $properties,
499            array(
500                'network_url'           => $this->get_url( 'network_admin_page' ),
501                'network_wpcom_blog_id' => $network_wpcom_blog_id,
502                'user_id'               => get_current_user_id(),
503
504                /*
505                 * Use the subsite's registration date as the site creation date.
506                 *
507                 * This is in contrast to regular standalone sites, where we use the helper
508                 * `Jetpack::get_assumed_site_creation_date()` to assume the site's creation date.
509                 */
510                'site_created'          => $blog_details->registered,
511            )
512        );
513    }
514
515    /**
516     * Initializes assets for network admin pages.
517     *
518     * @since 15.7
519     */
520    public function admin_init_network_page() {
521        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_network_admin_scripts' ) );
522
523        // Match the modernized single-site dashboards (e.g. Jetpack Forms): the
524        // network Sites/Settings pages render as full-viewport AdminPage shells,
525        // so strip core admin notices that would otherwise break the pinned
526        // layout. Network Admin fires `network_admin_notices`/`all_admin_notices`
527        // (not `admin_notices`). Jetpack's own notices use the `jetpack_notices`
528        // hook and are unaffected.
529        remove_all_actions( 'network_admin_notices' );
530        remove_all_actions( 'all_admin_notices' );
531    }
532
533    /**
534     * Enqueues the JS and CSS for the unified network admin header.
535     *
536     * @since 15.7
537     */
538    public function enqueue_network_admin_scripts() {
539        $build_dir         = JETPACK__PLUGIN_DIR . '_inc/build/';
540        $script_asset_path = $build_dir . 'network-admin.asset.php';
541
542        if ( ! file_exists( $script_asset_path ) ) {
543            return;
544        }
545
546        Assets::register_script(
547            'jetpack-network-admin',
548            '_inc/build/network-admin.js',
549            JETPACK__PLUGIN_FILE,
550            array(
551                'in_footer'  => true,
552                'textdomain' => 'jetpack',
553                'enqueue'    => true,
554            )
555        );
556
557        wp_localize_script(
558            'jetpack-network-admin',
559            'JetpackNetworkAdminData',
560            array(
561                'sitesUrl'    => network_admin_url( 'admin.php?page=jetpack' ),
562                'settingsUrl' => network_admin_url( 'admin.php?page=jetpack-settings' ),
563            )
564        );
565    }
566
567    /**
568     * Renders the Network Sites page with the unified admin header.
569     */
570    public function wrap_network_admin_page() {
571        echo '<div id="jp-network-admin-root" data-page="sites"></div>';
572        echo '<div id="jp-network-admin-content" style="display:none">';
573        $this->network_admin_page();
574        echo '</div>';
575    }
576
577    /**
578     * Handles the displaying of all sites on the network that are
579     * dis/connected to Jetpack
580     *
581     * @since 2.9
582     * @see   Jetpack_Network::jetpack_sites_list()
583     */
584    public function network_admin_page() {
585        global $current_site;
586
587        $jp = Jetpack::init();
588
589        // We should be, but ensure we are on the main blog.
590        switch_to_blog( $current_site->blog_id );
591        $main_active = $jp->is_connection_ready();
592        restore_current_blog();
593
594        // If we are in dev mode, just show the notice and bail.
595        if ( ( new Status() )->is_offline_mode() ) {
596            Jetpack::show_development_mode_notice();
597            return;
598        }
599
600        /*
601         * Ensure the main blog is connected as all other subsite blog
602         * connections will feed off this one
603         */
604        if ( ! $main_active ) {
605            $data = array( 'url' => $jp->build_connect_url() );
606            Jetpack::init()->load_view( 'admin/must-connect-main-blog.php', $data );
607
608            return;
609        }
610
611        require_once __DIR__ . '/class.jetpack-network-sites-list-table.php';
612
613        $network_sites_table = new Jetpack_Network_Sites_List_Table();
614        echo '<div class="wrap"><h2>' . esc_html__( 'Sites', 'jetpack' ) . '</h2>';
615        echo '<form method="post">';
616        $network_sites_table->prepare_items();
617        $network_sites_table->display();
618        echo '</form></div>';
619    }
620
621    /**
622     * Stylized JP header formatting
623     *
624     * @since 2.9
625     */
626    public function network_admin_page_header() {
627        $is_connected = Jetpack::is_connection_ready();
628
629        $data = array(
630            'is_connected' => $is_connected,
631        );
632        Jetpack::init()->load_view( 'admin/network-admin-header.php', $data );
633    }
634
635    /**
636     * Fires when the Jetpack > Settings page is saved.
637     *
638     * @since 2.9
639     * @return never
640     */
641    public function save_network_settings_page() {
642
643        if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'jetpack-network-settings' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
644            // No nonce, push back to settings page.
645            wp_safe_redirect(
646                add_query_arg(
647                    array( 'page' => 'jetpack-settings' ),
648                    network_admin_url( 'admin.php' )
649                )
650            );
651            exit( 0 );
652        }
653
654        // Try to save the Protect allow list before anything else, since that action can result in errors.
655        $allow_list = isset( $_POST['global-allow-list'] ) ? filter_var( wp_unslash( $_POST['global-allow-list'] ) ) : '';
656        $allow_list = str_replace( ' ', '', $allow_list );
657        $allow_list = explode( PHP_EOL, $allow_list );
658        $result     = Brute_Force_Protection_Shared_Functions::save_allow_list( $allow_list, true );
659        if ( is_wp_error( $result ) ) {
660            wp_safe_redirect(
661                add_query_arg(
662                    array(
663                        'page'  => 'jetpack-settings',
664                        'error' => 'jetpack_protect_whitelist',
665                    ),
666                    network_admin_url( 'admin.php' )
667                )
668            );
669            exit( 0 );
670        }
671
672        /*
673         * Fields
674         *
675         * auto-connect - Checkbox for global Jetpack connection
676         * sub-site-connection-override - Allow sub-site admins to (dis)reconnect with their own Jetpack account
677         */
678        $auto_connect = 0;
679        if ( isset( $_POST['auto-connect'] ) ) {
680            $auto_connect = 1;
681        }
682
683        $sub_site_connection_override = 0;
684        if ( isset( $_POST['sub-site-connection-override'] ) ) {
685            $sub_site_connection_override = 1;
686        }
687
688        $data = array(
689            'auto-connect'                 => $auto_connect,
690            'sub-site-connection-override' => $sub_site_connection_override,
691        );
692
693        update_site_option( $this->settings_name, $data );
694        wp_safe_redirect(
695            add_query_arg(
696                array(
697                    'page'    => 'jetpack-settings',
698                    'updated' => 'true',
699                ),
700                network_admin_url( 'admin.php' )
701            )
702        );
703        exit( 0 );
704    }
705
706    /**
707     * Renders the Network Settings page with the unified admin header.
708     */
709    public function wrap_render_network_admin_settings_page() {
710        echo '<div id="jp-network-admin-root" data-page="settings"></div>';
711        echo '<div id="jp-network-admin-content" style="display:none">';
712        $this->render_network_admin_settings_page();
713        echo '</div>';
714    }
715
716    /**
717     * A hook rendering the admin settings page.
718     */
719    public function render_network_admin_settings_page() {
720        $options = wp_parse_args( get_site_option( $this->settings_name ), $this->setting_defaults );
721
722        $modules      = array();
723        $module_slugs = Jetpack::get_available_modules();
724        foreach ( $module_slugs as $slug ) {
725            $module           = Jetpack::get_module( $slug );
726            $module['module'] = $slug;
727            $modules[]        = $module;
728        }
729
730        usort( $modules, array( 'Jetpack', 'sort_modules' ) );
731
732        if ( ! isset( $options['modules'] ) ) {
733            $options['modules'] = $modules;
734        }
735
736        $data = array(
737            'modules'                   => $modules,
738            'options'                   => $options,
739            'jetpack_protect_whitelist' => Brute_Force_Protection_Shared_Functions::format_allow_list(),
740        );
741
742        Jetpack::init()->load_view( 'admin/network-settings.php', $data );
743    }
744
745    /**
746     * Updates a site wide option
747     *
748     * @since 2.9
749     *
750     * @param string $key option name.
751     * @param mixed  $value option value.
752     *
753     * @return boolean
754     **/
755    public function update_option( $key, $value ) {
756        $options         = get_site_option( $this->settings_name, $this->setting_defaults );
757        $options[ $key ] = $value;
758
759        return update_site_option( $this->settings_name, $options );
760    }
761
762    /**
763     * Retrieves a site wide option
764     *
765     * @since 2.9
766     *
767     * @param string $name - Name of the option in the database.
768     **/
769    public function get_option( $name ) {
770        $options = get_site_option( $this->settings_name, $this->setting_defaults );
771        $options = wp_parse_args( $options, $this->setting_defaults );
772
773        if ( ! isset( $options[ $name ] ) ) {
774            $options[ $name ] = null;
775        }
776
777        return $options[ $name ];
778    }
779}