Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.62% covered (success)
97.62%
123 / 126
76.92% covered (warning)
76.92%
10 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
Stats_Settings
97.62% covered (success)
97.62%
123 / 126
76.92% covered (warning)
76.92%
10 / 13
48
0.00% covered (danger)
0.00%
0 / 1
 configure
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 register
100.00% covered (success)
100.00%
37 / 37
100.00% covered (success)
100.00%
1 / 1
2
 get_fields
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 get_stats_option_fields
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_role_slugs
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 get_stats_options
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 update_stats_options
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 report_update_error
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 add_script_data
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
8
 get_roles_with_counts
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
5.02
 get_consent_status
96.30% covered (success)
96.30%
26 / 27
0.00% covered (danger)
0.00%
0 / 1
6
 banner_blocks_stats
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
 get_features_screen
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
1<?php
2/**
3 * The Stats settings the dashboard's Settings page edits.
4 *
5 * @package automattic/jetpack-premium-analytics
6 */
7
8namespace Automattic\Jetpack\PremiumAnalytics;
9
10use Automattic\Jetpack\Stats\Options as Stats_Options;
11use Automattic\Jetpack\Stats\Settings as Stats_Package_Settings;
12
13/**
14 * Exposes the Stats settings through core's `wp/v2/settings` route, and the settings and roles the Settings page offers through script data.
15 */
16final class Stats_Settings {
17
18    /**
19     * Filter for the settings and the consent card the site offers, so a host can leave out what its Stats does not honor.
20     *
21     * @var string
22     */
23    public const FIELDS_FILTER = 'jetpack_premium_analytics_stats_settings_fields';
24
25    /**
26     * Settings group the options register under.
27     *
28     * @var string
29     */
30    private const GROUP = 'jetpack_premium_analytics';
31
32    /**
33     * The visitor consent card's entry in the host's list. It is not a setting, so the route never offers it.
34     *
35     * @var string
36     */
37    private const CONSENT = 'consent';
38
39    /**
40     * The `stats_options` fields the Settings page edits. The option also holds internal state, which the route never exposes.
41     *
42     * @var string[]
43     */
44    private const FIELDS = array( 'admin_bar', 'roles', 'count_roles' );
45
46    /**
47     * The screens that switch the Stats module on and off, by the name the card labels its link with.
48     *
49     * @var string[]
50     */
51    private const FEATURES_SCREENS = array(
52        'features' => 'admin.php?page=my-jetpack#/features?search=stats',
53        'modules'  => 'admin.php?page=jetpack_modules&s=stats',
54    );
55
56    /**
57     * Cookie banner plugins that support the WP Consent API, by plugin directory: the WordPress.org ones the WP Consent API readme lists.
58     *
59     * @var string[]
60     */
61    private const BANNER_PLUGINS = array(
62        'arqam360-consent-privacy-pdplgdpr'       => 'Arqam360 Cookie Consent Banner',
63        'beautiful-and-responsive-cookie-consent' => 'Beautiful Cookie Consent Banner',
64        'clickio-consent'                         => 'Clickio Consent',
65        'complianz-gdpr'                          => 'Complianz',
66        'complianz-gdpr-premium'                  => 'Complianz',
67        'consent-manager'                         => 'consentmanager',
68        'cookie-law-info'                         => 'CookieYes',
69        'cookiebot'                               => 'Cookiebot',
70        'cookiefirst-gdpr-cookie-consent-banner'  => 'CookieFirst',
71        'cookiehub'                               => 'CookieHub',
72        'cookietractor'                           => 'CookieTractor',
73        'gdpr-cookie-compliance'                  => 'GDPR Cookie Compliance',
74        'ibamu'                                   => 'Lawwwing',
75        'iubenda-cookie-law-solution'             => 'iubenda',
76        'pressidium-cookie-consent'               => 'Pressidium Cookie Consent',
77        'sirdata-cmp'                             => 'Abconsent Sirdata CMP',
78        'trustarc-cookie-consent-manager'         => 'TrustArc Cookie Consent Manager',
79    );
80
81    /**
82     * The banner plugins the card suggests, by WordPress.org slug.
83     *
84     * @var string[]
85     */
86    private const RECOMMENDED_BANNERS = array( 'complianz-gdpr', 'cookiebot', 'cookie-law-info' );
87
88    /**
89     * The Stats package's refusal of the current write, held until the route answers.
90     *
91     * @var \WP_Error|null
92     */
93    private static $update_error = null;
94
95    /**
96     * Hook up the settings route and the Settings page's script data.
97     *
98     * Call it before `rest_api_init`, or hook register() itself on that hook, which add_action() merges with this one. Add any FIELDS_FILTER callback before either.
99     *
100     * @return void
101     */
102    public static function configure() {
103        add_action( 'rest_api_init', array( __CLASS__, 'register' ) );
104        // Counting users per role costs a query, so only the dashboard pays for it.
105        if ( Analytics::renders_dashboard() ) {
106            add_filter( 'jetpack_admin_js_script_data', array( __CLASS__, 'add_script_data' ), 20 );
107        }
108    }
109
110    /**
111     * Declare the settings so core's settings route exposes them.
112     *
113     * @return void
114     */
115    public static function register() {
116        $fields       = self::get_fields();
117        $stats_fields = array_values( array_intersect( self::FIELDS, $fields ) );
118        if ( array() !== $stats_fields ) {
119            $role       = array(
120                'type' => 'string',
121                'enum' => self::get_role_slugs(),
122            );
123            $properties = array(
124                'admin_bar'   => array( 'type' => 'boolean' ),
125                'roles'       => array(
126                    'type'     => 'array',
127                    'items'    => $role,
128                    'minItems' => 1,
129                ),
130                'count_roles' => array(
131                    'type'  => 'array',
132                    'items' => $role,
133                ),
134            );
135
136            register_setting(
137                self::GROUP,
138                Stats_Options::OPTION_NAME,
139                array(
140                    'type'         => 'object',
141                    'show_in_rest' => array(
142                        'schema' => array(
143                            'type'                 => 'object',
144                            'properties'           => array_intersect_key( $properties, array_flip( $stats_fields ) ),
145                            'additionalProperties' => false,
146                        ),
147                    ),
148                    'description'  => __( 'Jetpack Stats settings.', 'jetpack-premium-analytics-pkg' ),
149                )
150            );
151        }
152        add_filter( 'rest_pre_get_setting', array( __CLASS__, 'get_stats_options' ), 10, 2 );
153        add_filter( 'rest_pre_update_setting', array( __CLASS__, 'update_stats_options' ), 10, 3 );
154        add_filter( 'rest_request_after_callbacks', array( __CLASS__, 'report_update_error' ) );
155    }
156
157    /**
158     * What the site offers: the `stats_options` fields and the consent card, less any the host leaves out.
159     *
160     * @return string[]
161     */
162    private static function get_fields() {
163        $fields = array_merge( self::FIELDS, array( self::CONSENT ) );
164
165        /**
166         * Filters the Stats settings the dashboard's Settings page and the settings route offer, and whether the page shows the visitor consent card.
167         *
168         * @since 0.16.0
169         *
170         * @param string[] $fields `admin_bar`, `roles`, `count_roles` and `consent`.
171         */
172        $kept = apply_filters( self::FIELDS_FILTER, $fields );
173
174        return array_values( array_intersect( $fields, is_array( $kept ) ? $kept : array() ) );
175    }
176
177    /**
178     * The `stats_options` fields the site offers.
179     *
180     * @return string[]
181     */
182    private static function get_stats_option_fields() {
183        return array_values( array_intersect( self::FIELDS, self::get_fields() ) );
184    }
185
186    /**
187     * The role slugs the role fields accept: the site's roles, plus any already stored, so a removed role still reads back.
188     *
189     * @return string[]
190     */
191    private static function get_role_slugs() {
192        $stored = get_option( Stats_Options::OPTION_NAME, array() );
193        $slugs  = array_keys( wp_roles()->roles );
194
195        foreach ( array( 'roles', 'count_roles' ) as $field ) {
196            if ( is_array( $stored ) && isset( $stored[ $field ] ) && is_array( $stored[ $field ] ) ) {
197                $slugs = array_merge( $slugs, array_filter( $stored[ $field ], 'is_string' ) );
198            }
199        }
200
201        return array_values( array_unique( $slugs ) );
202    }
203
204    /**
205     * Answer the settings route with the editable fields only, defaults included.
206     *
207     * @param mixed  $value The value another filter supplied, or null.
208     * @param string $name  The setting's name on the route.
209     * @return mixed The editable fields for `stats_options`, otherwise `$value`.
210     */
211    public static function get_stats_options( $value, $name ) {
212        if ( Stats_Options::OPTION_NAME !== $name ) {
213            return $value;
214        }
215
216        return Stats_Package_Settings::get( self::get_stats_option_fields() );
217    }
218
219    /**
220     * Save a write to `stats_options` through the Stats package, which keeps the option's internal state and administrators' access.
221     *
222     * Core ignores an error from this filter, so a refusal is held for `report_update_error()`.
223     *
224     * @param bool   $updated Whether another filter saved the setting.
225     * @param string $name    The setting's name on the route.
226     * @param mixed  $value   The value sent.
227     * @return bool Whether the setting was handled.
228     */
229    public static function update_stats_options( $updated, $name, $value ) {
230        if ( Stats_Options::OPTION_NAME !== $name ) {
231            return $updated;
232        }
233
234        $result = Stats_Package_Settings::update( is_array( $value ) ? $value : array(), self::get_stats_option_fields() );
235
236        if ( is_wp_error( $result ) ) {
237            self::$update_error = $result;
238        }
239
240        return true;
241    }
242
243    /**
244     * Answer the settings route with the Stats package's refusal, when it refused the write.
245     *
246     * @param mixed $response The route's response.
247     * @return mixed The refusal, otherwise `$response`.
248     */
249    public static function report_update_error( $response ) {
250        if ( null === self::$update_error ) {
251            return $response;
252        }
253
254        $error              = self::$update_error;
255        self::$update_error = null;
256
257        return $error;
258    }
259
260    /**
261     * Give the Settings page the settings it shows, the roles it lists with how many users hold each, the screen that switches the Stats module on and off, and the visitor consent setup.
262     *
263     * @param array $data The script data.
264     * @return array The script data with the Stats settings context added.
265     */
266    public static function add_script_data( $data ) {
267        $fields = self::get_fields();
268        if ( array() === $fields || ! current_user_can( 'manage_options' ) ) {
269            return $data;
270        }
271
272        if ( ! isset( $data['premium_analytics'] ) || ! is_array( $data['premium_analytics'] ) ) {
273            $data['premium_analytics'] = array();
274        }
275
276        $features_screen = self::get_features_screen();
277
278        $data['premium_analytics']['stats_settings'] = array(
279            'fields'          => $fields,
280            'roles'           => array_intersect( array( 'roles', 'count_roles' ), $fields ) ? self::get_roles_with_counts() : array(),
281            'features_url'    => null === $features_screen ? null : admin_url( self::FEATURES_SCREENS[ $features_screen ] ),
282            'features_screen' => $features_screen,
283        );
284        if ( in_array( self::CONSENT, $fields, true ) ) {
285            $data['premium_analytics']['stats_settings']['consent'] = self::get_consent_status();
286        }
287
288        return $data;
289    }
290
291    /**
292     * The site's editable roles, with how many users hold each.
293     *
294     * @return array[]
295     */
296    private static function get_roles_with_counts() {
297        if ( ! function_exists( 'get_editable_roles' ) ) {
298            require_once ABSPATH . 'wp-admin/includes/user.php';
299        }
300
301        // Counting users is a slow query on large sites, so their roles come without counts.
302        $counts = wp_is_large_user_count() ? null : count_users()['avail_roles'];
303        $roles  = array();
304        foreach ( get_editable_roles() as $slug => $role ) {
305            $roles[] = array(
306                'slug'  => $slug,
307                'name'  => translate_user_role( $role['name'] ),
308                'count' => null === $counts ? null : (int) ( $counts[ $slug ] ?? 0 ),
309            );
310        }
311
312        return $roles;
313    }
314
315    /**
316     * Whether visitor consent can reach Stats: the WP Consent API bridge, and a cookie banner plugin behind it.
317     *
318     * @return array{api_active: bool, api_installed: bool, consent_type_declared: bool, banner_plugin: string|null, banner_blocks_stats: bool, recommended_banners: list<array{name: string, url: string}>, can_install: bool, can_activate: bool, file_mods_allowed: bool}
319     */
320    private static function get_consent_status() {
321        $plugin_file    = 'wp-consent-api/wp-consent-api.php';
322        $active_plugins = (array) get_option( 'active_plugins', array() );
323        if ( is_multisite() ) {
324            $active_plugins = array_merge( $active_plugins, array_keys( (array) get_site_option( 'active_sitewide_plugins', array() ) ) );
325        }
326        $banner_plugin = null;
327        foreach ( $active_plugins as $active ) {
328            $dir = strtok( $active, '/' );
329            if ( isset( self::BANNER_PLUGINS[ $dir ] ) ) {
330                $banner_plugin = self::BANNER_PLUGINS[ $dir ];
331                break;
332            }
333        }
334
335        $recommended_banners = array();
336        foreach ( self::RECOMMENDED_BANNERS as $slug ) {
337            $recommended_banners[] = array(
338                'name' => self::BANNER_PLUGINS[ $slug ],
339                'url'  => 'https://wordpress.org/plugins/' . $slug . '/',
340            );
341        }
342
343        return array(
344            'api_active'            => function_exists( 'wp_has_consent' ),
345            'api_installed'         => file_exists( WP_PLUGIN_DIR . '/' . $plugin_file ),
346            // Some banners answer this filter even before the WP Consent API is active; others set the type only in the browser, hence `banner_plugin`.
347            'consent_type_declared' => (bool) apply_filters( 'wp_get_consent_type', '' ), // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- The WP Consent API's filter, which banner plugins answer.
348            'banner_plugin'         => $banner_plugin,
349            'banner_blocks_stats'   => self::banner_blocks_stats(),
350            'recommended_banners'   => $recommended_banners,
351            // What core's `wp/v2/plugins` route checks before it installs or activates.
352            'can_install'           => current_user_can( 'install_plugins' ) && current_user_can( 'activate_plugins' ),
353            'can_activate'          => current_user_can( 'activate_plugin', $plugin_file ),
354            // The check core's `install_plugins` capability makes first, so the card can say why it cannot install.
355            'file_mods_allowed'     => wp_is_file_mod_allowed( 'capability_update_core' ),
356        );
357    }
358
359    /**
360     * Whether Complianz's Jetpack integration holds the Stats script until visitors allow statistics, with or without the WP Consent API.
361     *
362     * @return bool
363     */
364    private static function banner_blocks_stats() {
365        if ( ! function_exists( 'cmplz_integration_plugin_is_enabled' ) || ! function_exists( 'cmplz_can_run_cookie_blocker' ) ) {
366            return false;
367        }
368
369        // `true` asks whether the blocker runs on the front end, since it never runs in wp-admin.
370        // @phan-suppress-next-line PhanUndeclaredFunction -- Defined by Complianz, checked just before.
371        return cmplz_integration_plugin_is_enabled( 'jetpack' ) && cmplz_can_run_cookie_blocker( true );
372    }
373
374    /**
375     * Where the Stats module is switched on and off: My Jetpack's Features, or Jetpack's Modules screen where the host keeps people out of My Jetpack.
376     *
377     * @return 'features'|'modules'|null The screen, or null when the site has neither.
378     */
379    private static function get_features_screen() {
380        if ( ! class_exists( 'Jetpack' ) ) {
381            return null;
382        }
383
384        // WordPress.com turns this off on Atomic Personal and Premium plans, which hide My Jetpack and redirect it to Stats.
385        /** This filter is documented in projects/packages/my-jetpack/src/class-initializer.php */
386        $features_available = apply_filters( 'jetpack_my_jetpack_modules_management_available', true );
387        // Jetpack can be active without My Jetpack's screen, for example in Offline Mode.
388        if ( $features_available && '' !== menu_page_url( 'my-jetpack', false ) ) {
389            return 'features';
390        }
391
392        return '' !== menu_page_url( 'jetpack_modules', false ) ? 'modules' : null;
393    }
394}