Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
92.96% covered (success)
92.96%
66 / 71
62.50% covered (warning)
62.50%
5 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
Google_Analytics_Settings
92.96% covered (success)
92.96%
66 / 71
62.50% covered (warning)
62.50%
5 / 8
26.24
0.00% covered (danger)
0.00%
0 / 1
 is_available
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
7
 get_entry
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 register_rest_routes
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
1
 get
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 update
89.47% covered (warning)
89.47%
17 / 19
0.00% covered (danger)
0.00%
0 / 1
7.06
 rest_get
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 rest_update
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 get_option_name
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Google Analytics settings for the settings panel.
4 *
5 * @package automattic/my-jetpack
6 */
7
8namespace Automattic\Jetpack\My_Jetpack;
9
10use Automattic\Jetpack\Google_Analytics\GA_Manager;
11use WP_Error;
12use WP_REST_Request;
13use WP_REST_Server;
14
15/**
16 * Reads and saves the built-in Google Analytics setup, a WordPress.com plan feature that has no module.
17 */
18class Google_Analytics_Settings {
19
20    /**
21     * The settings panel slug, as in `?configure=google-analytics`.
22     */
23    const SLUG = 'google-analytics';
24
25    /**
26     * The WordPress.com plan feature that includes the built-in setup.
27     */
28    const FEATURE = 'google-analytics';
29
30    /**
31     * Empty, or a Universal Analytics or GA4 Measurement ID.
32     */
33    const CODE_PATTERN = '/^(|UA-\d+-\d+|G-[A-Z0-9]+)$/i';
34
35    /**
36     * Whether the current user can set up Google Analytics in the settings panel.
37     *
38     * @return bool
39     */
40    public static function is_available() {
41        return Initializer::is_settings_consolidation_on_for_site()
42            // Offline, the route is not registered.
43            && ! Initializer::is_offline_features_enabled()
44            && current_user_can( 'manage_options' )
45            // Only jetpack-mu-wpcom loads it, so self-hosted sites never get the panel.
46            && class_exists( GA_Manager::class )
47            // jetpack-mu-wpcom ships GA_Manager on its own release schedule.
48            && method_exists( GA_Manager::class, 'get_google_analytics_option_name' )
49            && function_exists( 'wpcom_site_has_feature' )
50            && \wpcom_site_has_feature( self::FEATURE );
51    }
52
53    /**
54     * The Features row for Google Analytics.
55     *
56     * @return array{slug: string, name: string, description: string, status: string}
57     */
58    public static function get_entry() {
59        $settings = self::get();
60        if ( ! $settings['is_active'] ) {
61            $status = 'inactive';
62        } else {
63            // On without a Measurement ID, GA prints no tag.
64            $status = '' === $settings['code'] ? 'needs-setup' : 'active';
65        }
66
67        return array(
68            'slug'        => self::SLUG,
69            'name'        => __( 'Google Analytics', 'jetpack-my-jetpack' ),
70            'description' => __( 'Track your site with Google Analytics.', 'jetpack-my-jetpack' ),
71            'status'      => $status,
72        );
73    }
74
75    /**
76     * Register the REST route the panel reads and saves through.
77     *
78     * @return void
79     */
80    public static function register_rest_routes() {
81        register_rest_route(
82            'my-jetpack/v1',
83            'site/google-analytics',
84            array(
85                array(
86                    'methods'             => WP_REST_Server::READABLE,
87                    'callback'            => array( __CLASS__, 'rest_get' ),
88                    'permission_callback' => array( __CLASS__, 'is_available' ),
89                ),
90                array(
91                    'methods'             => WP_REST_Server::EDITABLE,
92                    'callback'            => array( __CLASS__, 'rest_update' ),
93                    'permission_callback' => array( __CLASS__, 'is_available' ),
94                    'args'                => array(
95                        'is_active'    => array( 'type' => 'boolean' ),
96                        'code'         => array( 'type' => 'string' ),
97                        'anonymize_ip' => array( 'type' => 'boolean' ),
98                    ),
99                ),
100            )
101        );
102    }
103
104    /**
105     * The settings the panel shows.
106     *
107     * @return array{is_active: bool, code: string, anonymize_ip: bool}
108     */
109    public static function get() {
110        $stored = get_option( self::get_option_name(), array() );
111        $stored = is_array( $stored ) ? $stored : array();
112
113        return array(
114            'is_active'    => ! empty( $stored['is_active'] ),
115            'code'         => isset( $stored['code'] ) && is_string( $stored['code'] ) ? $stored['code'] : '',
116            'anonymize_ip' => ! empty( $stored['anonymize_ip'] ),
117        );
118    }
119
120    /**
121     * Merge the given settings into the stored option, keeping the keys the panel does not show.
122     *
123     * @param array $value Any of `is_active`, `code` and `anonymize_ip`.
124     * @return true|WP_Error
125     */
126    public static function update( $value ) {
127        $value = array_intersect_key( is_array( $value ) ? $value : array(), self::get() );
128
129        if ( isset( $value['code'] ) ) {
130            $value['code'] = trim( (string) $value['code'] );
131            if ( ! preg_match( self::CODE_PATTERN, $value['code'] ) ) {
132                return new WP_Error(
133                    'invalid_google_analytics_code',
134                    __( 'Enter a Measurement ID, such as G-XXXXXXX.', 'jetpack-my-jetpack' ),
135                    array( 'status' => 400 )
136                );
137            }
138        }
139
140        $option = self::get_option_name();
141        $stored = get_option( $option, array() );
142        $stored = is_array( $stored ) ? $stored : array();
143        $merged = array_merge( $stored, $value );
144
145        /** This filter is documented in projects/packages/google-analytics/src/class-ga-manager.php */
146        $merged = apply_filters( 'site_settings_update_wga', $merged, $value ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- GA_Manager's filter, applied as its own save path does.
147        if ( $merged === $stored ) {
148            return true;
149        }
150
151        if ( ! update_option( $option, $merged ) ) {
152            return new WP_Error( 'google_analytics_not_saved', __( 'Google Analytics settings could not be saved.', 'jetpack-my-jetpack' ) );
153        }
154
155        return true;
156    }
157
158    /**
159     * REST callback: the current settings.
160     *
161     * @return \WP_REST_Response
162     */
163    public static function rest_get() {
164        return rest_ensure_response( self::get() );
165    }
166
167    /**
168     * REST callback: save, then answer with the settings as stored.
169     *
170     * @param WP_REST_Request $request The request.
171     * @return \WP_REST_Response|WP_Error
172     */
173    public static function rest_update( WP_REST_Request $request ) {
174        $result = self::update( $request->get_params() );
175
176        return is_wp_error( $result ) ? $result : rest_ensure_response( self::get() );
177    }
178
179    /**
180     * `jetpack_wga` on Atomic, `wga` on Simple.
181     *
182     * @return string
183     */
184    private static function get_option_name() {
185        return GA_Manager::get_instance()->get_google_analytics_option_name();
186    }
187}