Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
59.82% covered (warning)
59.82%
67 / 112
9.09% covered (danger)
9.09%
1 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
GA_Manager
59.82% covered (warning)
59.82%
67 / 112
9.09% covered (danger)
9.09%
1 / 11
176.34
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
20
 get_instance
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 site_settings_fetch
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 site_settings_update
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
5.05
 update_google_analytics_settings
81.48% covered (warning)
81.48%
22 / 27
0.00% covered (danger)
0.00%
0 / 1
16.43
 get_invalid_code_error
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 set_status_from_module
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 get_google_analytics_option_name
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 get_google_analytics_settings
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 amp_analytics_entries
96.88% covered (success)
96.88%
31 / 32
0.00% covered (danger)
0.00%
0 / 1
3
 get_amp_tracking_codes
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * The Facade of the package.
4 *
5 * Copyright 2024 Automattic
6 * Based on code originally Copyright 2006 Aaron D. Campbell (email : wp_plugins@xavisys.com)
7 *
8 * @package automattic/jetpack-google-analytics
9 */
10
11namespace Automattic\Jetpack\Google_Analytics;
12
13use Automattic\Jetpack\Modules;
14use WP_Error;
15
16/**
17 * The Facade class of the package.
18 */
19class GA_Manager {
20
21    const PACKAGE_VERSION = '0.4.0';
22
23    /**
24     * Empty, or a Universal Analytics or GA4 Measurement ID.
25     */
26    const CODE_PATTERN = '/^(|UA-\d+-\d+|G-[A-Z0-9]+)$/i';
27
28    /**
29     * Jetpack_Google_Analytics singleton instance.
30     *
31     * @var bool|self
32     */
33    public static $instance = false;
34
35    /**
36     * Property to hold concrete analytics implementation that does the work (universal or legacy).
37     *
38     * @var Universal|Legacy|bool
39     */
40    public static $analytics = false;
41
42    /**
43     * Defaults for the API version >=1.3.
44     *
45     * @var array
46     */
47    private $api_defaults = array(
48        '1.3' => array(
49            'code'                 => '',
50            'anonymize_ip'         => false,
51            'ec_track_purchases'   => false,
52            'ec_track_add_to_cart' => false,
53        ),
54        '1.4' => array(
55            'is_active'                     => false, // This default value will most likely be overwritten by the current status of the GA module.
56            'code'                          => '',
57            'anonymize_ip'                  => false,
58            'honor_dnt'                     => false,
59            'ec_track_purchases'            => false,
60            'ec_track_add_to_cart'          => false,
61            'enh_ec_tracking'               => false,
62            'enh_ec_track_remove_from_cart' => false,
63            'enh_ec_track_prod_impression'  => false,
64            'enh_ec_track_prod_click'       => false,
65            'enh_ec_track_prod_detail_view' => false,
66            'enh_ec_track_checkout_started' => false,
67        ),
68    );
69
70    /**
71     * This is our constructor, which is private to force the use of get_instance()
72     *
73     * @return void
74     */
75    private function __construct() {
76        $settings = $this->get_google_analytics_settings();
77
78        if ( ! empty( $settings['is_active'] ) ) {
79            // At this time, we only leverage universal analytics when enhanced ecommerce is selected and WooCommerce is active.
80            // Otherwise, don't bother emitting the tracking ID or fetching analytics.js
81            if ( class_exists( 'WooCommerce' ) && Options::enhanced_ecommerce_tracking_is_enabled() ) {
82                self::$analytics = new Universal();
83                new AMP_Analytics();
84            } else {
85                self::$analytics = new Legacy();
86            }
87        }
88
89        add_filter( 'site_settings_endpoint_get', array( $this, 'site_settings_fetch' ), 10, 2 );
90        add_filter( 'site_settings_endpoint_update_wga', array( $this, 'site_settings_update' ), 10, 2 );
91        add_filter( 'site_settings_endpoint_update_jetpack_wga', array( $this, 'site_settings_update' ) );
92        add_action( 'jetpack_activate_module_google-analytics', array( $this, 'set_status_from_module' ) );
93        add_action( 'jetpack_deactivate_module_google-analytics', array( $this, 'set_status_from_module' ) );
94    }
95
96    /**
97     * Function to instantiate our class and make it a singleton
98     */
99    public static function get_instance() {
100        if ( ! self::$instance ) {
101            self::$instance = new self();
102        }
103
104        return self::$instance;
105    }
106
107    /**
108     * Includes the GA settings into site settings during a fetch request.
109     *
110     * @phan-suppress PhanUndeclaredTypeParameter,PhanUndeclaredClassInstanceof,PhanUndeclaredClassProperty
111     *
112     * @param array                                  $settings The fetched settings.
113     * @param \WPCOM_JSON_API_Site_Settings_Endpoint $api_handler The API handler object.
114     *
115     * @return array|mixed
116     */
117    public function site_settings_fetch( $settings = array(), $api_handler = null ) {
118        if ( ! is_array( $settings ) || ! $api_handler instanceof \WPCOM_JSON_API_Site_Settings_Endpoint ) {
119            // Safeguard against something that should never happen.
120            return $settings;
121        }
122
123        $settings['wga'] = $this->get_google_analytics_settings();
124
125        if ( array_key_exists( $api_handler->min_version, $this->api_defaults ) ) {
126            $settings['wga'] = wp_parse_args( $settings['wga'], $this->api_defaults[ $api_handler->min_version ] );
127        }
128
129        return $settings;
130    }
131
132    /**
133     * Modifies the GA settings into site settings during an update request.
134     *
135     * @phan-suppress PhanUndeclaredTypeParameter,PhanUndeclaredClassInstanceof,PhanUndeclaredClassProperty
136     *
137     * @param array                                  $value The settings to update.
138     * @param \WPCOM_JSON_API_Site_Settings_Endpoint $api_handler The API handler object.
139     *
140     * @return array|mixed
141     */
142    public function site_settings_update( $value, $api_handler = null ) {
143        if ( ! is_array( $value ) || ! $api_handler instanceof \WPCOM_JSON_API_Site_Settings_Endpoint ) {
144            // This should never happen.
145            return $value;
146        }
147
148        if ( ! isset( $value['code'] ) ) {
149            return self::get_invalid_code_error();
150        }
151
152        $boolean_keys = array();
153        if ( array_key_exists( $api_handler->min_version, $this->api_defaults ) ) {
154            $boolean_keys = array_keys( $this->api_defaults[ $api_handler->min_version ] );
155        }
156
157        return $this->update_google_analytics_settings( $value, $boolean_keys );
158    }
159
160    /**
161     * Validates and saves GA settings, keeping the stored keys that `$value` leaves out.
162     *
163     * @since $$next-version$$
164     *
165     * @param array    $value        Any of `code` and `$boolean_keys`.
166     * @param string[] $boolean_keys The other keys `$value` may set, each saved as a boolean.
167     *
168     * @return array|WP_Error The settings as stored.
169     */
170    public function update_google_analytics_settings( $value, $boolean_keys = array() ) {
171        $value       = is_array( $value ) ? $value : array();
172        $option_name = $this->get_google_analytics_option_name();
173        $stored      = get_option( $option_name, array() );
174        $stored      = is_array( $stored ) ? $stored : array();
175        $wga         = $stored;
176
177        if ( isset( $value['code'] ) ) {
178            $code = is_scalar( $value['code'] ) ? trim( (string) $value['code'] ) : null;
179            // Calypso resends the stored ID with every save, so one an older, looser check accepted must not block the rest.
180            $is_stored_code = ( $stored['code'] ?? null ) === $code;
181            if ( null === $code || ( ! $is_stored_code && ! preg_match( self::CODE_PATTERN, $code ) ) ) {
182                return self::get_invalid_code_error();
183            }
184            $wga['code'] = $code;
185        }
186
187        if ( ! array_key_exists( 'is_active', $wga ) ) {
188            // The `is_active` flag is missing from the settings, add a default value based on the module status.
189            $wga['is_active'] = ( new Modules() )->is_active( 'google-analytics', false );
190        }
191
192        /**
193         * Allow newer versions of this endpoint to filter in additional fields for Google Analytics
194         *
195         * @since Jetpack 5.4.0
196         * @since 0.2.0
197         *
198         * @param array $wga Associative array of existing Google Analytics settings.
199         * @param array $value Associative array of new Google Analytics settings passed to the endpoint.
200         */
201        $wga = apply_filters( 'site_settings_update_wga', $wga, $value );
202
203        foreach ( $boolean_keys as $key ) {
204            if ( 'code' !== $key && array_key_exists( $key, $value ) ) {
205                $wga[ $key ] = Utils::is_truthy( $value[ $key ] );
206            }
207        }
208
209        if ( $wga === $stored ) {
210            return $wga;
211        }
212
213        if ( ! update_option( $option_name, $wga ) ) {
214            return new WP_Error(
215                'google_analytics_not_saved',
216                __( 'Google Analytics settings could not be saved.', 'jetpack-google-analytics' )
217            );
218        }
219
220        $enabled_or_disabled = empty( $wga['code'] ) ? 'disabled' : 'enabled';
221
222        /**
223         * Fires for each settings update.
224         *
225         * @since Jetpack 3.6.0
226         * @since 0.2.0
227         *
228         * @param string $action_type Type of settings to track.
229         * @param string $val The settings value.
230         */
231        do_action( 'jetpack_bump_stats_extras', 'google-analytics', $enabled_or_disabled );
232
233        return $wga;
234    }
235
236    /**
237     * The error for a code that is neither empty nor a Measurement ID.
238     *
239     * @return WP_Error
240     */
241    private static function get_invalid_code_error() {
242        return new WP_Error(
243            'invalid_code',
244            __( 'Enter a Measurement ID, such as G-XXXXXXX.', 'jetpack-google-analytics' ),
245            array( 'status' => 400 )
246        );
247    }
248
249    /**
250     * Update the `is_active` settings flag depending on the Google Analytics module status.
251     *
252     * @return void
253     */
254    public function set_status_from_module() {
255        $option_name = $this->get_google_analytics_option_name();
256
257        $wga       = get_option( $option_name, array() );
258        $is_active = ( new Modules() )->is_active( 'google-analytics', false );
259
260        if ( ! array_key_exists( 'is_active', $wga ) || $is_active !== $wga['is_active'] ) {
261            $wga['is_active'] = $is_active;
262        }
263
264        update_option( $option_name, $wga );
265    }
266
267    /**
268     * Get the GA settings option name.
269     *
270     * @return string
271     */
272    public function get_google_analytics_option_name() {
273        /**
274         * Filter whether the current site is a Jetpack site.
275         *
276         * @since Jetpack 3.3.0
277         * @since 0.2.0
278         *
279         * @param bool $is_jetpack Is the current site a Jetpack site. Default to false.
280         * @param int $blog_id Blog ID.
281         */
282        $is_jetpack = true === apply_filters( 'is_jetpack_site', false, get_current_blog_id() );
283        return $is_jetpack ? 'jetpack_wga' : 'wga';
284    }
285
286    /**
287     * Get GA settings.
288     *
289     * @return array
290     */
291    public function get_google_analytics_settings() {
292        $settings = get_option( $this->get_google_analytics_option_name() );
293
294        // The `is_active` flag is missing from the settings, add a value based on the module status.
295        if ( is_array( $settings ) && ! array_key_exists( 'is_active', $settings ) ) {
296            $settings['is_active'] = ( new Modules() )->is_active( 'google-analytics', false );
297            update_option( $this->get_google_analytics_option_name(), $settings );
298        }
299
300        return $settings;
301    }
302
303    /**
304     * Add amp-analytics tags.
305     *
306     * @param array $analytics_entries An associative array of the analytics entries.
307     *
308     * @return array
309     */
310    public static function amp_analytics_entries( $analytics_entries ) {
311        if ( ! is_array( $analytics_entries ) ) {
312            $analytics_entries = array();
313        }
314
315        $amp_tracking_codes = static::get_amp_tracking_codes( $analytics_entries );
316        $jetpack_account    = Options::get_tracking_code();
317
318        // Bypass tracking codes already set on AMP plugin.
319        if ( in_array( $jetpack_account, $amp_tracking_codes, true ) ) {
320            return $analytics_entries;
321        }
322
323        $config_data = array(
324            'vars'     => array(
325                'account' => Options::get_tracking_code(),
326            ),
327            'triggers' => array(
328                'trackPageview' => array(
329                    'on'      => 'visible',
330                    'request' => 'pageview',
331                ),
332            ),
333        );
334
335        // Generate a hash string to uniquely identify this entry.
336        $entry_id = substr(
337            md5(
338                'googleanalytics' . wp_json_encode(
339                    $config_data,
340                    0 // phpcs:ignore Jetpack.Functions.JsonEncodeFlags.ZeroFound -- No `json_encode()` flags because we don't want to disrupt the current hash index.
341                )
342            ),
343            0,
344            12
345        );
346
347        $analytics_entries[ $entry_id ] = array(
348            'type'   => 'googleanalytics',
349            'config' => wp_json_encode( $config_data, JSON_UNESCAPED_SLASHES ),
350        );
351
352        return $analytics_entries;
353    }
354
355    /**
356     * Get AMP tracking codes.
357     *
358     * @param array $analytics_entries The codes available for AMP.
359     *
360     * @return array
361     */
362    protected static function get_amp_tracking_codes( $analytics_entries ) {
363        $entries  = array_column( $analytics_entries, 'config' );
364        $accounts = array();
365
366        foreach ( $entries as $entry ) {
367            $entry = json_decode( $entry );
368
369            if ( ! empty( $entry->vars->account ) ) {
370                $accounts[] = $entry->vars->account;
371            }
372        }
373
374        return $accounts;
375    }
376}