Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.64% covered (success)
97.64%
124 / 127
76.92% covered (warning)
76.92%
10 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
Stats_Settings
97.64% covered (success)
97.64%
124 / 127
76.92% covered (warning)
76.92%
10 / 13
49
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%
7 / 7
100.00% covered (success)
100.00%
1 / 1
6
 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        $roles  = wp_roles()->roles;
194        $slugs  = is_array( $roles ) ? array_keys( $roles ) : array();
195
196        foreach ( array( 'roles', 'count_roles' ) as $field ) {
197            if ( is_array( $stored ) && isset( $stored[ $field ] ) && is_array( $stored[ $field ] ) ) {
198                $slugs = array_merge( $slugs, array_filter( $stored[ $field ], 'is_string' ) );
199            }
200        }
201
202        return array_values( array_unique( $slugs ) );
203    }
204
205    /**
206     * Answer the settings route with the editable fields only, defaults included.
207     *
208     * @param mixed  $value The value another filter supplied, or null.
209     * @param string $name  The setting's name on the route.
210     * @return mixed The editable fields for `stats_options`, otherwise `$value`.
211     */
212    public static function get_stats_options( $value, $name ) {
213        if ( Stats_Options::OPTION_NAME !== $name ) {
214            return $value;
215        }
216
217        return Stats_Package_Settings::get( self::get_stats_option_fields() );
218    }
219
220    /**
221     * Save a write to `stats_options` through the Stats package, which keeps the option's internal state and administrators' access.
222     *
223     * Core ignores an error from this filter, so a refusal is held for `report_update_error()`.
224     *
225     * @param bool   $updated Whether another filter saved the setting.
226     * @param string $name    The setting's name on the route.
227     * @param mixed  $value   The value sent.
228     * @return bool Whether the setting was handled.
229     */
230    public static function update_stats_options( $updated, $name, $value ) {
231        if ( Stats_Options::OPTION_NAME !== $name ) {
232            return $updated;
233        }
234
235        $result = Stats_Package_Settings::update( is_array( $value ) ? $value : array(), self::get_stats_option_fields() );
236
237        if ( is_wp_error( $result ) ) {
238            self::$update_error = $result;
239        }
240
241        return true;
242    }
243
244    /**
245     * Answer the settings route with the Stats package's refusal, when it refused the write.
246     *
247     * @param mixed $response The route's response.
248     * @return mixed The refusal, otherwise `$response`.
249     */
250    public static function report_update_error( $response ) {
251        if ( null === self::$update_error ) {
252            return $response;
253        }
254
255        $error              = self::$update_error;
256        self::$update_error = null;
257
258        return $error;
259    }
260
261    /**
262     * 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.
263     *
264     * @param array $data The script data.
265     * @return array The script data with the Stats settings context added.
266     */
267    public static function add_script_data( $data ) {
268        $fields = self::get_fields();
269        if ( array() === $fields || ! current_user_can( 'manage_options' ) ) {
270            return $data;
271        }
272
273        if ( ! isset( $data['premium_analytics'] ) || ! is_array( $data['premium_analytics'] ) ) {
274            $data['premium_analytics'] = array();
275        }
276
277        $features_screen = self::get_features_screen();
278
279        $data['premium_analytics']['stats_settings'] = array(
280            'fields'          => $fields,
281            'roles'           => array_intersect( array( 'roles', 'count_roles' ), $fields ) ? self::get_roles_with_counts() : array(),
282            'features_url'    => null === $features_screen ? null : admin_url( self::FEATURES_SCREENS[ $features_screen ] ),
283            'features_screen' => $features_screen,
284        );
285        if ( in_array( self::CONSENT, $fields, true ) ) {
286            $data['premium_analytics']['stats_settings']['consent'] = self::get_consent_status();
287        }
288
289        return $data;
290    }
291
292    /**
293     * The site's editable roles, with how many users hold each.
294     *
295     * @return array[]
296     */
297    private static function get_roles_with_counts() {
298        if ( ! function_exists( 'get_editable_roles' ) ) {
299            require_once ABSPATH . 'wp-admin/includes/user.php';
300        }
301
302        // Counting users is a slow query on large sites, so their roles come without counts.
303        $counts = wp_is_large_user_count() ? null : count_users()['avail_roles'];
304        $roles  = array();
305        foreach ( get_editable_roles() as $slug => $role ) {
306            $roles[] = array(
307                'slug'  => $slug,
308                'name'  => translate_user_role( $role['name'] ),
309                'count' => null === $counts ? null : (int) ( $counts[ $slug ] ?? 0 ),
310            );
311        }
312
313        return $roles;
314    }
315
316    /**
317     * Whether visitor consent can reach Stats: the WP Consent API bridge, and a cookie banner plugin behind it.
318     *
319     * @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}
320     */
321    private static function get_consent_status() {
322        $plugin_file    = 'wp-consent-api/wp-consent-api.php';
323        $active_plugins = (array) get_option( 'active_plugins', array() );
324        if ( is_multisite() ) {
325            $active_plugins = array_merge( $active_plugins, array_keys( (array) get_site_option( 'active_sitewide_plugins', array() ) ) );
326        }
327        $banner_plugin = null;
328        foreach ( $active_plugins as $active ) {
329            $dir = strtok( $active, '/' );
330            if ( isset( self::BANNER_PLUGINS[ $dir ] ) ) {
331                $banner_plugin = self::BANNER_PLUGINS[ $dir ];
332                break;
333            }
334        }
335
336        $recommended_banners = array();
337        foreach ( self::RECOMMENDED_BANNERS as $slug ) {
338            $recommended_banners[] = array(
339                'name' => self::BANNER_PLUGINS[ $slug ],
340                'url'  => 'https://wordpress.org/plugins/' . $slug . '/',
341            );
342        }
343
344        return array(
345            'api_active'            => function_exists( 'wp_has_consent' ),
346            'api_installed'         => file_exists( WP_PLUGIN_DIR . '/' . $plugin_file ),
347            // Some banners answer this filter even before the WP Consent API is active; others set the type only in the browser, hence `banner_plugin`.
348            '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.
349            'banner_plugin'         => $banner_plugin,
350            'banner_blocks_stats'   => self::banner_blocks_stats(),
351            'recommended_banners'   => $recommended_banners,
352            // What core's `wp/v2/plugins` route checks before it installs or activates.
353            'can_install'           => current_user_can( 'install_plugins' ) && current_user_can( 'activate_plugins' ),
354            'can_activate'          => current_user_can( 'activate_plugin', $plugin_file ),
355            // The check core's `install_plugins` capability makes first, so the card can say why it cannot install.
356            'file_mods_allowed'     => wp_is_file_mod_allowed( 'capability_update_core' ),
357        );
358    }
359
360    /**
361     * Whether Complianz's Jetpack integration holds the Stats script until visitors allow statistics, with or without the WP Consent API.
362     *
363     * @return bool
364     */
365    private static function banner_blocks_stats() {
366        if ( ! function_exists( 'cmplz_integration_plugin_is_enabled' ) || ! function_exists( 'cmplz_can_run_cookie_blocker' ) ) {
367            return false;
368        }
369
370        // `true` asks whether the blocker runs on the front end, since it never runs in wp-admin.
371        // @phan-suppress-next-line PhanUndeclaredFunction -- Defined by Complianz, checked just before.
372        return cmplz_integration_plugin_is_enabled( 'jetpack' ) && cmplz_can_run_cookie_blocker( true );
373    }
374
375    /**
376     * 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.
377     *
378     * @return 'features'|'modules'|null The screen, or null when the site has neither.
379     */
380    private static function get_features_screen() {
381        if ( ! class_exists( 'Jetpack' ) ) {
382            return null;
383        }
384
385        // WordPress.com turns this off on Atomic Personal and Premium plans, which hide My Jetpack and redirect it to Stats.
386        /** This filter is documented in projects/packages/my-jetpack/src/class-initializer.php */
387        $features_available = apply_filters( 'jetpack_my_jetpack_modules_management_available', true );
388        // Jetpack can be active without My Jetpack's screen, for example in Offline Mode.
389        if ( $features_available && '' !== menu_page_url( 'my-jetpack', false ) ) {
390            return 'features';
391        }
392
393        return '' !== menu_page_url( 'jetpack_modules', false ) ? 'modules' : null;
394    }
395}