Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.77% covered (success)
90.77%
59 / 65
80.00% covered (warning)
80.00%
8 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_Scan
96.72% covered (success)
96.72%
59 / 61
80.00% covered (warning)
80.00%
8 / 10
43
0.00% covered (danger)
0.00%
0 / 1
 should_register
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
 is_dashboard_module_off
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_state
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
5
 is_awaiting_connection
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 get_initial_state
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
6
 register_page
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 remove_menu_entry
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 handle_enable
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
7.03
 filter_available_modules
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 maybe_activate_protect_dashboard_module
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
9.03
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- Feature entry file, named after the feature, also holds the WPCOM_Scan bootstrap class.
2/**
3 * An in-wp-admin Protect page for WordPress.com Simple and WoA sites.
4 * Prompts for a plan upgrade or activation of Scan.
5 *
6 * @package automattic/jetpack-mu-wpcom
7 */
8
9namespace Automattic\Jetpack\Jetpack_Mu_Wpcom;
10
11use Automattic\Jetpack\Connection\Manager as Connection_Manager;
12use Automattic\Jetpack\Modules;
13
14require_once __DIR__ . '/../wpcom-hosting-feature-page/class-wpcom-hosting-feature-page.php';
15
16/**
17 * Registers the Protect admin page and its wp-build assets.
18 */
19class WPCOM_Scan extends WPCOM_Hosting_Feature_Page {
20
21    /**
22     * The slug the Jetpack plugin is expected to serve Protect from on WoA once Scan is live.
23     */
24    const MENU_SLUG = 'jetpack-protect';
25
26    /**
27     * The Jetpack plugin module that serves MENU_SLUG with the Protect package's dashboard.
28     */
29    const DASHBOARD_MODULE = 'protect-dashboard';
30
31    /**
32     * Set once the Protect dashboard has been on, so a site that turns it off later keeps it off.
33     */
34    const DASHBOARD_MODULE_ACTIVATED_OPTION = 'wpcom_protect_dashboard_activated';
35
36    /**
37     * As declared in routes/wpcom-scan/package.json.
38     */
39    const WP_BUILD_PAGE = 'wpcom-scan';
40
41    /**
42     * Its own global, as the admin shell can hold Backup and Protect in one document.
43     */
44    const INITIAL_STATE_VAR = 'wpcomScanInitialState';
45
46    /**
47     * Product name, do not translate.
48     */
49    const PAGE_TITLE = 'Jetpack Protect';
50
51    /**
52     * Product name, do not translate.
53     */
54    const MENU_TITLE = 'Protect';
55
56    /**
57     * SCAN_SELF_SERVE, not SCAN: SCAN also covers Personal and Premium plans, which run scans
58     * without exposing Scan's UI. It is also what the dashboard's Scan page gates on.
59     */
60    const FEATURE = 'SCAN_SELF_SERVE';
61
62    /**
63     * The admin-post action, and nonce action, that turns the Protect dashboard back on.
64     */
65    const ENABLE_ACTION = 'wpcom_enable_protect_dashboard';
66
67    /**
68     * The `enable_failed` reason when the site is not connected to WordPress.com, which the module requires.
69     */
70    const ENABLE_ERROR_CONNECTION = 'connection';
71
72    /**
73     * The `enable_failed` reason for any other refusal.
74     */
75    const ENABLE_ERROR_UNKNOWN = 'unknown';
76
77    /**
78     * Also claim the slug on a WoA site whose plan includes Scan but whose Protect dashboard is off,
79     * so a link into it gets a way to turn it back on rather than core's access error.
80     *
81     * @return bool
82     */
83    public static function should_register() {
84        if ( ! self::is_atomic() || ! self::has_feature() ) {
85            return parent::should_register();
86        }
87
88        return is_admin() && self::is_dashboard_module_off();
89    }
90
91    /**
92     * Whether the Jetpack plugin offers the Protect dashboard here, but it is turned off.
93     *
94     * @return bool
95     */
96    public static function is_dashboard_module_off() {
97        $modules = new Modules();
98
99        // Unavailable beside the standalone Protect plugin, which serves the slug itself.
100        return ! $modules->is_active( self::DASHBOARD_MODULE )
101            && in_array( self::DASHBOARD_MODULE, $modules->get_available(), true );
102    }
103
104    /**
105     * Offer to turn the Protect dashboard on wherever should_register() kept the page for that.
106     *
107     * @param int $blog_id Blog ID.
108     * @return string One of the STATE_* constants.
109     */
110    public static function get_state( $blog_id ) {
111        if ( self::is_atomic() && self::has_feature() && self::is_dashboard_module_off() ) {
112            return self::is_awaiting_connection() ? self::STATE_IN_PROGRESS : self::STATE_ENABLE;
113        }
114
115        return parent::get_state( $blog_id );
116    }
117
118    /**
119     * Whether a dashboard that has never been on is waiting for the connection, as just after a transfer.
120     *
121     * Nobody turned it off: maybe_activate_protect_dashboard_module() turns it on once the connection is ready.
122     *
123     * @return bool
124     */
125    public static function is_awaiting_connection() {
126        return ! get_option( self::DASHBOARD_MODULE_ACTIVATED_OPTION ) && ! ( new Connection_Manager() )->is_connected();
127    }
128
129    /**
130     * The resolved prompt, plus the link that turns the Protect dashboard on.
131     *
132     * @return array
133     */
134    public static function get_initial_state() {
135        $state = parent::get_initial_state();
136
137        if ( self::STATE_IN_PROGRESS === $state['state'] && self::is_atomic() ) {
138            $state['awaitingConnection'] = true;
139        }
140
141        if ( self::STATE_ENABLE === $state['state'] ) {
142            $state['enableUrl'] = add_query_arg(
143                array(
144                    'action'   => self::ENABLE_ACTION,
145                    '_wpnonce' => wp_create_nonce( self::ENABLE_ACTION ),
146                ),
147                admin_url( 'admin-post.php' )
148            );
149            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only flag set by handle_enable()'s redirect.
150            $error                = isset( $_GET['enable_failed'] ) ? sanitize_key( wp_unslash( $_GET['enable_failed'] ) ) : '';
151            $state['enableError'] = in_array( $error, array( self::ENABLE_ERROR_CONNECTION, self::ENABLE_ERROR_UNKNOWN ), true ) ? $error : null;
152        }
153
154        return $state;
155    }
156
157    /**
158     * Register the page, keeping its entry out of the sidebar while it only offers to turn the dashboard back on.
159     *
160     * Turning the module off hides the dashboard on purpose, so the entry goes as on self-hosted while links still land.
161     *
162     * @return void
163     */
164    public static function register_page() {
165        global $submenu;
166
167        parent::register_page();
168
169        if ( ! self::owns_page() || self::STATE_ENABLE !== self::get_state( get_current_blog_id() ) ) {
170            return;
171        }
172
173        // For Calypso's sidebar, whose REST request never reaches admin_head.
174        foreach ( $submenu[ self::PARENT_SLUG ] ?? array() as $i => $item ) {
175            if ( self::MENU_SLUG === ( $item[2] ?? null ) ) {
176                // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
177                $submenu[ self::PARENT_SLUG ][ $i ][4] = trim( ( $item[4] ?? '' ) . ' hide-if-js' );
178            }
179        }
180
181        add_action( 'admin_head', array( self::class, 'remove_menu_entry' ) );
182    }
183
184    /**
185     * Take the entry out of wp-admin's sidebar, after core's access check and page title have read it.
186     *
187     * Removed rather than left hidden: My Jetpack refreshes the sidebar by link, so a hidden entry sharing the
188     * dashboard's link would keep whichever state was on screen when the module is switched.
189     *
190     * @return void
191     */
192    public static function remove_menu_entry() {
193        remove_submenu_page( self::PARENT_SLUG, self::MENU_SLUG );
194    }
195
196    /**
197     * Turn the Protect dashboard on, then return to its page, which it now serves.
198     *
199     * @return never
200     */
201    public static function handle_enable() {
202        check_admin_referer( self::ENABLE_ACTION );
203
204        if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
205            wp_die( esc_html__( 'Sorry, you are not allowed to turn on Protect.', 'jetpack-mu-wpcom' ), '', 403 );
206        }
207
208        $url = self::get_page_url();
209
210        if ( self::is_atomic() && self::has_feature() && self::is_dashboard_module_off() ) {
211            $modules = new Modules();
212            $modules->activate( self::DASHBOARD_MODULE, false, false );
213
214            // Read back: activate() returns true even when its write to the saved list is filtered away.
215            if ( ! $modules->is_active( self::DASHBOARD_MODULE ) ) {
216                $error = ( new Connection_Manager() )->is_connected() ? self::ENABLE_ERROR_UNKNOWN : self::ENABLE_ERROR_CONNECTION;
217                $url   = add_query_arg( 'enable_failed', $error, $url );
218            }
219        }
220
221        wp_safe_redirect( $url );
222        exit( 0 );
223    }
224
225    /**
226     * Keep the Jetpack plugin's Protect dashboard off a WoA site whose plan lacks Scan, so this page's upgrade prompt keeps the slug.
227     *
228     * @param array $modules Available modules, keyed by slug.
229     * @return array
230     */
231    public static function filter_available_modules( $modules ) {
232        if ( ! self::has_feature() ) {
233            unset( $modules[ self::DASHBOARD_MODULE ] );
234        }
235
236        return $modules;
237    }
238
239    /**
240     * Turn the Protect dashboard on once for a WoA site that can have it.
241     *
242     * WoA sites passed the module's First Introduced version while it was unavailable there, so Jetpack's upgrade never turned it on.
243     *
244     * @return void
245     */
246    public static function maybe_activate_protect_dashboard_module() {
247        if ( ! self::is_atomic() || ! is_admin() || get_option( self::DASHBOARD_MODULE_ACTIVATED_OPTION ) ) {
248            return;
249        }
250
251        $modules = new Modules();
252        // Unavailable without the Jetpack plugin, without self-serve Scan, or beside the standalone Protect plugin, so it is retried once offered.
253        if ( ! in_array( self::DASHBOARD_MODULE, $modules->get_available(), true ) ) {
254            return;
255        }
256
257        $was_active = $modules->is_active( self::DASHBOARD_MODULE );
258        if ( ! $was_active ) {
259            $modules->activate( self::DASHBOARD_MODULE, false, false );
260        }
261
262        // Checked again rather than trusting activate(), which also refuses while the connection is not ready.
263        if ( ! $modules->is_active( self::DASHBOARD_MODULE ) ) {
264            return;
265        }
266
267        update_option( self::DASHBOARD_MODULE_ACTIVATED_OPTION, true, false );
268
269        // This page already claimed the slug at init 10, but the dashboard only loads on the next request.
270        if ( ! $was_active && self::is_page_request() ) {
271            wp_safe_redirect( self::get_page_url() );
272            exit( 0 );
273        }
274    }
275}
276
277add_action( 'init', array( WPCOM_Scan::class, 'init' ) );
278add_action( 'admin_post_' . WPCOM_Scan::ENABLE_ACTION, array( WPCOM_Scan::class, 'handle_enable' ) );
279// After Jetpack::activate_new_modules() on init 10, and before admin_menu registers the page.
280add_action( 'init', array( WPCOM_Scan::class, 'maybe_activate_protect_dashboard_module' ), 20 );