Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.11% covered (success)
97.11%
168 / 173
91.89% covered (success)
91.89%
34 / 37
CRAP
0.00% covered (danger)
0.00%
0 / 1
Protect
97.66% covered (success)
97.66%
167 / 171
91.89% covered (success)
91.89%
34 / 37
69
0.00% covered (danger)
0.00%
0 / 1
 get_module_name
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 should_use_standalone_plugin
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 is_dashboard_module_available
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 do_product_specific_activation
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 register_endpoints
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 permissions_callback
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_name
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_title
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_description
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_long_description
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_features
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 get_tiers
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_features_by_tier
n/a
0 / 0
n/a
0 / 0
1
 get_pricing_for_ui
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
1
 does_module_need_attention
96.00% covered (success)
96.00%
24 / 25
0.00% covered (danger)
0.00%
0 / 1
7
 get_paid_plan_product_slugs
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 has_paid_plan_for_product
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_status
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 is_upgradable
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_post_checkout_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_post_checkout_urls_by_feature
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_protect_page_module_urls
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 get_firewall_settings_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 has_protect_page
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 get_info
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 get_scan_dashboard_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 get_manage_url
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
3.07
 get_manage_urls_by_feature
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 is_upgradable_by_bundle
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_site_protect_data
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
4
 get_threat_count
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_critical_threat_count
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 get_open_threats
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
3.33
 count_critical
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 filter_waf_config_by_capability
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 filter_scan_data_by_capability
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
4
 redact_threat
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 redact_extension
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Protect product
4 *
5 * @package my-jetpack
6 */
7
8namespace Automattic\Jetpack\My_Jetpack\Products;
9
10use Automattic\Jetpack\Modules;
11use Automattic\Jetpack\My_Jetpack\Hybrid_Product;
12use Automattic\Jetpack\My_Jetpack\Products;
13use Automattic\Jetpack\My_Jetpack\Wpcom_Products;
14use Automattic\Jetpack\Protect\Dashboard_Threats;
15use Automattic\Jetpack\Protect\Threat_Count;
16use Automattic\Jetpack\Protect_Status\Plan;
17use Automattic\Jetpack\Protect_Status\Status as Protect_Status;
18use Automattic\Jetpack\Redirect;
19use Automattic\Jetpack\Status\Host;
20use Automattic\Jetpack\Waf\Waf_Runner;
21use WP_Error;
22use WP_REST_Response;
23
24if ( ! defined( 'ABSPATH' ) ) {
25    exit( 0 );
26}
27
28/**
29 * Class responsible for handling the Protect product
30 */
31class Protect extends Hybrid_Product {
32
33    const FREE_TIER_SLUG             = 'free';
34    const UPGRADED_TIER_SLUG         = 'upgraded';
35    const UPGRADED_TIER_PRODUCT_SLUG = 'jetpack_scan';
36
37    const SCAN_FEATURE_SLUG     = 'scan';
38    const FIREWALL_FEATURE_SLUG = 'firewall';
39
40    /**
41     * Keys from Waf_Runner::get_config() that may be exposed to users without `manage_options`.
42     *
43     * My Jetpack is reachable with `edit_posts`, and the Protect card renders these two as
44     * on/off status indicators. Everything else the WAF config carries (IP allow/block lists,
45     * the bootstrap file path, data sharing settings) is administrator-only.
46     *
47     * @var string[]
48     */
49    private const NON_ADMIN_WAF_CONFIG_KEYS = array(
50        'jetpack_waf_automatic_rules',
51        'brute_force_protection',
52    );
53
54    /**
55     * Status_Model properties that may be exposed to users without `manage_options`.
56     *
57     * My Jetpack is reachable with `edit_posts`, and the Protect card renders scan counts, the
58     * last scan time and whether that scan failed from these. The rest of the status report --
59     * the scan state, the error details, the list of fixable threat IDs -- is administrator-only.
60     *
61     * @var string[]
62     */
63    private const NON_ADMIN_SCAN_DATA_KEYS = array(
64        'last_checked',
65        'last_scan_failed',
66        'num_threats',
67        'num_plugins_threats',
68        'num_themes_threats',
69        'threats',
70        'plugins',
71        'themes',
72        'core',
73        'files',
74        'database',
75    );
76
77    /**
78     * Threat_Model properties that may be exposed to users without `manage_options`.
79     *
80     * The card counts threats and critical (severity >= 5) threats; it never renders a threat.
81     * Everything else a threat carries -- the infected file path, the surrounding source, the
82     * signature, the database table and the vulnerable extension version -- is administrator-only.
83     *
84     * @var string[]
85     */
86    private const NON_ADMIN_THREAT_KEYS = array( 'severity' );
87
88    /**
89     * The product slug
90     *
91     * @var string
92     */
93    public static $slug = 'protect';
94
95    /**
96     * The Jetpack module name, used where the `protect-dashboard` module is not on offer.
97     *
98     * @var string
99     */
100    public static $module_name = 'protect';
101
102    /**
103     * The module that loads the Protect page.
104     *
105     * @var string
106     */
107    const DASHBOARD_MODULE_NAME = 'protect-dashboard';
108
109    /**
110     * The filename (id) of the plugin associated with this product.
111     *
112     * @var string
113     */
114    public static $plugin_filename = array(
115        'jetpack-protect/jetpack-protect.php',
116        'protect/jetpack-protect.php',
117        'jetpack-protect-dev/jetpack-protect.php',
118    );
119
120    /**
121     * The slug of the plugin associated with this product.
122     *
123     * @var string
124     */
125    public static $plugin_slug = 'jetpack-protect';
126
127    /**
128     * Get the module that switches Protect on: the Protect page's, wherever the Jetpack plugin offers it.
129     *
130     * Not with the standalone plugin active: the page module would take over that plugin's dashboard (see JETPACK-3062).
131     *
132     * @since 6.12.0
133     *
134     * @return string
135     */
136    public static function get_module_name() {
137        if ( ! static::is_standalone_plugin_active() && self::is_dashboard_module_available() ) {
138            return self::DASHBOARD_MODULE_NAME;
139        }
140        return static::$module_name;
141    }
142
143    /**
144     * Leave the standalone plugin alone where the Jetpack plugin already delivers the Protect page.
145     *
146     * @since 6.12.0
147     *
148     * @return bool
149     */
150    public static function should_use_standalone_plugin() {
151        return ! ( static::is_jetpack_plugin_active() && self::is_dashboard_module_available() );
152    }
153
154    /**
155     * Whether the Jetpack plugin offers the module that loads the Protect page, which only happens while its flag is on.
156     *
157     * Not Modules::is_module(): it passes any slug.
158     *
159     * @since 6.12.0
160     *
161     * @return bool
162     */
163    public static function is_dashboard_module_available() {
164        return in_array( self::DASHBOARD_MODULE_NAME, (array) ( new Modules() )->get_available(), true );
165    }
166
167    /**
168     * Activate local product steps without scheduling connected modules offline.
169     *
170     * @since 6.10.0
171     * @param bool|WP_Error $current_result The plugin activation result.
172     * @param bool          $local          Whether to keep activation local.
173     * @return bool|WP_Error
174     */
175    public static function do_product_specific_activation( $current_result, $local = false ) {
176        if ( $local ) {
177            // Protect's deferred admin hook would activate connected modules on the next request.
178            delete_option( static::$plugin_slug . '_activated' );
179        }
180        return parent::do_product_specific_activation( $current_result, $local );
181    }
182
183    /**
184     * The category of the product
185     *
186     * @var string
187     */
188    public static $category = 'security';
189
190    /**
191     * Whether this product requires a user connection
192     *
193     * @var string
194     */
195    public static $requires_user_connection = false;
196
197    /**
198     * Whether this product has a free offering
199     *
200     * @var bool
201     */
202    public static $has_free_offering = true;
203
204    /**
205     * Protect has a standalone plugin
206     *
207     * @var bool
208     */
209    public static $has_standalone_plugin = true;
210
211    /**
212     * The feature slug that identifies the paid plan
213     *
214     * @var string
215     */
216    public static $feature_identifying_paid_plan = 'scan';
217
218    /**
219     * Setup Protect REST API endpoints
220     *
221     * @return void
222     */
223    public static function register_endpoints(): void {
224        parent::register_endpoints();
225        // Get Jetpack Protect data.
226        register_rest_route(
227            'my-jetpack/v1',
228            '/site/protect/data',
229            array(
230                'methods'             => \WP_REST_Server::READABLE,
231                'callback'            => __CLASS__ . '::get_site_protect_data',
232                'permission_callback' => __CLASS__ . '::permissions_callback',
233            )
234        );
235    }
236
237    /**
238     * Checks if the user has the correct permissions
239     */
240    public static function permissions_callback() {
241        return current_user_can( 'edit_posts' );
242    }
243
244    /**
245     * Get the product name
246     *
247     * @return string
248     */
249    public static function get_name() {
250        return 'Protect';
251    }
252
253    /**
254     * Get the product title
255     *
256     * @return string
257     */
258    public static function get_title() {
259        return 'Jetpack Protect';
260    }
261
262    /**
263     * Get the internationalized product description
264     *
265     * @return string
266     */
267    public static function get_description() {
268        return __( 'Guard against malware and bad actors 24/7', 'jetpack-my-jetpack' );
269    }
270
271    /**
272     * Get the internationalized product long description
273     *
274     * @return string
275     */
276    public static function get_long_description() {
277        return __( 'Protect your site from bad actors and malware 24/7. Clean up security vulnerabilities with one click.', 'jetpack-my-jetpack' );
278    }
279
280    /**
281     * Get the internationalized features list
282     *
283     * @return array Protect features list
284     */
285    public static function get_features() {
286        return array(
287            __( 'Over 20,000 listed vulnerabilities', 'jetpack-my-jetpack' ),
288            __( 'Daily automatic scans', 'jetpack-my-jetpack' ),
289            __( 'Check plugin and theme version status', 'jetpack-my-jetpack' ),
290            __( 'Easy to navigate and use', 'jetpack-my-jetpack' ),
291        );
292    }
293
294    /**
295     * Get the product's available tiers
296     *
297     * @return string[] Slugs of the available tiers
298     */
299    public static function get_tiers() {
300        return array(
301            self::UPGRADED_TIER_SLUG,
302            self::FREE_TIER_SLUG,
303        );
304    }
305
306    /**
307     * Get the internationalized comparison of free vs upgraded features
308     *
309     * @deprecated 6.10.0
310     *
311     * @return array[] Protect features comparison
312     */
313    public static function get_features_by_tier() {
314        _deprecated_function( __METHOD__, 'jetpack-my-jetpack-6.10.0' );
315
316        return array(
317            array(
318                'name'  => __( 'Scan for threats and vulnerabilities', 'jetpack-my-jetpack' ),
319                'tiers' => array(
320                    self::FREE_TIER_SLUG     => array(
321                        'included'    => true,
322                        'description' => __( 'Check items against database', 'jetpack-my-jetpack' ),
323                    ),
324                    self::UPGRADED_TIER_SLUG => array(
325                        'included'    => true,
326                        'description' => __( 'Line by line malware scanning', 'jetpack-my-jetpack' ),
327                    ),
328                ),
329            ),
330            array(
331                'name'  => __( 'Daily automated scans', 'jetpack-my-jetpack' ),
332                'tiers' => array(
333                    self::FREE_TIER_SLUG     => array( 'included' => true ),
334                    self::UPGRADED_TIER_SLUG => array(
335                        'included'    => true,
336                        'description' => __( 'Plus on-demand manual scans', 'jetpack-my-jetpack' ),
337                    ),
338                ),
339            ),
340            array(
341                'name'  => __( 'Firewall', 'jetpack-my-jetpack' ),
342                'tiers' => array(
343                    self::FREE_TIER_SLUG     => array(
344                        'included'    => false,
345                        'description' => __( 'Manual rules only', 'jetpack-my-jetpack' ),
346                    ),
347                    self::UPGRADED_TIER_SLUG => array(
348                        'included'    => true,
349                        'description' => __( 'Automatic protection and rule updates', 'jetpack-my-jetpack' ),
350                    ),
351                ),
352            ),
353            array(
354                'name'  => __( 'Login protection', 'jetpack-my-jetpack' ),
355                'tiers' => array(
356                    self::FREE_TIER_SLUG     => array( 'included' => true ),
357                    self::UPGRADED_TIER_SLUG => array( 'included' => true ),
358                ),
359            ),
360            array(
361                'name'  => __( 'Account protection', 'jetpack-my-jetpack' ),
362                'tiers' => array(
363                    self::FREE_TIER_SLUG     => array( 'included' => true ),
364                    self::UPGRADED_TIER_SLUG => array( 'included' => true ),
365                ),
366            ),
367            array(
368                'name'  => __( 'Access to scan on Cloud', 'jetpack-my-jetpack' ),
369                'tiers' => array(
370                    self::FREE_TIER_SLUG     => array( 'included' => false ),
371                    self::UPGRADED_TIER_SLUG => array( 'included' => true ),
372                ),
373            ),
374            array(
375                'name'  => __( 'One-click auto fixes', 'jetpack-my-jetpack' ),
376                'tiers' => array(
377                    self::FREE_TIER_SLUG     => array( 'included' => false ),
378                    self::UPGRADED_TIER_SLUG => array( 'included' => true ),
379                ),
380            ),
381            array(
382                'name'  => __( 'Notifications', 'jetpack-my-jetpack' ),
383                'tiers' => array(
384                    self::FREE_TIER_SLUG     => array( 'included' => false ),
385                    self::UPGRADED_TIER_SLUG => array( 'included' => true ),
386                ),
387            ),
388            array(
389                'name'  => __( 'Severity labels', 'jetpack-my-jetpack' ),
390                'tiers' => array(
391                    self::FREE_TIER_SLUG     => array( 'included' => false ),
392                    self::UPGRADED_TIER_SLUG => array( 'included' => true ),
393                ),
394            ),
395        );
396    }
397
398    /**
399     * Get the product pricing details
400     *
401     * @return array Pricing details
402     */
403    public static function get_pricing_for_ui() {
404        return array(
405            'tiers' => array(
406                self::FREE_TIER_SLUG     => array(
407                    'available' => true,
408                    'is_free'   => true,
409                ),
410                self::UPGRADED_TIER_SLUG => array_merge(
411                    array(
412                        'available'          => true,
413                        'wpcom_product_slug' => self::UPGRADED_TIER_PRODUCT_SLUG,
414                    ),
415                    Wpcom_Products::get_product_pricing( self::UPGRADED_TIER_PRODUCT_SLUG )
416                ),
417            ),
418        );
419    }
420
421    /**
422     * Determines whether the module/plugin/product needs the users attention.
423     * Typically due to some sort of error where user troubleshooting is needed.
424     *
425     * Only open threats count: not those the site fixed since Scan last scanned.
426     * When refreshing the status fails, the stored one is used, as Protect's threat count does.
427     *
428     * @return boolean|array
429     */
430    public static function does_module_need_attention() {
431        $protect_data = Protect_Status::get_status();
432        if ( is_wp_error( $protect_data ) ) {
433            return false;
434        }
435
436        // A failed refresh comes back with no threats. Protect Status before 0.9 has no get_cached_status().
437        if ( ! empty( $protect_data->error ) && method_exists( Protect_Status::class, 'get_cached_status' ) ) {
438            $protect_data = Protect_Status::get_cached_status();
439            if ( null === $protect_data ) {
440                return false;
441            }
442        }
443
444        $threats = self::get_open_threats( $protect_data ) ?? $protect_data->threats;
445        if ( empty( $threats ) ) {
446            return false;
447        }
448
449        $critical_threat_count = self::count_critical( $threats );
450        $open_ids              = array_map(
451            function ( $threat ) {
452                return $threat->id ?? null;
453            },
454            $threats
455        );
456
457        return array(
458            'type' => $critical_threat_count ? 'error' : 'warning',
459            'data' => array(
460                'threat_count'          => count( $threats ),
461                'critical_threat_count' => $critical_threat_count,
462                'fixable_threat_ids'    => array_values( array_intersect( (array) $protect_data->fixable_threat_ids, $open_ids ) ),
463            ),
464        );
465    }
466
467    /**
468     * Get the product-slugs of the paid plans for this product.
469     * (Do not include bundle plans, unless it's a bundle plan itself).
470     *
471     * @return array
472     */
473    public static function get_paid_plan_product_slugs() {
474        return Scan::get_paid_plan_product_slugs();
475    }
476
477    /**
478     * Whether the site pays for Scan, by the same check as the Protect page.
479     *
480     * @return bool
481     */
482    public static function has_paid_plan_for_product() {
483        return Plan::has_required_plan();
484    }
485
486    /**
487     * Get the card's status, Expired for a lapsed purchase that Protect Status no longer counts.
488     *
489     * @return string
490     */
491    public static function get_status() {
492        $status = parent::get_status();
493
494        // Plan only sees active purchases; the purchases lookup still lists a lapsed one, as for other products.
495        if ( Products::STATUS_CAN_UPGRADE === $status && static::is_paid_plan_expired() ) {
496            return Products::STATUS_EXPIRED;
497        }
498
499        return $status;
500    }
501
502    /**
503     * Checks whether the product can be upgraded - i.e. this shows the /#add-protect interstitial
504     *
505     * @return boolean
506     */
507    public static function is_upgradable() {
508        return ! self::has_paid_plan_for_product();
509    }
510
511    /**
512     * Get the URL the user is taken after purchasing the product through the checkout
513     *
514     * @return ?string
515     */
516    public static function get_post_checkout_url() {
517        return self::get_manage_url();
518    }
519
520    /**
521     * Get the URL the user is taken after purchasing the product through the checkout for each product feature
522     *
523     * @return ?array
524     */
525    public static function get_post_checkout_urls_by_feature() {
526        return array(
527            self::SCAN_FEATURE_SLUG     => self::get_post_checkout_url(),
528            self::FIREWALL_FEATURE_SLUG => self::get_firewall_settings_url(),
529        );
530    }
531
532    /**
533     * Where each Jetpack security module's settings live while the Protect package's dashboard is the Protect page.
534     *
535     * Screens that would offer one of these settings link there instead.
536     *
537     * @since 6.12.0
538     *
539     * @return array<string, string> Settings URLs keyed by module slug; empty without the dashboard.
540     */
541    public static function get_protect_page_module_urls() {
542        // method_exists, not class_exists: an older bundled Protect package can ship the class without it.
543        $dashboard = 'Automattic\Jetpack\Protect\Dashboard';
544        if ( ! did_action( 'jetpack_protect_dashboard_initialized' ) || ! method_exists( $dashboard, 'get_module_settings_urls' ) ) {
545            return array();
546        }
547
548        return (array) $dashboard::get_module_settings_urls();
549    }
550
551    /**
552     * The firewall's settings: the Protect page's Firewall card, or the standalone plugin's Firewall screen.
553     *
554     * @return string
555     */
556    private static function get_firewall_settings_url() {
557        return self::get_protect_page_module_urls()['waf'] ?? admin_url( 'admin.php?page=jetpack-protect#/firewall' );
558    }
559
560    /**
561     * Whether wp-admin has a Protect page, from the standalone plugin or the Protect package's dashboard.
562     *
563     * @since 6.11.0
564     *
565     * @return bool
566     */
567    public static function has_protect_page() {
568        return static::is_standalone_plugin_active() || (bool) did_action( 'jetpack_protect_dashboard_initialized' );
569    }
570
571    /**
572     * Get the product info, with whether the Protect page exists and where Scan's results are listed.
573     *
574     * @return array
575     */
576    public static function get_info() {
577        return array_merge(
578            parent::get_info(),
579            array(
580                'has_protect_page' => static::has_protect_page(),
581                'scan_results_url' => static::get_manage_url(),
582            )
583        );
584    }
585
586    /**
587     * Where a site with Scan manages its threats without the Protect page: WordPress.com on WoA, Jetpack Cloud elsewhere.
588     *
589     * @return string
590     */
591    public static function get_scan_dashboard_url() {
592        return Redirect::get_url( ( new Host() )->is_woa_site() ? 'my-jetpack-manage-scan-wpcom' : 'my-jetpack-manage-scan' );
593    }
594
595    /**
596     * Get the URL where the user manages the product
597     *
598     * @return ?string
599     */
600    public static function get_manage_url() {
601        if ( static::has_protect_page() ) {
602            // Protect admin dashboard.
603            return admin_url( 'admin.php?page=jetpack-protect' );
604        }
605
606        if ( static::has_paid_plan_for_product() ) {
607            return static::get_scan_dashboard_url();
608        }
609
610        // Free users without standalone plugin go to the Protect details page.
611        return admin_url( 'admin.php?page=my-jetpack#/protect-details' );
612    }
613
614    /**
615     * Get the URL where the user manages the product for each product feature
616     *
617     * @return ?array
618     */
619    public static function get_manage_urls_by_feature() {
620        return array(
621            self::SCAN_FEATURE_SLUG     => self::get_manage_url(),
622            self::FIREWALL_FEATURE_SLUG => self::get_firewall_settings_url(),
623        );
624    }
625
626    /**
627     * Return product bundles list
628     * that supports the product.
629     *
630     * @return array Products bundle list.
631     */
632    public static function is_upgradable_by_bundle() {
633        return array( 'security', 'complete' );
634    }
635
636    /**
637     * Return site Jetpack Protect data for the REST API.
638     *
639     * @return WP_Rest_Response|WP_Error
640     */
641    public static function get_site_protect_data() {
642        $scan_data = Protect_Status::get_status();
643
644        $waf_config          = array();
645        $waf_supported       = false;
646        $is_waf_enabled      = false;
647        $is_provided_by_host = false;
648
649        if ( class_exists( 'Automattic\Jetpack\Waf\Waf_Runner' ) ) {
650            $waf_config          = Waf_Runner::get_config();
651            $is_waf_enabled      = Waf_Runner::is_enabled();
652            $waf_supported       = Waf_Runner::is_supported_environment();
653            $is_provided_by_host = method_exists( Waf_Runner::class, 'is_provided_by_host' ) && Waf_Runner::is_provided_by_host();
654        }
655
656        $threat_count = self::get_threat_count();
657
658        return rest_ensure_response(
659            array(
660                'scanData'            => self::filter_scan_data_by_capability( $scan_data ),
661                'threatCount'         => $threat_count,
662                'criticalThreatCount' => null === $threat_count ? null : self::get_critical_threat_count(),
663                'wafConfig'           => array_merge(
664                    self::filter_waf_config_by_capability( $waf_config ),
665                    array(
666                        'waf_supported'        => $waf_supported,
667                        'waf_enabled'          => $is_waf_enabled,
668                        'waf_provided_by_host' => $is_provided_by_host,
669                    ),
670                    array( 'blocked_logins' => (int) get_site_option( 'jetpack_protect_blocked_attempts', 0 ) )
671                ),
672            )
673        );
674    }
675
676    /**
677     * The count Protect shows in its menu badge, which leaves out threats the site fixed since Scan last scanned.
678     *
679     * @return int|null Null when Protect is too old to tell, or has no stored status yet.
680     */
681    private static function get_threat_count() {
682        if ( ! class_exists( Threat_Count::class ) || ! method_exists( Threat_Count::class, 'get_cached' ) ) {
683            return null;
684        }
685        return Threat_Count::get_cached();
686    }
687
688    /**
689     * How many of the threats get_threat_count() counts are critical.
690     *
691     * Worked out here because users without `manage_options` get no threat IDs to leave fixed threats out with.
692     *
693     * @return int|null Null when Protect is too old to tell, or has no stored status yet.
694     */
695    private static function get_critical_threat_count() {
696        $status = Protect_Status::get_cached_status();
697        $open   = null === $status ? null : self::get_open_threats( $status );
698        return null === $open ? null : self::count_critical( $open );
699    }
700
701    /**
702     * Scan's threats without the ones the site fixed since Scan last scanned, as Protect counts them.
703     *
704     * @param object $status A Protect status.
705     * @return array|null Null when Protect is too old to tell.
706     */
707    private static function get_open_threats( $status ) {
708        if ( ! method_exists( Dashboard_Threats::class, 'without_resolved' ) ) {
709            return null;
710        }
711        // Protect 0.5 has no get_scanned_at(), and its get_cached() passes last_checked instead.
712        $scanned_at = method_exists( Dashboard_Threats::class, 'get_scanned_at' )
713            ? Dashboard_Threats::get_scanned_at( $status )
714            : ( $status->last_checked ?? null );
715        return Dashboard_Threats::without_resolved( $status->threats, $scanned_at );
716    }
717
718    /**
719     * How many of the threats are critical.
720     *
721     * @param array $threats Threats.
722     * @return int
723     */
724    private static function count_critical( $threats ) {
725        return count(
726            array_filter(
727                $threats,
728                function ( $threat ) {
729                    return ( $threat->severity ?? 0 ) >= 5;
730                }
731            )
732        );
733    }
734
735    /**
736     * Reduce the WAF configuration to the keys the current user is allowed to read.
737     *
738     * @param array $waf_config The WAF configuration as returned by Waf_Runner::get_config().
739     * @return array
740     */
741    private static function filter_waf_config_by_capability( array $waf_config ) {
742        if ( current_user_can( 'manage_options' ) ) {
743            return $waf_config;
744        }
745
746        return array_intersect_key( $waf_config, array_flip( self::NON_ADMIN_WAF_CONFIG_KEYS ) );
747    }
748
749    /**
750     * Reduce the scan status to the parts the current user is allowed to read.
751     *
752     * @param \Automattic\Jetpack\Protect_Models\Status_Model $scan_data The scan status as returned by Protect_Status::get_status().
753     * @return \Automattic\Jetpack\Protect_Models\Status_Model|array
754     */
755    private static function filter_scan_data_by_capability( $scan_data ) {
756        if ( current_user_can( 'manage_options' ) ) {
757            return $scan_data;
758        }
759
760        $filtered = array_intersect_key( (array) $scan_data, array_flip( self::NON_ADMIN_SCAN_DATA_KEYS ) );
761
762        // `files` and `database` hold Threat_Model instances, not extensions.
763        foreach ( array( 'threats', 'files', 'database' ) as $key ) {
764            $filtered[ $key ] = array_map( array( __CLASS__, 'redact_threat' ), (array) ( $filtered[ $key ] ?? array() ) );
765        }
766
767        foreach ( array( 'plugins', 'themes' ) as $key ) {
768            $filtered[ $key ] = array_map( array( __CLASS__, 'redact_extension' ), (array) ( $filtered[ $key ] ?? array() ) );
769        }
770
771        $filtered['core'] = self::redact_extension( $filtered['core'] ?? array() );
772
773        return $filtered;
774    }
775
776    /**
777     * Reduce a threat to the properties a user without `manage_options` may read.
778     *
779     * @param object|array $threat A Threat_Model instance.
780     * @return array
781     */
782    private static function redact_threat( $threat ) {
783        return array_intersect_key( (array) $threat, array_flip( self::NON_ADMIN_THREAT_KEYS ) );
784    }
785
786    /**
787     * Reduce an extension to the properties a user without `manage_options` may read.
788     *
789     * Only the nested threats survive: the extension's name, slug and installed version identify
790     * which vulnerable software the site is running.
791     *
792     * @param object|array $extension An Extension_Model instance.
793     * @return array
794     */
795    private static function redact_extension( $extension ) {
796        $threats = ( (array) $extension )['threats'] ?? array();
797
798        return array( 'threats' => array_map( array( __CLASS__, 'redact_threat' ), (array) $threats ) );
799    }
800}