2022-12-15 17:34:08 +01:00
< ? php
/**
* Class Google\Site_Kit\Modules\Analytics_4
*
* @ package Google\Site_Kit
* @ copyright 2021 Google LLC
* @ license https :// www . apache . org / licenses / LICENSE - 2.0 Apache License 2.0
* @ link https :// sitekit . withgoogle . com
*/
2025-04-25 12:30:07 +02:00
// phpcs:disable Generic.Metrics.CyclomaticComplexity.MaxExceeded
2022-12-15 17:34:08 +01:00
namespace Google\Site_Kit\Modules ;
use Exception ;
2023-12-07 09:44:11 +01:00
use Google\Site_Kit\Context ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit\Core\Assets\Asset ;
2023-12-07 09:44:11 +01:00
use Google\Site_Kit\Core\Assets\Assets ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit\Core\Assets\Script ;
2023-12-07 09:44:11 +01:00
use Google\Site_Kit\Core\Authentication\Authentication ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit\Core\Authentication\Clients\Google_Site_Kit_Client ;
2023-09-26 10:24:36 +02:00
use Google\Site_Kit\Core\Dismissals\Dismissed_Items ;
2024-02-16 11:03:01 +01:00
use Google\Site_Kit\Core\Modules\Analytics_4\Tag_Matchers ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit\Core\Modules\Module ;
use Google\Site_Kit\Core\Modules\Module_Settings ;
2023-09-26 10:24:36 +02:00
use Google\Site_Kit\Core\Modules\Module_With_Activation ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit\Core\Modules\Module_With_Deactivation ;
use Google\Site_Kit\Core\Modules\Module_With_Debug_Fields ;
use Google\Site_Kit\Core\Modules\Module_With_Assets ;
use Google\Site_Kit\Core\Modules\Module_With_Assets_Trait ;
2023-04-26 17:39:43 +02:00
use Google\Site_Kit\Core\Modules\Module_With_Data_Available_State ;
use Google\Site_Kit\Core\Modules\Module_With_Data_Available_State_Trait ;
2025-08-27 08:44:30 +02:00
use Google\Site_Kit\Core\Modules\Module_With_Inline_Data ;
use Google\Site_Kit\Core\Modules\Module_With_Inline_Data_Trait ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit\Core\Modules\Module_With_Scopes ;
use Google\Site_Kit\Core\Modules\Module_With_Scopes_Trait ;
use Google\Site_Kit\Core\Modules\Module_With_Settings ;
use Google\Site_Kit\Core\Modules\Module_With_Settings_Trait ;
use Google\Site_Kit\Core\Modules\Module_With_Owner ;
use Google\Site_Kit\Core\Modules\Module_With_Owner_Trait ;
use Google\Site_Kit\Core\Modules\Module_With_Service_Entity ;
2024-04-17 11:32:24 +02:00
use Google\Site_Kit\Core\Permissions\Permissions ;
2024-02-16 11:03:01 +01:00
use Google\Site_Kit\Core\Modules\Module_With_Tag ;
use Google\Site_Kit\Core\Modules\Module_With_Tag_Trait ;
use Google\Site_Kit\Core\Modules\Tags\Module_Tag_Matchers ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit\Core\REST_API\Exception\Invalid_Datapoint_Exception ;
use Google\Site_Kit\Core\REST_API\Data_Request ;
2024-04-17 11:32:24 +02:00
use Google\Site_Kit\Core\REST_API\Exception\Invalid_Param_Exception ;
2023-04-26 17:39:43 +02:00
use Google\Site_Kit\Core\REST_API\Exception\Missing_Required_Param_Exception ;
2024-02-16 11:03:01 +01:00
use Google\Site_Kit\Core\Site_Health\Debug_Data ;
2023-12-07 09:44:11 +01:00
use Google\Site_Kit\Core\Storage\Options ;
use Google\Site_Kit\Core\Storage\User_Options ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit\Core\Tags\Guards\Tag_Environment_Type_Guard ;
use Google\Site_Kit\Core\Tags\Guards\Tag_Verify_Guard ;
use Google\Site_Kit\Core\Util\BC_Functions ;
2023-01-25 20:43:46 +01:00
use Google\Site_Kit\Core\Util\Feature_Flags ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit\Core\Util\Method_Proxy_Trait ;
2023-01-25 20:43:46 +01:00
use Google\Site_Kit\Core\Util\Sort ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit\Core\Util\URL ;
2024-04-17 11:32:24 +02:00
use Google\Site_Kit\Modules\AdSense\Settings as AdSense_Settings ;
use Google\Site_Kit\Modules\Analytics_4\Account_Ticket ;
use Google\Site_Kit\Modules\Analytics_4\Advanced_Tracking ;
2023-09-26 10:24:36 +02:00
use Google\Site_Kit\Modules\Analytics_4\AMP_Tag ;
2023-12-07 09:44:11 +01:00
use Google\Site_Kit\Modules\Analytics_4\Custom_Dimensions_Data_Available ;
2024-02-16 11:03:01 +01:00
use Google\Site_Kit\Modules\Analytics_4\Synchronize_Property ;
2024-04-17 11:32:24 +02:00
use Google\Site_Kit\Modules\Analytics_4\Synchronize_AdSenseLinked ;
2023-04-26 17:39:43 +02:00
use Google\Site_Kit\Modules\Analytics_4\GoogleAnalyticsAdmin\AccountProvisioningService ;
2023-12-07 09:44:11 +01:00
use Google\Site_Kit\Modules\Analytics_4\GoogleAnalyticsAdmin\EnhancedMeasurementSettingsModel ;
2024-02-16 11:03:01 +01:00
use Google\Site_Kit\Modules\Analytics_4\GoogleAnalyticsAdmin\PropertiesAdSenseLinksService ;
use Google\Site_Kit\Modules\Analytics_4\GoogleAnalyticsAdmin\PropertiesAudiencesService ;
2023-09-26 10:24:36 +02:00
use Google\Site_Kit\Modules\Analytics_4\GoogleAnalyticsAdmin\PropertiesEnhancedMeasurementService ;
2023-04-26 17:39:43 +02:00
use Google\Site_Kit\Modules\Analytics_4\GoogleAnalyticsAdmin\Proxy_GoogleAnalyticsAdminProvisionAccountTicketRequest ;
use Google\Site_Kit\Modules\Analytics_4\Report\Request as Analytics_4_Report_Request ;
use Google\Site_Kit\Modules\Analytics_4\Report\Response as Analytics_4_Report_Response ;
2025-02-28 08:42:11 +01:00
use Google\Site_Kit\Modules\Analytics_4\Report\PivotRequest as Analytics_4_PivotReport_Request ;
use Google\Site_Kit\Modules\Analytics_4\Resource_Data_Availability_Date ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit\Modules\Analytics_4\Settings ;
2024-04-17 11:32:24 +02:00
use Google\Site_Kit\Modules\Analytics_4\Synchronize_AdsLinked ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit\Modules\Analytics_4\Tag_Guard ;
2023-12-07 09:44:11 +01:00
use Google\Site_Kit\Modules\Analytics_4\Tag_Interface ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit\Modules\Analytics_4\Web_Tag ;
use Google\Site_Kit_Dependencies\Google\Model as Google_Model ;
2023-04-26 17:39:43 +02:00
use Google\Site_Kit_Dependencies\Google\Service\AnalyticsData as Google_Service_AnalyticsData ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit_Dependencies\Google\Service\GoogleAnalyticsAdmin as Google_Service_GoogleAnalyticsAdmin ;
2024-02-16 11:03:01 +01:00
use Google\Site_Kit_Dependencies\Google\Service\GoogleAnalyticsAdmin\GoogleAnalyticsAdminV1alphaAudience ;
2023-04-26 17:39:43 +02:00
use Google\Site_Kit_Dependencies\Google\Service\GoogleAnalyticsAdmin\GoogleAnalyticsAdminV1betaAccount ;
2023-12-07 09:44:11 +01:00
use Google\Site_Kit_Dependencies\Google\Service\GoogleAnalyticsAdmin\GoogleAnalyticsAdminV1betaCustomDimension ;
2023-01-25 20:43:46 +01:00
use Google\Site_Kit_Dependencies\Google\Service\GoogleAnalyticsAdmin\GoogleAnalyticsAdminV1betaDataStream ;
use Google\Site_Kit_Dependencies\Google\Service\GoogleAnalyticsAdmin\GoogleAnalyticsAdminV1betaDataStreamWebStreamData ;
use Google\Site_Kit_Dependencies\Google\Service\GoogleAnalyticsAdmin\GoogleAnalyticsAdminV1betaListDataStreamsResponse ;
use Google\Site_Kit_Dependencies\Google\Service\GoogleAnalyticsAdmin\GoogleAnalyticsAdminV1betaProperty as Google_Service_GoogleAnalyticsAdmin_GoogleAnalyticsAdminV1betaProperty ;
use Google\Site_Kit_Dependencies\Google\Service\TagManager as Google_Service_TagManager ;
2023-04-26 17:39:43 +02:00
use Google\Site_Kit_Dependencies\Google_Service_TagManager_Container ;
2022-12-15 17:34:08 +01:00
use Google\Site_Kit_Dependencies\Psr\Http\Message\RequestInterface ;
2025-02-28 08:42:11 +01:00
use Google\Site_Kit\Core\REST_API\REST_Routes ;
2025-07-27 19:58:08 +02:00
use Google\Site_Kit\Core\Tags\Google_Tag_Gateway\Google_Tag_Gateway ;
2025-04-25 12:30:07 +02:00
use Google\Site_Kit\Modules\Analytics_4\Audience_Settings ;
2025-02-28 08:42:11 +01:00
use Google\Site_Kit\Modules\Analytics_4\Conversion_Reporting\Conversion_Reporting_Cron ;
use Google\Site_Kit\Modules\Analytics_4\Conversion_Reporting\Conversion_Reporting_Events_Sync ;
use Google\Site_Kit\Modules\Analytics_4\Conversion_Reporting\Conversion_Reporting_New_Badge_Events_Sync ;
use Google\Site_Kit\Modules\Analytics_4\Conversion_Reporting\Conversion_Reporting_Provider ;
use Google\Site_Kit\Modules\Analytics_4\Reset_Audiences ;
2022-12-15 17:34:08 +01:00
use stdClass ;
use WP_Error ;
2025-02-28 08:42:11 +01:00
use WP_Post ;
2022-12-15 17:34:08 +01:00
/**
* Class representing the Analytics 4 module .
*
* @ since 1.30 . 0
* @ access private
* @ ignore
*/
2025-08-27 08:44:30 +02:00
final class Analytics_4 extends Module implements Module_With_Inline_Data , Module_With_Scopes , Module_With_Settings , Module_With_Debug_Fields , Module_With_Owner , Module_With_Assets , Module_With_Service_Entity , Module_With_Activation , Module_With_Deactivation , Module_With_Data_Available_State , Module_With_Tag {
2024-04-17 11:32:24 +02:00
2022-12-15 17:34:08 +01:00
use Method_Proxy_Trait ;
use Module_With_Assets_Trait ;
use Module_With_Owner_Trait ;
use Module_With_Scopes_Trait ;
use Module_With_Settings_Trait ;
2023-04-26 17:39:43 +02:00
use Module_With_Data_Available_State_Trait ;
2024-02-16 11:03:01 +01:00
use Module_With_Tag_Trait ;
2025-08-27 08:44:30 +02:00
use Module_With_Inline_Data_Trait ;
2022-12-15 17:34:08 +01:00
2024-04-17 11:32:24 +02:00
const PROVISION_ACCOUNT_TICKET_ID = 'googlesitekit_analytics_provision_account_ticket_id' ;
2025-07-27 19:58:08 +02:00
const READONLY_SCOPE = 'https://www.googleapis.com/auth/analytics.readonly' ;
const EDIT_SCOPE = 'https://www.googleapis.com/auth/analytics.edit' ;
2024-04-17 11:32:24 +02:00
2022-12-15 17:34:08 +01:00
/**
* Module slug name .
*/
const MODULE_SLUG = 'analytics-4' ;
2023-12-07 09:44:11 +01:00
/**
* Prefix used to fetch custom dimensions in reports .
*/
const CUSTOM_EVENT_PREFIX = 'customEvent:' ;
/**
* Custom dimensions tracked by Site Kit .
*/
const CUSTOM_DIMENSION_POST_AUTHOR = 'googlesitekit_post_author' ;
const CUSTOM_DIMENSION_POST_CATEGORIES = 'googlesitekit_post_categories' ;
2025-02-28 08:42:11 +01:00
/**
* Weights for audience types when sorting audiences in the selection panel
* and within the dashboard widget .
*/
const AUDIENCE_TYPE_SORT_ORDER = array (
'USER_AUDIENCE' => 0 ,
'SITE_KIT_AUDIENCE' => 1 ,
'DEFAULT_AUDIENCE' => 2 ,
);
2023-12-07 09:44:11 +01:00
/**
* Custom_Dimensions_Data_Available instance .
*
* @ since 1.113 . 0
* @ var Custom_Dimensions_Data_Available
*/
protected $custom_dimensions_data_available ;
2024-04-17 11:32:24 +02:00
/**
2025-02-28 08:42:11 +01:00
* Reset_Audiences instance .
*
* @ since 1.137 . 0
* @ var Reset_Audiences
*/
protected $reset_audiences ;
/**
* Resource_Data_Availability_Date instance .
2024-04-17 11:32:24 +02:00
*
2025-02-28 08:42:11 +01:00
* @ since 1.127 . 0
* @ var Resource_Data_Availability_Date
2024-04-17 11:32:24 +02:00
*/
2025-02-28 08:42:11 +01:00
protected $resource_data_availability_date ;
2024-04-17 11:32:24 +02:00
2025-04-25 12:30:07 +02:00
/**
* Audience_Settings instance .
*
* @ since 1.148 . 0
*
* @ var Audience_Settings
*/
protected $audience_settings ;
2023-12-07 09:44:11 +01:00
/**
* Constructor .
*
* @ since 1.113 . 0
*
* @ param Context $context Plugin context .
* @ param Options $options Optional . Option API instance . Default is a new instance .
* @ param User_Options $user_options Optional . User Option API instance . Default is a new instance .
* @ param Authentication $authentication Optional . Authentication instance . Default is a new instance .
* @ param Assets $assets Optional . Assets API instance . Default is a new instance .
*/
public function __construct (
Context $context ,
2025-08-27 08:44:30 +02:00
? Options $options = null ,
? User_Options $user_options = null ,
? Authentication $authentication = null ,
? Assets $assets = null
2023-12-07 09:44:11 +01:00
) {
parent :: __construct ( $context , $options , $user_options , $authentication , $assets );
$this -> custom_dimensions_data_available = new Custom_Dimensions_Data_Available ( $this -> transients );
2025-02-28 08:42:11 +01:00
$this -> reset_audiences = new Reset_Audiences ( $this -> user_options );
2025-04-25 12:30:07 +02:00
$this -> audience_settings = new Audience_Settings ( $this -> options );
$this -> resource_data_availability_date = new Resource_Data_Availability_Date ( $this -> transients , $this -> get_settings (), $this -> audience_settings );
2023-12-07 09:44:11 +01:00
}
2022-12-15 17:34:08 +01:00
/**
* Registers functionality through WordPress hooks .
*
* @ since 1.30 . 0
2023-05-23 23:18:12 +02:00
* @ since 1.101 . 0 Added a filter hook to add the required `https://www.googleapis.com/auth/tagmanager.readonly` scope for GTE support .
2022-12-15 17:34:08 +01:00
*/
public function register () {
$this -> register_scopes_hook ();
2025-08-27 08:44:30 +02:00
$this -> register_inline_data ();
2024-02-16 11:03:01 +01:00
$synchronize_property = new Synchronize_Property (
$this ,
$this -> user_options
);
$synchronize_property -> register ();
2024-04-17 11:32:24 +02:00
$synchronize_adsense_linked = new Synchronize_AdSenseLinked (
$this ,
$this -> user_options ,
$this -> options
2024-02-16 11:03:01 +01:00
);
2024-04-17 11:32:24 +02:00
$synchronize_adsense_linked -> register ();
2024-02-16 11:03:01 +01:00
2024-04-17 11:32:24 +02:00
$synchronize_ads_linked = new Synchronize_AdsLinked (
$this ,
$this -> user_options
2023-04-26 17:39:43 +02:00
);
2024-04-17 11:32:24 +02:00
$synchronize_ads_linked -> register ();
2025-04-25 12:30:07 +02:00
$conversion_reporting_provider = new Conversion_Reporting_Provider (
$this -> context ,
$this -> settings ,
$this -> user_options ,
$this
);
$conversion_reporting_provider -> register ();
$this -> audience_settings -> register ();
2025-02-28 08:42:11 +01:00
2024-04-17 11:32:24 +02:00
( new Advanced_Tracking ( $this -> context ) ) -> register ();
add_action ( 'admin_init' , array ( $synchronize_property , 'maybe_schedule_synchronize_property' ) );
add_action ( 'admin_init' , array ( $synchronize_adsense_linked , 'maybe_schedule_synchronize_adsense_linked' ) );
2025-02-28 08:42:11 +01:00
add_action ( 'load-toplevel_page_googlesitekit-dashboard' , array ( $synchronize_ads_linked , 'maybe_schedule_synchronize_ads_linked' ) );
2024-04-17 11:32:24 +02:00
add_action ( 'admin_init' , $this -> get_method_proxy ( 'handle_provisioning_callback' ) );
// For non-AMP and AMP.
add_action ( 'wp_head' , $this -> get_method_proxy ( 'print_tracking_opt_out' ), 0 );
// For Web Stories plugin.
add_action ( 'web_stories_story_head' , $this -> get_method_proxy ( 'print_tracking_opt_out' ), 0 );
2022-12-15 17:34:08 +01:00
// Analytics 4 tag placement logic.
2024-02-16 11:03:01 +01:00
add_action ( 'template_redirect' , array ( $this , 'register_tag' ) );
2023-04-26 17:39:43 +02:00
2025-04-25 12:30:07 +02:00
$this -> audience_settings -> on_change (
2025-02-28 08:42:11 +01:00
function ( $old_value , $new_value ) {
// Ensure that the resource data availability dates for `availableAudiences` that no longer exist are reset.
$old_available_audiences = $old_value [ 'availableAudiences' ];
if ( $old_available_audiences ) {
$old_available_audience_names = array_map (
function ( $audience ) {
return $audience [ 'name' ];
},
$old_available_audiences
);
$new_available_audiences = $new_value [ 'availableAudiences' ] ? ? array ();
$new_available_audience_names = array_map (
function ( $audience ) {
return $audience [ 'name' ];
},
$new_available_audiences
);
$unavailable_audience_names = array_diff ( $old_available_audience_names , $new_available_audience_names );
foreach ( $unavailable_audience_names as $unavailable_audience_name ) {
$this -> resource_data_availability_date -> reset_resource_date ( $unavailable_audience_name , Resource_Data_Availability_Date :: RESOURCE_TYPE_AUDIENCE );
}
2024-02-16 11:03:01 +01:00
}
2025-04-25 12:30:07 +02:00
}
);
$this -> get_settings () -> on_change (
function ( $old_value , $new_value ) {
// Ensure that the data available state is reset when the property ID or measurement ID changes.
if ( $old_value [ 'propertyID' ] !== $new_value [ 'propertyID' ] || $old_value [ 'measurementID' ] !== $new_value [ 'measurementID' ] ) {
$this -> reset_data_available ();
$this -> custom_dimensions_data_available -> reset_data_available ();
$audience_settings = $this -> audience_settings -> get ();
$available_audiences = $audience_settings [ 'availableAudiences' ] ? ? array ();
$available_audience_names = array_map (
function ( $audience ) {
return $audience [ 'name' ];
},
$available_audiences
);
$this -> resource_data_availability_date -> reset_all_resource_dates ( $available_audience_names , $old_value [ 'propertyID' ] );
}
2023-12-07 09:44:11 +01:00
2025-02-28 08:42:11 +01:00
// Reset property specific settings when propertyID changes.
2024-02-16 11:03:01 +01:00
if ( $old_value [ 'propertyID' ] !== $new_value [ 'propertyID' ] ) {
$this -> get_settings () -> merge (
array (
'adSenseLinked' => false ,
'adSenseLinkedLastSyncedAt' => 0 ,
2024-04-17 11:32:24 +02:00
'adsLinked' => false ,
'adsLinkedLastSyncedAt' => 0 ,
2025-02-28 08:42:11 +01:00
'detectedEvents' => array (),
2024-02-16 11:03:01 +01:00
)
);
2025-02-28 08:42:11 +01:00
2025-04-25 12:30:07 +02:00
$this -> audience_settings -> delete ();
2025-02-28 08:42:11 +01:00
if ( ! empty ( $new_value [ 'propertyID' ] ) ) {
do_action ( Synchronize_AdSenseLinked :: CRON_SYNCHRONIZE_ADSENSE_LINKED );
2025-04-25 12:30:07 +02:00
// Reset event detection and new badge events.
$this -> transients -> delete ( Conversion_Reporting_Events_Sync :: DETECTED_EVENTS_TRANSIENT );
$this -> transients -> delete ( Conversion_Reporting_Events_Sync :: LOST_EVENTS_TRANSIENT );
$this -> transients -> delete ( Conversion_Reporting_New_Badge_Events_Sync :: NEW_EVENTS_BADGE_TRANSIENT );
$this -> transients -> set ( Conversion_Reporting_New_Badge_Events_Sync :: SKIP_NEW_BADGE_TRANSIENT , 1 );
do_action ( Conversion_Reporting_Cron :: CRON_ACTION );
2025-02-28 08:42:11 +01:00
}
// Reset audience specific settings.
$this -> reset_audiences -> reset_audience_data ();
2023-04-26 17:39:43 +02:00
}
2024-02-16 11:03:01 +01:00
}
2023-04-26 17:39:43 +02:00
);
2025-02-28 08:42:11 +01:00
// Check if the property ID has changed and reset applicable settings to null.
//
// This is not done using the `get_settings()->merge` method because
// `Module_Settings::merge` doesn't support setting a value to `null`.
2024-02-16 11:03:01 +01:00
add_filter (
'pre_update_option_googlesitekit_analytics-4_settings' ,
function ( $new_value , $old_value ) {
if ( $new_value [ 'propertyID' ] !== $old_value [ 'propertyID' ] ) {
2025-04-25 12:30:07 +02:00
$new_value [ 'availableCustomDimensions' ] = null ;
2024-02-16 11:03:01 +01:00
}
2023-12-07 09:44:11 +01:00
2024-02-16 11:03:01 +01:00
return $new_value ;
},
10 ,
2
);
2023-12-07 09:44:11 +01:00
2023-09-26 10:24:36 +02:00
add_filter (
'googlesitekit_auth_scopes' ,
2025-02-28 08:42:11 +01:00
function ( array $scopes ) {
2023-09-26 10:24:36 +02:00
$oauth_client = $this -> authentication -> get_oauth_client ();
2023-05-23 23:18:12 +02:00
2023-09-26 10:24:36 +02:00
$needs_tagmanager_scope = false ;
2023-05-23 23:18:12 +02:00
2023-09-26 10:24:36 +02:00
if ( $oauth_client -> has_sufficient_scopes (
array (
2024-04-17 11:32:24 +02:00
self :: READONLY_SCOPE ,
2023-09-26 10:24:36 +02:00
'https://www.googleapis.com/auth/tagmanager.readonly' ,
)
) ) {
$needs_tagmanager_scope = true ;
2025-02-28 08:42:11 +01:00
2023-09-26 10:24:36 +02:00
// Ensure the Tag Manager scope is not added as a required scope in the case where the user has
// granted the Analytics scope but not the Tag Manager scope, in order to allow the GTE-specific
// Unsatisfied Scopes notification to be displayed without the Additional Permissions Required
// modal also appearing.
2025-02-28 08:42:11 +01:00
} elseif ( ! $oauth_client -> has_sufficient_scopes (
array (
self :: READONLY_SCOPE ,
)
) ) {
2025-04-25 12:30:07 +02:00
$needs_tagmanager_scope = true ;
2023-09-26 10:24:36 +02:00
}
2023-05-23 23:18:12 +02:00
2023-09-26 10:24:36 +02:00
if ( $needs_tagmanager_scope ) {
$scopes [] = 'https://www.googleapis.com/auth/tagmanager.readonly' ;
2023-05-23 23:18:12 +02:00
}
2023-09-26 10:24:36 +02:00
return $scopes ;
}
);
2023-05-23 23:18:12 +02:00
add_filter ( 'googlesitekit_allow_tracking_disabled' , $this -> get_method_proxy ( 'filter_analytics_allow_tracking_disabled' ) );
2024-04-17 11:32:24 +02:00
// This hook adds the "Set up Google Analytics" step to the Site Kit
// setup flow.
//
// This filter is documented in
// Core\Authentication\Google_Proxy::get_metadata_fields.
add_filter (
'googlesitekit_proxy_setup_mode' ,
2025-02-28 08:42:11 +01:00
function ( $original_mode ) {
2024-04-17 11:32:24 +02:00
return ! $this -> is_connected ()
? 'analytics-step'
: $original_mode ;
}
);
2025-02-28 08:42:11 +01:00
// Preload the path to avoid layout shift for audience setup CTA banner.
add_filter (
'googlesitekit_apifetch_preload_paths' ,
function ( $routes ) {
return array_merge (
$routes ,
array (
'/' . REST_Routes :: REST_ROOT . '/modules/analytics-4/data/audience-settings' ,
)
);
}
);
2025-04-25 12:30:07 +02:00
add_filter (
'googlesitekit_ads_measurement_connection_checks' ,
function ( $checks ) {
$checks [] = array ( $this , 'check_ads_measurement_connection' );
return $checks ;
},
20
);
}
/**
* Checks if the Analytics 4 module is connected and contributing to Ads measurement .
*
* Verifies connection status and settings to determine if Ads - related configurations
* ( AdSense linked or Google Tag Container with AW - destination IDs ) exist .
*
* @ since 1.151 . 0
*
* @ return bool True if Analytics 4 is connected and configured for Ads measurement ; false otherwise .
*/
public function check_ads_measurement_connection () {
if ( ! $this -> is_connected () ) {
return false ;
}
$settings = $this -> get_settings () -> get ();
if ( $settings [ 'adsLinked' ] ) {
return true ;
}
foreach ( ( array ) $settings [ 'googleTagContainerDestinationIDs' ] as $destination_id ) {
if ( 0 === stripos ( $destination_id , 'AW-' ) ) {
return true ;
}
}
return false ;
2022-12-15 17:34:08 +01:00
}
/**
* Gets required Google OAuth scopes for the module .
*
* @ since 1.30 . 0
*
* @ return array List of Google OAuth scopes .
*/
public function get_scopes () {
2024-04-17 11:32:24 +02:00
return array ( self :: READONLY_SCOPE );
2022-12-15 17:34:08 +01:00
}
/**
* Checks whether the module is connected .
*
* A module being connected means that all steps required as part of its activation are completed .
*
* @ since 1.30 . 0
*
* @ return bool True if module is connected , false otherwise .
*/
public function is_connected () {
$required_keys = array (
2024-04-17 11:32:24 +02:00
'accountID' ,
2022-12-15 17:34:08 +01:00
'propertyID' ,
'webDataStreamID' ,
'measurementID' ,
);
$options = $this -> get_settings () -> get ();
foreach ( $required_keys as $required_key ) {
if ( empty ( $options [ $required_key ] ) ) {
return false ;
}
}
return parent :: is_connected ();
}
2023-09-26 10:24:36 +02:00
/**
* Cleans up when the module is activated .
*
* @ since 1.107 . 0
*/
public function on_activation () {
$dismissed_items = new Dismissed_Items ( $this -> user_options );
$dismissed_items -> remove ( 'key-metrics-connect-ga4-cta-widget' );
}
2022-12-15 17:34:08 +01:00
/**
* Cleans up when the module is deactivated .
*
* @ since 1.30 . 0
*/
public function on_deactivation () {
2025-02-28 08:42:11 +01:00
// We need to reset the resource data availability dates before deleting the settings.
// This is because the property ID and the audience resource names are pulled from settings.
$this -> resource_data_availability_date -> reset_all_resource_dates ();
2022-12-15 17:34:08 +01:00
$this -> get_settings () -> delete ();
2023-04-26 17:39:43 +02:00
$this -> reset_data_available ();
2024-02-16 11:03:01 +01:00
$this -> custom_dimensions_data_available -> reset_data_available ();
2025-02-28 08:42:11 +01:00
$this -> reset_audiences -> reset_audience_data ();
2025-04-25 12:30:07 +02:00
$this -> audience_settings -> delete ();
2022-12-15 17:34:08 +01:00
}
2024-04-17 11:32:24 +02:00
/**
* Checks whether the AdSense module is connected .
*
* @ since 1.121 . 0
*
* @ return bool True if AdSense is connected , false otherwise .
*/
private function is_adsense_connected () {
$adsense_settings = ( new AdSense_Settings ( $this -> options ) ) -> get ();
if ( empty ( $adsense_settings [ 'accountSetupComplete' ] ) || empty ( $adsense_settings [ 'siteSetupComplete' ] ) ) {
return false ;
}
return true ;
}
2022-12-15 17:34:08 +01:00
/**
* Gets an array of debug field definitions .
*
* @ since 1.30 . 0
*
* @ return array
*/
public function get_debug_fields () {
$settings = $this -> get_settings () -> get ();
2023-12-07 09:44:11 +01:00
$debug_fields = array (
2024-04-17 11:32:24 +02:00
'analytics_4_account_id' => array (
2025-02-28 08:42:11 +01:00
'label' => __ ( 'Analytics: Account ID' , 'google-site-kit' ),
2022-12-15 17:34:08 +01:00
'value' => $settings [ 'accountID' ],
'debug' => Debug_Data :: redact_debug_value ( $settings [ 'accountID' ] ),
),
2024-04-17 11:32:24 +02:00
'analytics_4_property_id' => array (
2025-02-28 08:42:11 +01:00
'label' => __ ( 'Analytics: Property ID' , 'google-site-kit' ),
2022-12-15 17:34:08 +01:00
'value' => $settings [ 'propertyID' ],
'debug' => Debug_Data :: redact_debug_value ( $settings [ 'propertyID' ], 7 ),
),
2024-04-17 11:32:24 +02:00
'analytics_4_web_data_stream_id' => array (
2025-02-28 08:42:11 +01:00
'label' => __ ( 'Analytics: Web Data Stream ID' , 'google-site-kit' ),
2022-12-15 17:34:08 +01:00
'value' => $settings [ 'webDataStreamID' ],
'debug' => Debug_Data :: redact_debug_value ( $settings [ 'webDataStreamID' ] ),
),
2024-04-17 11:32:24 +02:00
'analytics_4_measurement_id' => array (
2025-02-28 08:42:11 +01:00
'label' => __ ( 'Analytics: Measurement ID' , 'google-site-kit' ),
2022-12-15 17:34:08 +01:00
'value' => $settings [ 'measurementID' ],
'debug' => Debug_Data :: redact_debug_value ( $settings [ 'measurementID' ] ),
),
2024-04-17 11:32:24 +02:00
'analytics_4_use_snippet' => array (
2025-02-28 08:42:11 +01:00
'label' => __ ( 'Analytics: Snippet placed' , 'google-site-kit' ),
2022-12-15 17:34:08 +01:00
'value' => $settings [ 'useSnippet' ] ? __ ( 'Yes' , 'google-site-kit' ) : __ ( 'No' , 'google-site-kit' ),
'debug' => $settings [ 'useSnippet' ] ? 'yes' : 'no' ,
),
2024-04-17 11:32:24 +02:00
'analytics_4_available_custom_dimensions' => array (
2025-02-28 08:42:11 +01:00
'label' => __ ( 'Analytics: Available Custom Dimensions' , 'google-site-kit' ),
2024-04-17 11:32:24 +02:00
'value' => empty ( $settings [ 'availableCustomDimensions' ] )
? __ ( 'None' , 'google-site-kit' )
: join (
/* translators: used between list items, there is a space after the comma */
__ ( ', ' , 'google-site-kit' ),
$settings [ 'availableCustomDimensions' ]
),
'debug' => empty ( $settings [ 'availableCustomDimensions' ] )
? 'none'
: join ( ', ' , $settings [ 'availableCustomDimensions' ] ),
),
'analytics_4_ads_linked' => array (
2025-02-28 08:42:11 +01:00
'label' => __ ( 'Analytics: Ads Linked' , 'google-site-kit' ),
2024-04-17 11:32:24 +02:00
'value' => $settings [ 'adsLinked' ] ? __ ( 'Connected' , 'google-site-kit' ) : __ ( 'Not connected' , 'google-site-kit' ),
'debug' => $settings [ 'adsLinked' ],
),
'analytics_4_ads_linked_last_synced_at' => array (
2025-02-28 08:42:11 +01:00
'label' => __ ( 'Analytics: Ads Linked Last Synced At' , 'google-site-kit' ),
2024-04-17 11:32:24 +02:00
'value' => $settings [ 'adsLinkedLastSyncedAt' ] ? gmdate ( 'Y-m-d H:i:s' , $settings [ 'adsLinkedLastSyncedAt' ] ) : __ ( 'Never synced' , 'google-site-kit' ),
'debug' => $settings [ 'adsLinkedLastSyncedAt' ],
),
2022-12-15 17:34:08 +01:00
);
2023-12-07 09:44:11 +01:00
2024-04-17 11:32:24 +02:00
if ( $this -> is_adsense_connected () ) {
$debug_fields [ 'analytics_4_adsense_linked' ] = array (
2025-02-28 08:42:11 +01:00
'label' => __ ( 'Analytics: AdSense Linked' , 'google-site-kit' ),
2024-04-17 11:32:24 +02:00
'value' => $settings [ 'adSenseLinked' ] ? __ ( 'Connected' , 'google-site-kit' ) : __ ( 'Not connected' , 'google-site-kit' ),
'debug' => Debug_Data :: redact_debug_value ( $settings [ 'adSenseLinked' ] ),
);
$debug_fields [ 'analytics_4_adsense_linked_last_synced_at' ] = array (
2025-02-28 08:42:11 +01:00
'label' => __ ( 'Analytics: AdSense Linked Last Synced At' , 'google-site-kit' ),
2024-04-17 11:32:24 +02:00
'value' => $settings [ 'adSenseLinkedLastSyncedAt' ] ? gmdate ( 'Y-m-d H:i:s' , $settings [ 'adSenseLinkedLastSyncedAt' ] ) : __ ( 'Never synced' , 'google-site-kit' ),
'debug' => Debug_Data :: redact_debug_value ( $settings [ 'adSenseLinkedLastSyncedAt' ] ),
);
}
2023-12-07 09:44:11 +01:00
2025-04-25 12:30:07 +02:00
// Return the SITE_KIT_AUDIENCE audiences.
$available_audiences = $this -> audience_settings -> get ()[ 'availableAudiences' ] ? ? array ();
$site_kit_audiences = $this -> get_site_kit_audiences ( $available_audiences );
$debug_fields [ 'analytics_4_site_kit_audiences' ] = array (
'label' => __ ( 'Analytics: Site created audiences' , 'google-site-kit' ),
'value' => empty ( $site_kit_audiences )
? __ ( 'None' , 'google-site-kit' )
: join (
/* translators: used between list items, there is a space after the comma */
__ ( ', ' , 'google-site-kit' ),
$site_kit_audiences
),
'debug' => empty ( $site_kit_audiences )
? 'none'
: join ( ', ' , $site_kit_audiences ),
);
2025-02-28 08:42:11 +01:00
2025-07-27 19:58:08 +02:00
// Add fields from Google tag gateway.
2025-02-28 08:42:11 +01:00
// Note: fields are added in both Analytics and Ads so that the debug fields will show if either module is enabled.
2025-07-27 19:58:08 +02:00
if ( Feature_Flags :: enabled ( 'googleTagGateway' ) ) {
$google_tag_gateway = new Google_Tag_Gateway ( $this -> context );
$fields_from_google_tag_gateway = $google_tag_gateway -> get_debug_fields ();
2025-02-28 08:42:11 +01:00
2025-07-27 19:58:08 +02:00
$debug_fields = array_merge ( $debug_fields , $fields_from_google_tag_gateway );
2025-02-28 08:42:11 +01:00
}
2023-12-07 09:44:11 +01:00
return $debug_fields ;
2022-12-15 17:34:08 +01:00
}
/**
* Gets map of datapoint to definition data for each .
*
* @ since 1.30 . 0
*
* @ return array Map of datapoints to their definitions .
*/
protected function get_datapoint_definitions () {
2023-04-26 17:39:43 +02:00
$datapoints = array (
2025-04-25 12:30:07 +02:00
'GET:account-summaries' => array ( 'service' => 'analyticsadmin' ),
'GET:accounts' => array ( 'service' => 'analyticsadmin' ),
'GET:ads-links' => array ( 'service' => 'analyticsadmin' ),
'GET:adsense-links' => array ( 'service' => 'analyticsadsenselinks' ),
'GET:container-lookup' => array (
2023-05-23 23:18:12 +02:00
'service' => 'tagmanager' ,
'scopes' => array (
'https://www.googleapis.com/auth/tagmanager.readonly' ,
),
),
2025-04-25 12:30:07 +02:00
'GET:container-destinations' => array (
2023-05-23 23:18:12 +02:00
'service' => 'tagmanager' ,
'scopes' => array (
'https://www.googleapis.com/auth/tagmanager.readonly' ,
),
),
2025-07-27 19:58:08 +02:00
'GET:key-events' => array (
2023-04-26 17:39:43 +02:00
'service' => 'analyticsadmin' ,
2023-12-07 09:44:11 +01:00
'shareable' => true ,
2023-04-26 17:39:43 +02:00
),
2025-04-25 12:30:07 +02:00
'POST:create-account-ticket' => array (
2023-04-26 17:39:43 +02:00
'service' => 'analyticsprovisioning' ,
2024-04-17 11:32:24 +02:00
'scopes' => array ( self :: EDIT_SCOPE ),
2023-04-26 17:39:43 +02:00
'request_scopes_message' => __ ( 'You’ ll need to grant Site Kit permission to create a new Analytics account on your behalf.' , 'google-site-kit' ),
),
2025-04-25 12:30:07 +02:00
'GET:google-tag-settings' => array (
2023-09-26 10:24:36 +02:00
'service' => 'tagmanager' ,
'scopes' => array (
'https://www.googleapis.com/auth/tagmanager.readonly' ,
),
),
2025-04-25 12:30:07 +02:00
'POST:create-property' => array (
2022-12-15 17:34:08 +01:00
'service' => 'analyticsadmin' ,
2024-04-17 11:32:24 +02:00
'scopes' => array ( self :: EDIT_SCOPE ),
'request_scopes_message' => __ ( 'You’ ll need to grant Site Kit permission to create a new Analytics property on your behalf.' , 'google-site-kit' ),
2022-12-15 17:34:08 +01:00
),
2025-04-25 12:30:07 +02:00
'POST:create-webdatastream' => array (
2022-12-15 17:34:08 +01:00
'service' => 'analyticsadmin' ,
2024-04-17 11:32:24 +02:00
'scopes' => array ( self :: EDIT_SCOPE ),
'request_scopes_message' => __ ( 'You’ ll need to grant Site Kit permission to create a new Analytics web data stream for this site on your behalf.' , 'google-site-kit' ),
2022-12-15 17:34:08 +01:00
),
2025-04-25 12:30:07 +02:00
'GET:properties' => array ( 'service' => 'analyticsadmin' ),
'GET:property' => array ( 'service' => 'analyticsadmin' ),
'GET:report' => array (
2023-12-07 09:44:11 +01:00
'service' => 'analyticsdata' ,
'shareable' => true ,
),
2025-08-27 08:44:30 +02:00
'GET:non-shareable-report' => array ( 'service' => 'analyticsdata' ),
2025-04-25 12:30:07 +02:00
'GET:pivot-report' => array (
2025-02-28 08:42:11 +01:00
'service' => 'analyticsdata' ,
'shareable' => true ,
),
2025-04-25 12:30:07 +02:00
'GET:webdatastreams' => array ( 'service' => 'analyticsadmin' ),
'GET:webdatastreams-batch' => array ( 'service' => 'analyticsadmin' ),
'GET:enhanced-measurement-settings' => array ( 'service' => 'analyticsenhancedmeasurement' ),
'POST:enhanced-measurement-settings' => array (
2023-09-26 10:24:36 +02:00
'service' => 'analyticsenhancedmeasurement' ,
2024-04-17 11:32:24 +02:00
'scopes' => array ( self :: EDIT_SCOPE ),
'request_scopes_message' => __ ( 'You’ ll need to grant Site Kit permission to update enhanced measurement settings for this Analytics web data stream on your behalf.' , 'google-site-kit' ),
2023-09-26 10:24:36 +02:00
),
2025-04-25 12:30:07 +02:00
'POST:create-custom-dimension' => array (
2023-12-07 09:44:11 +01:00
'service' => 'analyticsdata' ,
2024-04-17 11:32:24 +02:00
'scopes' => array ( self :: EDIT_SCOPE ),
'request_scopes_message' => __ ( 'You’ ll need to grant Site Kit permission to create a new Analytics custom dimension on your behalf.' , 'google-site-kit' ),
2024-02-16 11:03:01 +01:00
),
2025-04-25 12:30:07 +02:00
'POST:sync-custom-dimensions' => array (
2023-12-07 09:44:11 +01:00
'service' => 'analyticsadmin' ,
2024-02-16 11:03:01 +01:00
),
2025-04-25 12:30:07 +02:00
'POST:custom-dimension-data-available' => array (
2024-02-16 11:03:01 +01:00
'service' => '' ,
),
2025-04-25 12:30:07 +02:00
'POST:set-google-tag-id-mismatch' => array (
2025-02-28 08:42:11 +01:00
'service' => '' ,
),
2025-08-27 08:44:30 +02:00
'POST:set-is-web-data-stream-unavailable' => array (
'service' => '' ,
),
2025-04-25 12:30:07 +02:00
'POST:create-audience' => array (
2024-02-16 11:03:01 +01:00
'service' => 'analyticsaudiences' ,
2024-04-17 11:32:24 +02:00
'scopes' => array ( self :: EDIT_SCOPE ),
'request_scopes_message' => __ ( 'You’ ll need to grant Site Kit permission to create new audiences for your Analytics property on your behalf.' , 'google-site-kit' ),
2025-04-25 12:30:07 +02:00
),
'POST:save-resource-data-availability-date' => array (
2024-04-17 11:32:24 +02:00
'service' => '' ,
2025-04-25 12:30:07 +02:00
),
'POST:sync-audiences' => array (
2025-02-28 08:42:11 +01:00
'service' => 'analyticsaudiences' ,
'shareable' => true ,
2025-04-25 12:30:07 +02:00
),
'GET:audience-settings' => array (
'service' => '' ,
'shareable' => true ,
),
'POST:save-audience-settings' => array (
'service' => '' ,
),
);
2023-04-26 17:39:43 +02:00
return $datapoints ;
2022-12-15 17:34:08 +01:00
}
/**
* Creates a new property for provided account .
*
* @ since 1.35 . 0
2023-04-26 17:39:43 +02:00
* @ since 1.98 . 0 Added `$options` parameter .
2022-12-15 17:34:08 +01:00
*
* @ param string $account_id Account ID .
2023-04-26 17:39:43 +02:00
* @ param array $options {
* Property options .
*
* @ type string $displayName Display name .
* @ type string $timezone Timezone .
* }
2023-01-25 20:43:46 +01:00
* @ return Google_Service_GoogleAnalyticsAdmin_GoogleAnalyticsAdminV1betaProperty A new property .
2022-12-15 17:34:08 +01:00
*/
2023-04-26 17:39:43 +02:00
private function create_property ( $account_id , $options = array () ) {
if ( ! empty ( $options [ 'displayName' ] ) ) {
$display_name = sanitize_text_field ( $options [ 'displayName' ] );
} else {
$display_name = URL :: parse ( $this -> context -> get_reference_site_url (), PHP_URL_HOST );
}
if ( ! empty ( $options [ 'timezone' ] ) ) {
$timezone = $options [ 'timezone' ];
} else {
$timezone = get_option ( 'timezone_string' ) ? : 'UTC' ;
2022-12-15 17:34:08 +01:00
}
2023-01-25 20:43:46 +01:00
$property = new Google_Service_GoogleAnalyticsAdmin_GoogleAnalyticsAdminV1betaProperty ();
2022-12-15 17:34:08 +01:00
$property -> setParent ( self :: normalize_account_id ( $account_id ) );
2023-04-26 17:39:43 +02:00
$property -> setDisplayName ( $display_name );
2022-12-15 17:34:08 +01:00
$property -> setTimeZone ( $timezone );
return $this -> get_service ( 'analyticsadmin' ) -> properties -> create ( $property );
}
/**
* Creates a new web data stream for provided property .
*
* @ since 1.35 . 0
2023-04-26 17:39:43 +02:00
* @ since 1.98 . 0 Added `$options` parameter .
2022-12-15 17:34:08 +01:00
*
* @ param string $property_id Property ID .
2023-04-26 17:39:43 +02:00
* @ param array $options {
* Web data stream options .
*
* @ type string $displayName Display name .
* }
2023-01-25 20:43:46 +01:00
* @ return GoogleAnalyticsAdminV1betaDataStream A new web data stream .
2022-12-15 17:34:08 +01:00
*/
2023-04-26 17:39:43 +02:00
private function create_webdatastream ( $property_id , $options = array () ) {
2022-12-15 17:34:08 +01:00
$site_url = $this -> context -> get_reference_site_url ();
2023-04-26 17:39:43 +02:00
if ( ! empty ( $options [ 'displayName' ] ) ) {
$display_name = sanitize_text_field ( $options [ 'displayName' ] );
} else {
$display_name = URL :: parse ( $site_url , PHP_URL_HOST );
}
$data = new GoogleAnalyticsAdminV1betaDataStreamWebStreamData ();
2022-12-15 17:34:08 +01:00
$data -> setDefaultUri ( $site_url );
2023-01-25 20:43:46 +01:00
$datastream = new GoogleAnalyticsAdminV1betaDataStream ();
2023-04-26 17:39:43 +02:00
$datastream -> setDisplayName ( $display_name );
2022-12-15 17:34:08 +01:00
$datastream -> setType ( 'WEB_DATA_STREAM' );
$datastream -> setWebStreamData ( $data );
/* @var Google_Service_GoogleAnalyticsAdmin $analyticsadmin phpcs:ignore Squiz.PHP.CommentedOutCode.Found */
$analyticsadmin = $this -> get_service ( 'analyticsadmin' );
return $analyticsadmin
-> properties_dataStreams // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
-> create (
self :: normalize_property_id ( $property_id ),
$datastream
);
}
/**
2024-04-17 11:32:24 +02:00
* Outputs the user tracking opt - out script .
*
* This script opts out of all Google Analytics tracking , for all measurement IDs , regardless of implementation .
* E . g . via Tag Manager , etc .
*
* @ since 1.5 . 0
* @ since 1.121 . 0 Migrated from the Analytics ( UA ) class and adapted to only work for GA4 properties .
* @ link https :// developers . google . com / analytics / devguides / collection / analyticsjs / user - opt - out
*/
private function print_tracking_opt_out () {
$settings = $this -> get_settings () -> get ();
$account_id = $settings [ 'accountID' ];
$property_id = $settings [ 'propertyID' ];
if ( ! $this -> is_tracking_disabled () ) {
return ;
}
if ( $this -> context -> is_amp () ) : ?>
2025-04-25 12:30:07 +02:00
<!-- < ? php esc_html_e ( 'Google Analytics AMP opt-out snippet added by Site Kit' , 'google-site-kit' ); ?> -->
< meta name = " ga-opt-out " content = " " id = " __gaOptOutExtension " >
<!-- < ? php esc_html_e ( 'End Google Analytics AMP opt-out snippet added by Site Kit' , 'google-site-kit' ); ?> -->
< ? php else : ?>
<!-- < ? php esc_html_e ( 'Google Analytics opt-out snippet added by Site Kit' , 'google-site-kit' ); ?> -->
< ? php
2024-04-17 11:32:24 +02:00
// Opt-out should always use the measurement ID, even when using a GT tag.
$tag_id = $this -> get_measurement_id ();
2025-04-25 12:30:07 +02:00
if ( ! empty ( $tag_id ) ) {
BC_Functions :: wp_print_inline_script_tag ( sprintf ( 'window["ga-disable-%s"] = true;' , esc_attr ( $tag_id ) ) );
}
?>
< ? php do_action ( 'googlesitekit_analytics_tracking_opt_out' , $property_id , $account_id ); ?>
<!-- < ? php esc_html_e ( 'End Google Analytics opt-out snippet added by Site Kit' , 'google-site-kit' ); ?> -->
< ? php
2024-04-17 11:32:24 +02:00
endif ;
}
/**
* Checks whether or not tracking snippet should be contextually disabled for this request .
*
* @ since 1.1 . 0
* @ since 1.121 . 0 Migrated here from the Analytics ( UA ) class .
*
* @ return bool
*/
protected function is_tracking_disabled () {
$settings = $this -> get_settings () -> get ();
// This filter is documented in Tag_Manager::filter_analytics_allow_tracking_disabled.
if ( ! apply_filters ( 'googlesitekit_allow_tracking_disabled' , $settings [ 'useSnippet' ] ) ) {
return false ;
}
$disable_logged_in_users = in_array ( 'loggedinUsers' , $settings [ 'trackingDisabled' ], true ) && is_user_logged_in ();
$disable_content_creators = in_array ( 'contentCreators' , $settings [ 'trackingDisabled' ], true ) && current_user_can ( 'edit_posts' );
$disabled = $disable_logged_in_users || $disable_content_creators ;
/**
* Filters whether or not the Analytics tracking snippet is output for the current request .
*
* @ since 1.1 . 0
*
* @ param $disabled bool Whether to disable tracking or not .
*/
return ( bool ) apply_filters ( 'googlesitekit_analytics_tracking_disabled' , $disabled );
}
/**
* Handles the provisioning callback after the user completes the terms of service .
2022-12-15 17:34:08 +01:00
*
2024-04-17 11:32:24 +02:00
* @ since 1.9 . 0
* @ since 1.98 . 0 Extended to handle callback from Admin API ( no UA entities ) .
* @ since 1.121 . 0 Migrated method from original Analytics class to Analytics_4 class .
2022-12-15 17:34:08 +01:00
*/
2024-04-17 11:32:24 +02:00
protected function handle_provisioning_callback () {
if ( defined ( 'WP_CLI' ) && WP_CLI ) {
return ;
}
if ( ! current_user_can ( Permissions :: MANAGE_OPTIONS ) ) {
return ;
}
$input = $this -> context -> input ();
if ( ! $input -> filter ( INPUT_GET , 'gatoscallback' ) ) {
2022-12-15 17:34:08 +01:00
return ;
}
2024-04-17 11:32:24 +02:00
// First check that the accountTicketId matches one stored for the user.
// This is always provided, even in the event of an error.
$account_ticket_id = htmlspecialchars ( $input -> filter ( INPUT_GET , 'accountTicketId' ) );
// The create-account-ticket request stores the created account ticket in a transient before
// sending the user off to the terms of service page.
$account_ticket_transient_key = self :: PROVISION_ACCOUNT_TICKET_ID . '::' . get_current_user_id ();
$account_ticket_params = $this -> transients -> get ( $account_ticket_transient_key );
$account_ticket = new Account_Ticket ( $account_ticket_params );
// Backwards compat for previous storage type which stored ID only.
if ( is_scalar ( $account_ticket_params ) ) {
$account_ticket -> set_id ( $account_ticket_params );
}
if ( $account_ticket -> get_id () !== $account_ticket_id ) {
wp_safe_redirect (
$this -> context -> admin_url ( 'dashboard' , array ( 'error_code' => 'account_ticket_id_mismatch' ) )
);
exit ;
}
// At this point, the accountTicketId is a match and params are loaded, so we can safely delete the transient.
$this -> transients -> delete ( $account_ticket_transient_key );
// Next, check for a returned error.
$error = $input -> filter ( INPUT_GET , 'error' );
if ( ! empty ( $error ) ) {
wp_safe_redirect (
$this -> context -> admin_url ( 'dashboard' , array ( 'error_code' => htmlspecialchars ( $error ) ) )
);
exit ;
}
$account_id = htmlspecialchars ( $input -> filter ( INPUT_GET , 'accountId' ) );
if ( empty ( $account_id ) ) {
wp_safe_redirect (
$this -> context -> admin_url ( 'dashboard' , array ( 'error_code' => 'callback_missing_parameter' ) )
);
exit ;
}
$new_settings = array ();
// At this point, account creation was successful.
$new_settings [ 'accountID' ] = $account_id ;
$this -> get_settings () -> merge ( $new_settings );
$this -> provision_property_webdatastream ( $account_id , $account_ticket );
wp_safe_redirect (
$this -> context -> admin_url (
'dashboard' ,
array (
'notification' => 'authentication_success' ,
'slug' => 'analytics-4' ,
)
)
);
exit ;
2022-12-15 17:34:08 +01:00
}
/**
* Provisions new GA4 property and web data stream for provided account .
*
* @ since 1.35 . 0
2023-04-26 17:39:43 +02:00
* @ since 1.98 . 0 Added $account_ticket .
2022-12-15 17:34:08 +01:00
*
2023-04-26 17:39:43 +02:00
* @ param string $account_id Account ID .
* @ param Account_Ticket $account_ticket Account ticket instance .
2022-12-15 17:34:08 +01:00
*/
2024-04-17 11:32:24 +02:00
private function provision_property_webdatastream ( $account_id , $account_ticket ) {
2023-04-26 17:39:43 +02:00
// Reset the current GA4 settings.
$this -> get_settings () -> merge (
array (
'propertyID' => '' ,
'webDataStreamID' => '' ,
'measurementID' => '' ,
)
);
2022-12-15 17:34:08 +01:00
2023-04-26 17:39:43 +02:00
$property = $this -> create_property (
$account_id ,
array (
'displayName' => $account_ticket -> get_property_name (),
'timezone' => $account_ticket -> get_timezone (),
)
);
$property = self :: filter_property_with_ids ( $property );
2022-12-15 17:34:08 +01:00
2023-04-26 17:39:43 +02:00
if ( empty ( $property -> _id ) ) {
return ;
}
2022-12-15 17:34:08 +01:00
2024-02-16 11:03:01 +01:00
$create_time = isset ( $property -> createTime ) ? $property -> createTime : '' ; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$create_time_ms = 0 ;
if ( $create_time ) {
$create_time_ms = Synchronize_Property :: convert_time_to_unix_ms ( $create_time );
}
$this -> get_settings () -> merge (
array (
'propertyID' => $property -> _id ,
'propertyCreateTime' => $create_time_ms ,
)
);
2022-12-15 17:34:08 +01:00
2023-04-26 17:39:43 +02:00
$web_datastream = $this -> create_webdatastream (
$property -> _id ,
array (
'displayName' => $account_ticket -> get_data_stream_name (),
)
);
$web_datastream = self :: filter_webdatastream_with_ids ( $web_datastream );
2022-12-15 17:34:08 +01:00
2023-04-26 17:39:43 +02:00
if ( empty ( $web_datastream -> _id ) ) {
return ;
}
2022-12-15 17:34:08 +01:00
2023-04-26 17:39:43 +02:00
$measurement_id = $web_datastream -> webStreamData -> measurementId ; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$this -> get_settings () -> merge (
array (
'webDataStreamID' => $web_datastream -> _id ,
'measurementID' => $measurement_id ,
)
);
2024-02-16 11:03:01 +01:00
if ( $account_ticket -> get_enhanced_measurement_stream_enabled () ) {
2023-12-07 09:44:11 +01:00
$this -> set_data (
'enhanced-measurement-settings' ,
array (
'propertyID' => $property -> _id ,
'webDataStreamID' => $web_datastream -> _id ,
'enhancedMeasurementSettings' => array (
// We can hardcode this to `true` here due to the conditional invocation.
'streamEnabled' => true ,
),
)
);
}
2023-09-26 10:24:36 +02:00
$this -> sync_google_tag_settings ();
}
/**
* Syncs Google tag settings for the currently configured measurementID .
*
* @ since 1.102 . 0
*/
protected function sync_google_tag_settings () {
$settings = $this -> get_settings ();
$measurement_id = $settings -> get ()[ 'measurementID' ];
if ( ! $measurement_id ) {
return ;
}
$google_tag_settings = $this -> get_data ( 'google-tag-settings' , array ( 'measurementID' => $measurement_id ) );
if ( is_wp_error ( $google_tag_settings ) ) {
return ;
2022-12-15 17:34:08 +01:00
}
2023-09-26 10:24:36 +02:00
$settings -> merge ( $google_tag_settings );
2022-12-15 17:34:08 +01:00
}
/**
* Creates a request object for the given datapoint .
*
* @ since 1.30 . 0
*
* @ param Data_Request $data Data request object .
* @ return RequestInterface | callable | WP_Error Request object or callable on success , or WP_Error on failure .
*
* @ throws Invalid_Datapoint_Exception Thrown if the datapoint does not exist .
2024-04-17 11:32:24 +02:00
* @ throws Invalid_Param_Exception Thrown if a parameter is invalid .
2023-04-26 17:39:43 +02:00
* @ throws Missing_Required_Param_Exception Thrown if a required parameter is missing or empty .
2025-02-28 08:42:11 +01:00
*
2023-04-26 17:39:43 +02:00
* phpcs : ignore Squiz . Commenting . FunctionCommentThrowTag . WrongNumber
2022-12-15 17:34:08 +01:00
*/
protected function create_data_request ( Data_Request $data ) {
switch ( " { $data -> method } : { $data -> datapoint } " ) {
case 'GET:accounts' :
return $this -> get_service ( 'analyticsadmin' ) -> accounts -> listAccounts ();
case 'GET:account-summaries' :
2025-02-28 08:42:11 +01:00
return $this -> get_service ( 'analyticsadmin' ) -> accountSummaries -> listAccountSummaries (
array (
'pageSize' => 200 ,
'pageToken' => $data [ 'pageToken' ],
)
);
2024-04-17 11:32:24 +02:00
case 'GET:ads-links' :
if ( empty ( $data [ 'propertyID' ] ) ) {
throw new Missing_Required_Param_Exception ( 'propertyID' );
}
$parent = self :: normalize_property_id ( $data [ 'propertyID' ] );
return $this -> get_service ( 'analyticsadmin' ) -> properties_googleAdsLinks -> listPropertiesGoogleAdsLinks ( $parent );
2024-02-16 11:03:01 +01:00
case 'GET:adsense-links' :
if ( empty ( $data [ 'propertyID' ] ) ) {
throw new Missing_Required_Param_Exception ( 'propertyID' );
}
$parent = self :: normalize_property_id ( $data [ 'propertyID' ] );
return $this -> get_analyticsadsenselinks_service () -> properties_adSenseLinks -> listPropertiesAdSenseLinks ( $parent );
case 'POST:create-audience' :
$settings = $this -> get_settings () -> get ();
if ( ! isset ( $settings [ 'propertyID' ] ) ) {
return new WP_Error (
'missing_required_setting' ,
2024-04-17 11:32:24 +02:00
__ ( 'No connected Google Analytics property ID.' , 'google-site-kit' ),
2024-02-16 11:03:01 +01:00
array ( 'status' => 500 )
);
}
if ( ! isset ( $data [ 'audience' ] ) ) {
throw new Missing_Required_Param_Exception ( 'audience' );
}
$property_id = $settings [ 'propertyID' ];
$audience = $data [ 'audience' ];
$fields = array (
'displayName' ,
'description' ,
'membershipDurationDays' ,
'eventTrigger' ,
'exclusionDurationMode' ,
'filterClauses' ,
);
$invalid_keys = array_diff ( array_keys ( $audience ), $fields );
if ( ! empty ( $invalid_keys ) ) {
return new WP_Error (
'invalid_property_name' ,
/* translators: %s: Invalid property names */
sprintf ( __ ( 'Invalid properties in audience: %s.' , 'google-site-kit' ), implode ( ', ' , $invalid_keys ) ),
array ( 'status' => 400 )
);
}
$property_id = self :: normalize_property_id ( $property_id );
$post_body = new GoogleAnalyticsAdminV1alphaAudience ( $audience );
$analyticsadmin = $this -> get_analyticsaudiences_service ();
return $analyticsadmin
-> properties_audiences
-> create (
$property_id ,
$post_body
);
2023-04-26 17:39:43 +02:00
case 'POST:create-account-ticket' :
if ( empty ( $data [ 'displayName' ] ) ) {
throw new Missing_Required_Param_Exception ( 'displayName' );
}
if ( empty ( $data [ 'regionCode' ] ) ) {
throw new Missing_Required_Param_Exception ( 'regionCode' );
}
if ( empty ( $data [ 'propertyName' ] ) ) {
throw new Missing_Required_Param_Exception ( 'propertyName' );
}
if ( empty ( $data [ 'dataStreamName' ] ) ) {
throw new Missing_Required_Param_Exception ( 'dataStreamName' );
}
if ( empty ( $data [ 'timezone' ] ) ) {
throw new Missing_Required_Param_Exception ( 'timezone' );
}
$account = new GoogleAnalyticsAdminV1betaAccount ();
$account -> setDisplayName ( $data [ 'displayName' ] );
$account -> setRegionCode ( $data [ 'regionCode' ] );
$credentials = $this -> authentication -> credentials () -> get ();
$account_ticket_request = new Proxy_GoogleAnalyticsAdminProvisionAccountTicketRequest ();
$account_ticket_request -> setSiteId ( $credentials [ 'oauth2_client_id' ] );
$account_ticket_request -> setSiteSecret ( $credentials [ 'oauth2_client_secret' ] );
$account_ticket_request -> setRedirectUri ( $this -> get_provisioning_redirect_uri () );
$account_ticket_request -> setAccount ( $account );
return $this -> get_service ( 'analyticsprovisioning' )
-> accounts -> provisionAccountTicket ( $account_ticket_request );
2022-12-15 17:34:08 +01:00
case 'POST:create-property' :
if ( ! isset ( $data [ 'accountID' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'accountID' ),
array ( 'status' => 400 )
);
}
2023-04-26 17:39:43 +02:00
$options = array (
'displayName' => $data [ 'displayName' ],
'timezone' => $data [ 'timezone' ],
);
return $this -> create_property ( $data [ 'accountID' ], $options );
2022-12-15 17:34:08 +01:00
case 'POST:create-webdatastream' :
if ( ! isset ( $data [ 'propertyID' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'propertyID' ),
array ( 'status' => 400 )
);
}
2023-04-26 17:39:43 +02:00
$options = array (
'displayName' => $data [ 'displayName' ],
);
return $this -> create_webdatastream ( $data [ 'propertyID' ], $options );
2022-12-15 17:34:08 +01:00
case 'GET:properties' :
if ( ! isset ( $data [ 'accountID' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'accountID' ),
array ( 'status' => 400 )
);
}
return $this -> get_service ( 'analyticsadmin' ) -> properties -> listProperties (
array (
2023-12-07 09:44:11 +01:00
'filter' => 'parent:' . self :: normalize_account_id ( $data [ 'accountID' ] ),
'pageSize' => 200 ,
2022-12-15 17:34:08 +01:00
)
);
case 'GET:property' :
if ( ! isset ( $data [ 'propertyID' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'propertyID' ),
array ( 'status' => 400 )
);
}
return $this -> get_service ( 'analyticsadmin' ) -> properties -> get ( self :: normalize_property_id ( $data [ 'propertyID' ] ) );
2023-04-26 17:39:43 +02:00
case 'GET:report' :
2025-08-27 08:44:30 +02:00
case 'GET:non-shareable-report' :
2023-04-26 17:39:43 +02:00
if ( empty ( $data [ 'metrics' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'metrics' ),
array ( 'status' => 400 )
);
}
$settings = $this -> get_settings () -> get ();
if ( empty ( $settings [ 'propertyID' ] ) ) {
return new WP_Error (
'missing_required_setting' ,
2024-04-17 11:32:24 +02:00
__ ( 'No connected Google Analytics property ID.' , 'google-site-kit' ),
2023-04-26 17:39:43 +02:00
array ( 'status' => 500 )
);
}
$report = new Analytics_4_Report_Request ( $this -> context );
$request = $report -> create_request ( $data , $this -> is_shared_data_request ( $data ) );
if ( is_wp_error ( $request ) ) {
return $request ;
}
$property_id = self :: normalize_property_id ( $settings [ 'propertyID' ] );
$request -> setProperty ( $property_id );
return $this -> get_analyticsdata_service () -> properties -> runReport ( $property_id , $request );
2025-02-28 08:42:11 +01:00
case 'GET:pivot-report' :
if ( empty ( $data [ 'metrics' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'metrics' ),
array ( 'status' => 400 )
);
}
if ( empty ( $data [ 'pivots' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'pivots' ),
array ( 'status' => 400 )
);
}
$settings = $this -> get_settings () -> get ();
if ( empty ( $settings [ 'propertyID' ] ) ) {
return new WP_Error (
'missing_required_setting' ,
__ ( 'No connected Google Analytics property ID.' , 'google-site-kit' ),
array ( 'status' => 500 )
);
}
$report = new Analytics_4_PivotReport_Request ( $this -> context );
$request = $report -> create_request ( $data , $this -> is_shared_data_request ( $data ) );
if ( is_wp_error ( $request ) ) {
return $request ;
}
$property_id = self :: normalize_property_id ( $settings [ 'propertyID' ] );
$request -> setProperty ( $property_id );
return $this -> get_analyticsdata_service () -> properties -> runPivotReport ( $property_id , $request );
2023-09-26 10:24:36 +02:00
case 'GET:enhanced-measurement-settings' :
if ( ! isset ( $data [ 'propertyID' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'propertyID' ),
array ( 'status' => 400 )
);
}
if ( ! isset ( $data [ 'webDataStreamID' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'webDataStreamID' ),
array ( 'status' => 400 )
);
}
$name = self :: normalize_property_id (
$data [ 'propertyID' ]
) . '/dataStreams/' . $data [ 'webDataStreamID' ] . '/enhancedMeasurementSettings' ;
$analyticsadmin = $this -> get_analyticsenhancedmeasurements_service ();
return $analyticsadmin
-> properties_enhancedMeasurements // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
-> getEnhancedMeasurementSettings ( $name );
case 'POST:enhanced-measurement-settings' :
if ( ! isset ( $data [ 'propertyID' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'propertyID' ),
array ( 'status' => 400 )
);
}
if ( ! isset ( $data [ 'webDataStreamID' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'webDataStreamID' ),
array ( 'status' => 400 )
);
}
if ( ! isset ( $data [ 'enhancedMeasurementSettings' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'enhancedMeasurementSettings' ),
array ( 'status' => 400 )
);
}
$enhanced_measurement_settings = $data [ 'enhancedMeasurementSettings' ];
$fields = array (
'name' ,
'streamEnabled' ,
'scrollsEnabled' ,
'outboundClicksEnabled' ,
'siteSearchEnabled' ,
'videoEngagementEnabled' ,
'fileDownloadsEnabled' ,
'pageChangesEnabled' ,
'formInteractionsEnabled' ,
'searchQueryParameter' ,
'uriQueryParameter' ,
);
$invalid_keys = array_diff ( array_keys ( $enhanced_measurement_settings ), $fields );
if ( ! empty ( $invalid_keys ) ) {
return new WP_Error (
'invalid_property_name' ,
/* translators: %s: Invalid property names */
sprintf ( __ ( 'Invalid properties in enhancedMeasurementSettings: %s.' , 'google-site-kit' ), implode ( ', ' , $invalid_keys ) ),
array ( 'status' => 400 )
);
}
$name = self :: normalize_property_id (
$data [ 'propertyID' ]
) . '/dataStreams/' . $data [ 'webDataStreamID' ] . '/enhancedMeasurementSettings' ;
$post_body = new EnhancedMeasurementSettingsModel ( $data [ 'enhancedMeasurementSettings' ] );
$analyticsadmin = $this -> get_analyticsenhancedmeasurements_service ();
return $analyticsadmin
-> properties_enhancedMeasurements // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
-> updateEnhancedMeasurementSettings (
$name ,
$post_body ,
array (
'updateMask' => 'streamEnabled' , // Only allow updating the streamEnabled field for now.
)
);
2023-12-07 09:44:11 +01:00
case 'POST:create-custom-dimension' :
if ( ! isset ( $data [ 'propertyID' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'propertyID' ),
array ( 'status' => 400 )
);
}
if ( ! isset ( $data [ 'customDimension' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'customDimension' ),
array ( 'status' => 400 )
);
}
$custom_dimension_data = $data [ 'customDimension' ];
$fields = array (
'parameterName' ,
'displayName' ,
'description' ,
'scope' ,
'disallowAdsPersonalization' ,
);
$invalid_keys = array_diff ( array_keys ( $custom_dimension_data ), $fields );
if ( ! empty ( $invalid_keys ) ) {
return new WP_Error (
'invalid_property_name' ,
/* translators: %s: Invalid property names */
sprintf ( __ ( 'Invalid properties in customDimension: %s.' , 'google-site-kit' ), implode ( ', ' , $invalid_keys ) ),
array ( 'status' => 400 )
);
}
// Define the valid `DimensionScope` enum values.
$valid_scopes = array ( 'EVENT' , 'USER' , 'ITEM' );
// If the scope field is not set, default to `EVENT`.
// Otherwise, validate against the enum values.
if ( ! isset ( $custom_dimension_data [ 'scope' ] ) ) {
$custom_dimension_data [ 'scope' ] = 'EVENT' ;
} elseif ( ! in_array ( $custom_dimension_data [ 'scope' ], $valid_scopes , true ) ) {
return new WP_Error (
'invalid_scope' ,
/* translators: %s: Invalid scope */
sprintf ( __ ( 'Invalid scope: %s.' , 'google-site-kit' ), $custom_dimension_data [ 'scope' ] ),
array ( 'status' => 400 )
);
}
$custom_dimension = new GoogleAnalyticsAdminV1betaCustomDimension ();
$custom_dimension -> setParameterName ( $custom_dimension_data [ 'parameterName' ] );
$custom_dimension -> setDisplayName ( $custom_dimension_data [ 'displayName' ] );
$custom_dimension -> setScope ( $custom_dimension_data [ 'scope' ] );
2025-02-28 08:42:11 +01:00
if ( isset ( $custom_dimension_data [ 'description' ] ) ) {
$custom_dimension -> setDescription ( $custom_dimension_data [ 'description' ] );
}
if ( isset ( $custom_dimension_data [ 'disallowAdsPersonalization' ] ) ) {
$custom_dimension -> setDisallowAdsPersonalization ( $custom_dimension_data [ 'disallowAdsPersonalization' ] );
}
2023-12-07 09:44:11 +01:00
$analyticsadmin = $this -> get_service ( 'analyticsadmin' );
return $analyticsadmin
-> properties_customDimensions // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
-> create (
self :: normalize_property_id ( $data [ 'propertyID' ] ),
$custom_dimension
);
2025-04-25 12:30:07 +02:00
case 'GET:audience-settings' :
return function () {
$settings = $this -> audience_settings -> get ();
return current_user_can ( Permissions :: MANAGE_OPTIONS ) ? $settings : array_intersect_key ( $settings , array_flip ( $this -> audience_settings -> get_view_only_keys () ) );
};
case 'POST:save-audience-settings' :
if ( ! current_user_can ( Permissions :: MANAGE_OPTIONS ) ) {
return new WP_Error (
'forbidden' ,
__ ( 'User does not have permission to save audience settings.' , 'google-site-kit' ),
array ( 'status' => 403 )
);
}
$settings = $data [ 'settings' ];
if (
isset ( $settings [ 'audienceSegmentationSetupCompletedBy' ] ) &&
! is_int ( $settings [ 'audienceSegmentationSetupCompletedBy' ] )
) {
throw new Invalid_Param_Exception ( 'audienceSegmentationSetupCompletedBy' );
}
return function () use ( $settings ) {
$new_settings = array ();
if ( isset ( $settings [ 'audienceSegmentationSetupCompletedBy' ] ) ) {
$new_settings [ 'audienceSegmentationSetupCompletedBy' ] = $settings [ 'audienceSegmentationSetupCompletedBy' ];
}
$settings = $this -> audience_settings -> merge ( $new_settings );
return $settings ;
};
2025-02-28 08:42:11 +01:00
case 'POST:sync-audiences' :
if ( ! $this -> authentication -> is_authenticated () ) {
return new WP_Error (
'forbidden' ,
__ ( 'User must be authenticated to sync audiences.' , 'google-site-kit' ),
array ( 'status' => 403 )
);
}
$settings = $this -> get_settings () -> get ();
if ( empty ( $settings [ 'propertyID' ] ) ) {
return new WP_Error (
'missing_required_setting' ,
__ ( 'No connected Google Analytics property ID.' , 'google-site-kit' ),
array ( 'status' => 500 )
);
}
$analyticsadmin = $this -> get_analyticsaudiences_service ();
$property_id = self :: normalize_property_id ( $settings [ 'propertyID' ] );
return $analyticsadmin
-> properties_audiences
-> listPropertiesAudiences ( $property_id );
2023-12-07 09:44:11 +01:00
case 'POST:sync-custom-dimensions' :
$settings = $this -> get_settings () -> get ();
if ( empty ( $settings [ 'propertyID' ] ) ) {
return new WP_Error (
'missing_required_setting' ,
2024-04-17 11:32:24 +02:00
__ ( 'No connected Google Analytics property ID.' , 'google-site-kit' ),
2023-12-07 09:44:11 +01:00
array ( 'status' => 500 )
);
}
$analyticsadmin = $this -> get_service ( 'analyticsadmin' );
return $analyticsadmin
-> properties_customDimensions // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
-> listPropertiesCustomDimensions ( self :: normalize_property_id ( $settings [ 'propertyID' ] ) );
case 'POST:custom-dimension-data-available' :
if ( ! isset ( $data [ 'customDimension' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'customDimension' ),
array ( 'status' => 400 )
);
}
if ( ! $this -> custom_dimensions_data_available -> is_valid_custom_dimension ( $data [ 'customDimension' ] ) ) {
return new WP_Error (
'invalid_custom_dimension_slug' ,
/* translators: %s: Invalid custom dimension slug */
sprintf ( __ ( 'Invalid custom dimension slug: %s.' , 'google-site-kit' ), $data [ 'customDimension' ] ),
array ( 'status' => 400 )
);
}
2025-02-28 08:42:11 +01:00
return function () use ( $data ) {
2023-12-07 09:44:11 +01:00
return $this -> custom_dimensions_data_available -> set_data_available ( $data [ 'customDimension' ] );
};
2025-02-28 08:42:11 +01:00
case 'POST:save-resource-data-availability-date' :
if ( ! isset ( $data [ 'resourceType' ] ) ) {
throw new Missing_Required_Param_Exception ( 'resourceType' );
}
if ( ! isset ( $data [ 'resourceSlug' ] ) ) {
throw new Missing_Required_Param_Exception ( 'resourceSlug' );
}
if ( ! isset ( $data [ 'date' ] ) ) {
throw new Missing_Required_Param_Exception ( 'date' );
}
if ( ! $this -> resource_data_availability_date -> is_valid_resource_type ( $data [ 'resourceType' ] ) ) {
throw new Invalid_Param_Exception ( 'resourceType' );
}
if ( ! $this -> resource_data_availability_date -> is_valid_resource_slug ( $data [ 'resourceSlug' ], $data [ 'resourceType' ] ) ) {
throw new Invalid_Param_Exception ( 'resourceSlug' );
}
if ( ! is_int ( $data [ 'date' ] ) ) {
throw new Invalid_Param_Exception ( 'date' );
}
return function () use ( $data ) {
return $this -> resource_data_availability_date -> set_resource_date ( $data [ 'resourceSlug' ], $data [ 'resourceType' ], $data [ 'date' ] );
};
2022-12-15 17:34:08 +01:00
case 'GET:webdatastreams' :
if ( ! isset ( $data [ 'propertyID' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'propertyID' ),
array ( 'status' => 400 )
);
}
$analyticsadmin = $this -> get_service ( 'analyticsadmin' );
return $analyticsadmin
-> properties_dataStreams // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
-> listPropertiesDataStreams (
self :: normalize_property_id ( $data [ 'propertyID' ] )
);
case 'GET:webdatastreams-batch' :
if ( ! isset ( $data [ 'propertyIDs' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'propertyIDs' ),
array ( 'status' => 400 )
);
}
if ( ! is_array ( $data [ 'propertyIDs' ] ) || count ( $data [ 'propertyIDs' ] ) > 10 ) {
return new WP_Error (
'rest_invalid_param' ,
/* translators: %s: List of invalid parameters. */
sprintf ( __ ( 'Invalid parameter(s): %s' , 'google-site-kit' ), 'propertyIDs' ),
array ( 'status' => 400 )
);
}
$analyticsadmin = $this -> get_service ( 'analyticsadmin' );
$batch_request = $analyticsadmin -> createBatch ();
foreach ( $data [ 'propertyIDs' ] as $property_id ) {
$batch_request -> add (
$analyticsadmin
-> properties_dataStreams // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
-> listPropertiesDataStreams (
self :: normalize_property_id ( $property_id )
)
);
}
2025-02-28 08:42:11 +01:00
return function () use ( $batch_request ) {
2022-12-15 17:34:08 +01:00
return $batch_request -> execute ();
};
2023-01-25 20:43:46 +01:00
case 'GET:container-lookup' :
if ( ! isset ( $data [ 'destinationID' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'destinationID' ),
array ( 'status' => 400 )
);
}
return $this -> get_tagmanager_service () -> accounts_containers -> lookup ( array ( 'destinationId' => $data [ 'destinationID' ] ) );
case 'GET:container-destinations' :
if ( ! isset ( $data [ 'accountID' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'accountID' ),
array ( 'status' => 400 )
);
}
2023-04-26 17:39:43 +02:00
if ( ! isset ( $data [ 'containerID' ] ) ) {
2023-01-25 20:43:46 +01:00
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
2023-04-26 17:39:43 +02:00
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'containerID' ),
2023-01-25 20:43:46 +01:00
array ( 'status' => 400 )
);
}
return $this -> get_tagmanager_service () -> accounts_containers_destinations -> listAccountsContainersDestinations (
2023-04-26 17:39:43 +02:00
" accounts/ { $data [ 'accountID' ] } /containers/ { $data [ 'containerID' ] } "
2023-01-25 20:43:46 +01:00
);
2023-04-26 17:39:43 +02:00
case 'GET:google-tag-settings' :
if ( ! isset ( $data [ 'measurementID' ] ) ) {
return new WP_Error (
'missing_required_param' ,
/* translators: %s: Missing parameter name */
sprintf ( __ ( 'Request parameter is empty: %s.' , 'google-site-kit' ), 'measurementID' ),
array ( 'status' => 400 )
);
}
return $this -> get_tagmanager_service () -> accounts_containers -> lookup ( array ( 'destinationId' => $data [ 'measurementID' ] ) );
2025-07-27 19:58:08 +02:00
case 'GET:key-events' :
2023-04-26 17:39:43 +02:00
$settings = $this -> get_settings () -> get ();
if ( empty ( $settings [ 'propertyID' ] ) ) {
return new WP_Error (
'missing_required_setting' ,
2024-04-17 11:32:24 +02:00
__ ( 'No connected Google Analytics property ID.' , 'google-site-kit' ),
2023-04-26 17:39:43 +02:00
array ( 'status' => 500 )
);
}
$analyticsadmin = $this -> get_service ( 'analyticsadmin' );
$property_id = self :: normalize_property_id ( $settings [ 'propertyID' ] );
return $analyticsadmin
2025-08-27 08:44:30 +02:00
-> properties_keyEvents // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
-> listPropertiesKeyEvents ( $property_id );
2025-02-28 08:42:11 +01:00
case 'POST:set-google-tag-id-mismatch' :
if ( ! isset ( $data [ 'hasMismatchedTag' ] ) ) {
throw new Missing_Required_Param_Exception ( 'hasMismatchedTag' );
}
if ( false === $data [ 'hasMismatchedTag' ] ) {
return function () {
2025-08-27 08:44:30 +02:00
$this -> transients -> delete ( 'googlesitekit_inline_tag_id_mismatch' );
return false ;
2025-02-28 08:42:11 +01:00
};
}
return function () use ( $data ) {
2025-08-27 08:44:30 +02:00
$this -> transients -> set ( 'googlesitekit_inline_tag_id_mismatch' , $data [ 'hasMismatchedTag' ] );
return $data [ 'hasMismatchedTag' ];
};
case 'POST:set-is-web-data-stream-unavailable' :
if ( ! isset ( $data [ 'isWebDataStreamUnavailable' ] ) ) {
throw new Missing_Required_Param_Exception ( 'isWebDataStreamUnavailable' );
}
if ( true === $data [ 'isWebDataStreamUnavailable' ] ) {
return function () {
$settings = $this -> get_settings () -> get ();
$transient_key = 'googlesitekit_web_data_stream_unavailable_' . $settings [ 'webDataStreamID' ];
$this -> transients -> set ( $transient_key , true );
return true ;
};
}
return function () {
$settings = $this -> get_settings () -> get ();
$transient_key = 'googlesitekit_web_data_stream_unavailable_' . $settings [ 'webDataStreamID' ];
$this -> transients -> delete ( $transient_key );
return false ;
2025-02-28 08:42:11 +01:00
};
2022-12-15 17:34:08 +01:00
}
return parent :: create_data_request ( $data );
}
/**
* Parses a response for the given datapoint .
*
* @ since 1.30 . 0
*
* @ param Data_Request $data Data request object .
* @ param mixed $response Request response .
*
* @ return mixed Parsed response data on success , or WP_Error on failure .
*/
protected function parse_data_response ( Data_Request $data , $response ) {
switch ( " { $data -> method } : { $data -> datapoint } " ) {
case 'GET:accounts' :
return array_map ( array ( self :: class , 'filter_account_with_ids' ), $response -> getAccounts () );
2024-04-17 11:32:24 +02:00
case 'GET:ads-links' :
return ( array ) $response -> getGoogleAdsLinks ();
2024-02-16 11:03:01 +01:00
case 'GET:adsense-links' :
return ( array ) $response -> getAdsenseLinks ();
2023-04-26 17:39:43 +02:00
case 'POST:create-account-ticket' :
$account_ticket = new Account_Ticket ();
$account_ticket -> set_id ( $response -> getAccountTicketId () );
// Required in create_data_request.
$account_ticket -> set_property_name ( $data [ 'propertyName' ] );
$account_ticket -> set_data_stream_name ( $data [ 'dataStreamName' ] );
$account_ticket -> set_timezone ( $data [ 'timezone' ] );
2023-12-07 09:44:11 +01:00
$account_ticket -> set_enhanced_measurement_stream_enabled ( ! empty ( $data [ 'enhancedMeasurementStreamEnabled' ] ) );
2023-04-26 17:39:43 +02:00
// Cache the create ticket id long enough to verify it upon completion of the terms of service.
set_transient (
2024-04-17 11:32:24 +02:00
self :: PROVISION_ACCOUNT_TICKET_ID . '::' . get_current_user_id (),
2023-04-26 17:39:43 +02:00
$account_ticket -> to_array (),
15 * MINUTE_IN_SECONDS
);
return $response ;
2022-12-15 17:34:08 +01:00
case 'POST:create-property' :
return self :: filter_property_with_ids ( $response );
case 'POST:create-webdatastream' :
return self :: filter_webdatastream_with_ids ( $response );
case 'GET:properties' :
2023-01-25 20:43:46 +01:00
return Sort :: case_insensitive_list_sort (
array_map ( array ( self :: class , 'filter_property_with_ids' ), $response -> getProperties () ),
'displayName'
);
2022-12-15 17:34:08 +01:00
case 'GET:property' :
return self :: filter_property_with_ids ( $response );
case 'GET:webdatastreams' :
2023-01-25 20:43:46 +01:00
/* @var GoogleAnalyticsAdminV1betaListDataStreamsResponse $response phpcs:ignore Squiz.PHP.CommentedOutCode.Found */
2022-12-15 17:34:08 +01:00
$webdatastreams = self :: filter_web_datastreams ( $response -> getDataStreams () );
return array_map ( array ( self :: class , 'filter_webdatastream_with_ids' ), $webdatastreams );
case 'GET:webdatastreams-batch' :
return self :: parse_webdatastreams_batch ( $response );
2023-01-25 20:43:46 +01:00
case 'GET:container-destinations' :
return ( array ) $response -> getDestination ();
2023-04-26 17:39:43 +02:00
case 'GET:google-tag-settings' :
return $this -> get_google_tag_settings_for_measurement_id ( $response , $data [ 'measurementID' ] );
2025-07-27 19:58:08 +02:00
case 'GET:key-events' :
return ( array ) $response -> getKeyEvents ();
2023-04-26 17:39:43 +02:00
case 'GET:report' :
2025-08-27 08:44:30 +02:00
case 'GET:non-shareable-report' :
2025-02-28 08:42:11 +01:00
case 'GET:pivot-report' :
$report = new Analytics_4_Report_Response ( $this -> context );
return $report -> parse_response ( $data , $response );
case 'POST:sync-audiences' :
$audiences = $this -> set_available_audiences ( $response -> getAudiences () );
return $audiences ;
2023-12-07 09:44:11 +01:00
case 'POST:sync-custom-dimensions' :
if ( is_wp_error ( $response ) ) {
return $response ;
}
$custom_dimensions = wp_list_pluck ( $response -> getCustomDimensions (), 'parameterName' );
$matching_dimensions = array_values (
array_filter (
$custom_dimensions ,
2025-02-28 08:42:11 +01:00
function ( $dimension ) {
2023-12-07 09:44:11 +01:00
return strpos ( $dimension , 'googlesitekit_' ) === 0 ;
}
)
);
$this -> get_settings () -> merge (
array (
'availableCustomDimensions' => $matching_dimensions ,
)
);
// Reset the data available state for custom dimensions that are no longer available.
$missing_custom_dimensions_with_data_available = array_diff (
array_keys (
// Only compare against custom dimensions that have data available.
array_filter (
$this -> custom_dimensions_data_available -> get_data_availability ()
)
),
$matching_dimensions
);
if ( count ( $missing_custom_dimensions_with_data_available ) > 0 ) {
$this -> custom_dimensions_data_available -> reset_data_available (
$missing_custom_dimensions_with_data_available
);
}
return $matching_dimensions ;
2022-12-15 17:34:08 +01:00
}
return parent :: parse_data_response ( $data , $response );
}
2023-01-25 20:43:46 +01:00
/**
* Gets the configured TagManager service instance .
*
* @ since 1.92 . 0
*
* @ return Google_Service_TagManager instance .
* @ throws Exception Thrown if the module did not correctly set up the service .
*/
private function get_tagmanager_service () {
return $this -> get_service ( 'tagmanager' );
}
2022-12-15 17:34:08 +01:00
/**
* Sets up information about the module .
*
* @ since 1.30 . 0
2024-04-17 11:32:24 +02:00
* @ since 1.123 . 0 Updated to include in the module setup .
2022-12-15 17:34:08 +01:00
*
* @ return array Associative array of module info .
*/
protected function setup_info () {
return array (
'slug' => self :: MODULE_SLUG ,
2024-04-17 11:32:24 +02:00
'name' => _x ( 'Analytics' , 'Service name' , 'google-site-kit' ),
2022-12-15 17:34:08 +01:00
'description' => __ ( 'Get a deeper understanding of your customers. Google Analytics gives you the free tools you need to analyze data for your business in one place.' , 'google-site-kit' ),
'homepage' => __ ( 'https://analytics.google.com/analytics/web' , 'google-site-kit' ),
);
}
2023-04-26 17:39:43 +02:00
/**
* Gets the configured Analytics Data service object instance .
*
* @ since 1.93 . 0
*
* @ return Google_Service_AnalyticsData The Analytics Data API service .
*/
protected function get_analyticsdata_service () {
return $this -> get_service ( 'analyticsdata' );
}
2023-09-26 10:24:36 +02:00
/**
* Gets the configured Analytics Data service object instance .
*
* @ since 1.110 . 0
*
* @ return PropertiesEnhancedMeasurementService The Analytics Admin API service .
*/
protected function get_analyticsenhancedmeasurements_service () {
return $this -> get_service ( 'analyticsenhancedmeasurement' );
}
2024-02-16 11:03:01 +01:00
/**
* Gets the configured Analytics Admin service object instance that includes `adSenseLinks` related methods .
*
* @ since 1.120 . 0
*
* @ return PropertiesAdSenseLinksService The Analytics Admin API service .
*/
protected function get_analyticsadsenselinks_service () {
return $this -> get_service ( 'analyticsadsenselinks' );
}
/**
* Gets the configured Analytics Data service object instance .
*
* @ since 1.120 . 0
*
* @ return PropertiesAudiencesService The Analytics Admin API service .
*/
protected function get_analyticsaudiences_service () {
return $this -> get_service ( 'analyticsaudiences' );
}
2022-12-15 17:34:08 +01:00
/**
* Sets up the Google services the module should use .
*
* This method is invoked once by { @ see Module :: get_service ()} to lazily set up the services when one is requested
* for the first time .
*
* @ since 1.30 . 0
*
* @ param Google_Site_Kit_Client $client Google client instance .
* @ return array Google services as $identifier => $service_instance pairs . Every $service_instance must be an
* instance of Google_Service .
*/
protected function setup_services ( Google_Site_Kit_Client $client ) {
2023-04-26 17:39:43 +02:00
$google_proxy = $this -> authentication -> get_google_proxy ();
2022-12-15 17:34:08 +01:00
return array (
2023-09-26 10:24:36 +02:00
'analyticsadmin' => new Google_Service_GoogleAnalyticsAdmin ( $client ),
'analyticsdata' => new Google_Service_AnalyticsData ( $client ),
'analyticsprovisioning' => new AccountProvisioningService ( $client , $google_proxy -> url () ),
'analyticsenhancedmeasurement' => new PropertiesEnhancedMeasurementService ( $client ),
2024-02-16 11:03:01 +01:00
'analyticsaudiences' => new PropertiesAudiencesService ( $client ),
'analyticsadsenselinks' => new PropertiesAdSenseLinksService ( $client ),
2023-09-26 10:24:36 +02:00
'tagmanager' => new Google_Service_TagManager ( $client ),
2022-12-15 17:34:08 +01:00
);
}
/**
* Sets up the module ' s settings instance .
*
* @ since 1.30 . 0
*
* @ return Module_Settings
*/
protected function setup_settings () {
return new Settings ( $this -> options );
}
/**
* Sets up the module ' s assets to register .
*
* @ since 1.31 . 0
*
* @ return Asset [] List of Asset objects .
*/
protected function setup_assets () {
$base_url = $this -> context -> url ( 'dist/assets/' );
return array (
new Script (
'googlesitekit-modules-analytics-4' ,
array (
'src' => $base_url . 'js/googlesitekit-modules-analytics-4.js' ,
'dependencies' => array (
'googlesitekit-vendor' ,
'googlesitekit-api' ,
'googlesitekit-data' ,
'googlesitekit-modules' ,
2025-06-09 09:58:01 +02:00
'googlesitekit-notifications' ,
2022-12-15 17:34:08 +01:00
'googlesitekit-datastore-site' ,
2023-09-26 10:24:36 +02:00
'googlesitekit-datastore-user' ,
2022-12-15 17:34:08 +01:00
'googlesitekit-datastore-forms' ,
'googlesitekit-components' ,
2023-04-26 17:39:43 +02:00
'googlesitekit-modules-data' ,
2022-12-15 17:34:08 +01:00
),
)
),
);
}
2023-04-26 17:39:43 +02:00
/**
* Gets the provisioning redirect URI that listens for the Terms of Service redirect .
*
* @ since 1.98 . 0
*
* @ return string Provisioning redirect URI .
*/
private function get_provisioning_redirect_uri () {
return $this -> authentication -> get_google_proxy ()
-> get_site_fields ()[ 'analytics_redirect_uri' ];
}
2022-12-15 17:34:08 +01:00
/**
* Registers the Analytics 4 tag .
*
* @ since 1.31 . 0
2023-09-26 10:24:36 +02:00
* @ since 1.104 . 0 Added support for AMP tag .
2024-02-16 11:03:01 +01:00
* @ since 1.119 . 0 Made method public .
2022-12-15 17:34:08 +01:00
*/
2024-02-16 11:03:01 +01:00
public function register_tag () {
2023-12-07 09:44:11 +01:00
$tag = $this -> context -> is_amp ()
? new AMP_Tag ( $this -> get_measurement_id (), self :: MODULE_SLUG ) // AMP currently only works with the measurement ID.
: new Web_Tag ( $this -> get_tag_id (), self :: MODULE_SLUG );
2022-12-15 17:34:08 +01:00
if ( $tag -> is_tag_blocked () ) {
return ;
}
$tag -> use_guard ( new Tag_Verify_Guard ( $this -> context -> input () ) );
$tag -> use_guard ( new Tag_Guard ( $this -> get_settings () ) );
$tag -> use_guard ( new Tag_Environment_Type_Guard () );
2023-12-07 09:44:11 +01:00
if ( ! $tag -> can_register () ) {
return ;
}
$home_domain = URL :: parse ( $this -> context -> get_canonical_home_url (), PHP_URL_HOST );
$tag -> set_home_domain ( $home_domain );
2024-02-16 11:03:01 +01:00
$custom_dimensions_data = $this -> get_custom_dimensions_data ();
if ( ! empty ( $custom_dimensions_data ) && $tag instanceof Tag_Interface ) {
$tag -> set_custom_dimensions ( $custom_dimensions_data );
2023-12-07 09:44:11 +01:00
}
$tag -> register ();
}
2024-02-16 11:03:01 +01:00
/**
* Returns the Module_Tag_Matchers instance .
*
* @ since 1.119 . 0
*
* @ return Module_Tag_Matchers Module_Tag_Matchers instance .
*/
public function get_tag_matchers () {
return new Tag_Matchers ();
}
2023-12-07 09:44:11 +01:00
/**
* Gets custom dimensions data based on available custom dimensions .
*
* @ since 1.113 . 0
*
* @ return array An associated array of custom dimensions data .
*/
private function get_custom_dimensions_data () {
if ( ! is_singular () ) {
return array ();
}
$settings = $this -> get_settings () -> get ();
if ( empty ( $settings [ 'availableCustomDimensions' ] ) ) {
return array ();
}
/**
* Filters the allowed post types for custom dimensions tracking .
*
* @ since 1.113 . 0
*
* @ param array $allowed_post_types The array of allowed post types .
*/
$allowed_post_types = apply_filters ( 'googlesitekit_custom_dimension_valid_post_types' , array ( 'post' ) );
2022-12-15 17:34:08 +01:00
2023-12-07 09:44:11 +01:00
$data = array ();
$post = get_queried_object ();
2025-02-28 08:42:11 +01:00
if ( ! $post instanceof WP_Post ) {
return $data ;
}
2023-12-07 09:44:11 +01:00
if ( in_array ( 'googlesitekit_post_type' , $settings [ 'availableCustomDimensions' ], true ) ) {
$data [ 'googlesitekit_post_type' ] = $post -> post_type ;
2022-12-15 17:34:08 +01:00
}
2023-12-07 09:44:11 +01:00
if ( is_singular ( $allowed_post_types ) ) {
foreach ( $settings [ 'availableCustomDimensions' ] as $custom_dimension ) {
switch ( $custom_dimension ) {
case 'googlesitekit_post_author' :
$author = get_userdata ( $post -> post_author );
if ( $author ) {
$data [ $custom_dimension ] = $author -> display_name ? $author -> display_name : $author -> user_login ;
}
break ;
case 'googlesitekit_post_categories' :
$categories = get_the_category ( $post -> ID );
if ( ! empty ( $categories ) ) {
$category_names = wp_list_pluck ( $categories , 'name' );
$data [ $custom_dimension ] = implode ( '; ' , $category_names );
}
break ;
case 'googlesitekit_post_date' :
$data [ $custom_dimension ] = get_the_date ( 'Ymd' , $post );
break ;
}
}
}
return $data ;
2022-12-15 17:34:08 +01:00
}
/**
* Parses account ID , adds it to the model object and returns updated model .
*
* @ since 1.31 . 0
*
* @ param Google_Model $account Account model .
* @ param string $id_key Attribute name that contains account id .
* @ return stdClass Updated model with _id attribute .
*/
public static function filter_account_with_ids ( $account , $id_key = 'name' ) {
$obj = $account -> toSimpleObject ();
$matches = array ();
if ( preg_match ( '#accounts/([^/]+)#' , $account [ $id_key ], $matches ) ) {
$obj -> _id = $matches [ 1 ];
}
return $obj ;
}
/**
* Parses account and property IDs , adds it to the model object and returns updated model .
*
* @ since 1.31 . 0
*
* @ param Google_Model $property Property model .
* @ param string $id_key Attribute name that contains property id .
* @ return stdClass Updated model with _id and _accountID attributes .
*/
public static function filter_property_with_ids ( $property , $id_key = 'name' ) {
$obj = $property -> toSimpleObject ();
$matches = array ();
2025-02-28 08:42:11 +01:00
if ( preg_match ( '#properties/([^/]+)#' , $property [ $id_key ] ? ? '' , $matches ) ) {
2022-12-15 17:34:08 +01:00
$obj -> _id = $matches [ 1 ];
}
$matches = array ();
2025-02-28 08:42:11 +01:00
if ( preg_match ( '#accounts/([^/]+)#' , $property [ 'parent' ] ? ? '' , $matches ) ) {
2022-12-15 17:34:08 +01:00
$obj -> _accountID = $matches [ 1 ]; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
}
return $obj ;
}
/**
* Parses property and web datastream IDs , adds it to the model object and returns updated model .
*
* @ since 1.31 . 0
*
* @ param Google_Model $webdatastream Web datastream model .
* @ return stdClass Updated model with _id and _propertyID attributes .
*/
public static function filter_webdatastream_with_ids ( $webdatastream ) {
$obj = $webdatastream -> toSimpleObject ();
$matches = array ();
if ( preg_match ( '#properties/([^/]+)/dataStreams/([^/]+)#' , $webdatastream [ 'name' ], $matches ) ) {
$obj -> _id = $matches [ 2 ];
$obj -> _propertyID = $matches [ 1 ]; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
}
return $obj ;
}
/**
* Filters a list of data stream objects and returns only web data streams .
*
* @ since 1.49 . 1
*
2023-01-25 20:43:46 +01:00
* @ param GoogleAnalyticsAdminV1betaDataStream [] $datastreams Data streams to filter .
* @ return GoogleAnalyticsAdminV1betaDataStream [] Web data streams .
2022-12-15 17:34:08 +01:00
*/
public static function filter_web_datastreams ( array $datastreams ) {
return array_filter (
$datastreams ,
2023-01-25 20:43:46 +01:00
function ( GoogleAnalyticsAdminV1betaDataStream $datastream ) {
2022-12-15 17:34:08 +01:00
return $datastream -> getType () === 'WEB_DATA_STREAM' ;
}
);
}
/**
* Parses a response , adding the _id and _propertyID params and converting to an array keyed by the propertyID and web datastream IDs .
*
* @ since 1.39 . 0
*
2023-01-25 20:43:46 +01:00
* @ param GoogleAnalyticsAdminV1betaListDataStreamsResponse [] $batch_response Array of GoogleAnalyticsAdminV1betaListWebDataStreamsResponse objects .
2022-12-15 17:34:08 +01:00
* @ return stdClass [] Array of models containing _id and _propertyID attributes , keyed by the propertyID .
*/
public static function parse_webdatastreams_batch ( $batch_response ) {
$mapped = array ();
foreach ( $batch_response as $response ) {
2023-01-25 20:43:46 +01:00
if ( $response instanceof Exception ) {
continue ;
}
2022-12-15 17:34:08 +01:00
$webdatastreams = self :: filter_web_datastreams ( $response -> getDataStreams () );
foreach ( $webdatastreams as $webdatastream ) {
$value = self :: filter_webdatastream_with_ids ( $webdatastream );
$key = $value -> _propertyID ; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
$mapped [ $key ] = isset ( $mapped [ $key ] ) ? $mapped [ $key ] : array ();
$mapped [ $key ][] = $value ;
}
}
return $mapped ;
}
/**
* Normalizes account ID and returns it .
*
* @ since 1.31 . 0
*
* @ param string $account_id Account ID .
* @ return string Updated account ID with " accounts/ " prefix .
*/
public static function normalize_account_id ( $account_id ) {
return 'accounts/' . $account_id ;
}
/**
* Normalizes property ID and returns it .
*
* @ since 1.31 . 0
*
* @ param string $property_id Property ID .
* @ return string Updated property ID with " properties/ " prefix .
*/
public static function normalize_property_id ( $property_id ) {
return 'properties/' . $property_id ;
}
/**
* Checks if the current user has access to the current configured service entity .
*
* @ since 1.70 . 0
*
* @ return boolean | WP_Error
*/
public function check_service_entity_access () {
2025-08-27 08:44:30 +02:00
// Create a basic report request with minimal parameters to test access.
$data = array (
'dimensions' => array ( 'date' ),
'metrics' => array ( 'sessions' ),
'startDate' => 'yesterday' ,
'endDate' => 'today' ,
'limit' => 0 ,
);
2022-12-15 17:34:08 +01:00
2025-08-27 08:44:30 +02:00
// Use the 'non-shareable-report' datapoint to prevent user access assumption
// when using dashboard sharing.
$request = $this -> get_data ( 'non-shareable-report' , $data );
if ( is_wp_error ( $request ) ) {
// A 403 error implies that the user does not have access to the service entity.
if ( $request -> get_error_code () === 403 ) {
2022-12-15 17:34:08 +01:00
return false ;
}
2025-08-27 08:44:30 +02:00
return $request ;
2022-12-15 17:34:08 +01:00
}
return true ;
}
2023-04-26 17:39:43 +02:00
/**
* Gets the Google Tag Settings for the given measurement ID .
*
* @ since 1.94 . 0
*
* @ param Google_Service_TagManager_Container $container Tag Manager container .
* @ param string $measurement_id Measurement ID .
* @ return array Google Tag Settings .
*/
protected function get_google_tag_settings_for_measurement_id ( $container , $measurement_id ) {
return array (
'googleTagAccountID' => $container -> getAccountId (),
'googleTagContainerID' => $container -> getContainerId (),
'googleTagID' => $this -> determine_google_tag_id_from_tag_ids ( $container -> getTagIds (), $measurement_id ),
);
}
/**
* Determines Google Tag ID from the given Tag IDs .
*
* @ since 1.94 . 0
*
* @ param array $tag_ids Tag IDs .
* @ param string $measurement_id Measurement ID .
* @ return string Google Tag ID .
*/
private function determine_google_tag_id_from_tag_ids ( $tag_ids , $measurement_id ) {
// If there is only one tag id in the array, return it.
if ( count ( $tag_ids ) === 1 ) {
return $tag_ids [ 0 ];
}
// If there are multiple tags, return the first one that starts with `GT-`.
foreach ( $tag_ids as $tag_id ) {
if ( substr ( $tag_id , 0 , 3 ) === 'GT-' ) { // strlen( 'GT-' ) === 3.
return $tag_id ;
}
}
// Otherwise, return the `$measurement_id` if it is in the array.
if ( in_array ( $measurement_id , $tag_ids , true ) ) {
return $measurement_id ;
}
// Otherwise, return the first one that starts with `G-`.
foreach ( $tag_ids as $tag_id ) {
if ( substr ( $tag_id , 0 , 2 ) === 'G-' ) { // strlen( 'G-' ) === 2.
return $tag_id ;
}
}
// If none of the above, return the first one.
return $tag_ids [ 0 ];
}
/**
* Gets the Google Analytics 4 tag ID .
*
* @ since 1.96 . 0
*
* @ return string Google Analytics 4 tag ID .
*/
private function get_tag_id () {
$settings = $this -> get_settings () -> get ();
2023-09-26 10:24:36 +02:00
if ( ! empty ( $settings [ 'googleTagID' ] ) ) {
2023-04-26 17:39:43 +02:00
return $settings [ 'googleTagID' ];
}
return $settings [ 'measurementID' ];
}
2023-09-26 10:24:36 +02:00
/**
* Gets the currently configured measurement ID .
*
* @ since 1.104 . 0
*
* @ return string Google Analytics 4 measurement ID .
*/
protected function get_measurement_id () {
$settings = $this -> get_settings () -> get ();
return $settings [ 'measurementID' ];
}
2023-12-07 09:44:11 +01:00
/**
* Populates custom dimension data to pass to JS via _googlesitekitModulesData .
*
* @ since 1.113 . 0
2025-08-27 08:44:30 +02:00
* @ since 1.158 . 0 Renamed method to `get_inline_custom_dimensions_data()` , and modified it to return a new array rather than populating a passed filter value .
2023-12-07 09:44:11 +01:00
*
* @ return array Inline modules data .
*/
2025-08-27 08:44:30 +02:00
private function get_inline_custom_dimensions_data () {
2023-12-07 09:44:11 +01:00
if ( $this -> is_connected () ) {
2025-08-27 08:44:30 +02:00
return array (
2023-12-07 09:44:11 +01:00
'customDimensionsDataAvailable' => $this -> custom_dimensions_data_available -> get_data_availability (),
);
}
}
2025-02-28 08:42:11 +01:00
/**
* Populates tag ID mismatch value to pass to JS via _googlesitekitModulesData .
*
* @ since 1.130 . 0
2025-08-27 08:44:30 +02:00
* @ since 1.158 . 0 Renamed method to `get_inline_tag_id_mismatch()` , and modified it to return a new array rather than populating a passed filter value .
2025-02-28 08:42:11 +01:00
*
* @ return array Inline modules data .
*/
2025-08-27 08:44:30 +02:00
private function get_inline_tag_id_mismatch () {
2025-02-28 08:42:11 +01:00
if ( $this -> is_connected () ) {
$tag_id_mismatch = $this -> transients -> get ( 'googlesitekit_inline_tag_id_mismatch' );
2025-08-27 08:44:30 +02:00
return array (
'tagIDMismatch' => $tag_id_mismatch ,
);
2025-02-28 08:42:11 +01:00
}
2025-08-27 08:44:30 +02:00
return array ();
2025-02-28 08:42:11 +01:00
}
/**
* Populates resource availability dates data to pass to JS via _googlesitekitModulesData .
*
* @ since 1.127 . 0
2025-08-27 08:44:30 +02:00
* @ since 1.158 . 0 Renamed method to `get_inline_resource_availability_dates_data()` , and modified it to return a new array rather than populating a passed filter value .
2025-02-28 08:42:11 +01:00
*
* @ return array Inline modules data .
*/
2025-08-27 08:44:30 +02:00
private function get_inline_resource_availability_dates_data () {
2025-02-28 08:42:11 +01:00
if ( $this -> is_connected () ) {
2025-08-27 08:44:30 +02:00
return array (
'resourceAvailabilityDates' => $this -> resource_data_availability_date -> get_all_resource_dates (),
2025-02-28 08:42:11 +01:00
);
}
2025-08-27 08:44:30 +02:00
return array ();
2025-02-28 08:42:11 +01:00
}
2023-05-23 23:18:12 +02:00
/**
* Filters whether or not the option to exclude certain users from tracking should be displayed .
*
* If the Analytics - 4 module is enabled , and the snippet is enabled , then the option to exclude
* the option to exclude certain users from tracking should be displayed .
*
* @ since 1.101 . 0
*
* @ param bool $allowed Whether to allow tracking exclusion .
* @ return bool Filtered value .
*/
private function filter_analytics_allow_tracking_disabled ( $allowed ) {
if ( $allowed ) {
return $allowed ;
}
2023-12-07 09:44:11 +01:00
if ( $this -> get_settings () -> get ()[ 'useSnippet' ] ) {
2023-05-23 23:18:12 +02:00
return true ;
}
return $allowed ;
}
2025-02-28 08:42:11 +01:00
/**
* Sets and returns available audiences .
*
* @ since 1.126 . 0
*
* @ param GoogleAnalyticsAdminV1alphaAudience [] $audiences The audiences to set .
* @ return array The available audiences .
*/
private function set_available_audiences ( $audiences ) {
$available_audiences = array_map (
function ( GoogleAnalyticsAdminV1alphaAudience $audience ) {
$display_name = $audience -> getDisplayName ();
$audience_item = array (
'name' => $audience -> getName (),
'displayName' => ( 'All Users' === $display_name ) ? 'All visitors' : $display_name ,
'description' => $audience -> getDescription (),
);
$audience_slug = $this -> get_audience_slug ( $audience );
$audience_type = $this -> get_audience_type ( $audience_slug );
$audience_item [ 'audienceType' ] = $audience_type ;
$audience_item [ 'audienceSlug' ] = $audience_slug ;
return $audience_item ;
},
$audiences
);
usort (
$available_audiences ,
function ( $audience_a , $audience_b ) use ( $available_audiences ) {
$audience_index_a = array_search ( $audience_a , $available_audiences , true );
$audience_index_b = array_search ( $audience_b , $available_audiences , true );
if ( false === $audience_index_a || false === $audience_index_b ) {
return 0 ;
}
$audience_a = $available_audiences [ $audience_index_a ];
$audience_b = $available_audiences [ $audience_index_b ];
$audience_type_a = $audience_a [ 'audienceType' ];
$audience_type_b = $audience_b [ 'audienceType' ];
if ( $audience_type_a === $audience_type_b ) {
if ( 'SITE_KIT_AUDIENCE' === $audience_type_b ) {
return 'new-visitors' === $audience_a [ 'audienceSlug' ] ? - 1 : 1 ;
}
return $audience_index_a - $audience_index_b ;
}
$weight_a = self :: AUDIENCE_TYPE_SORT_ORDER [ $audience_type_a ];
$weight_b = self :: AUDIENCE_TYPE_SORT_ORDER [ $audience_type_b ];
if ( $weight_a === $weight_b ) {
return $audience_index_a - $audience_index_b ;
}
return $weight_a - $weight_b ;
}
);
2025-04-25 12:30:07 +02:00
$this -> audience_settings -> merge (
2025-02-28 08:42:11 +01:00
array (
'availableAudiences' => $available_audiences ,
'availableAudiencesLastSyncedAt' => time (),
)
);
return $available_audiences ;
}
/**
* Gets the audience slug .
*
* @ since 1.126 . 0
*
* @ param GoogleAnalyticsAdminV1alphaAudience $audience The audience object .
* @ return string The audience slug .
*/
private function get_audience_slug ( GoogleAnalyticsAdminV1alphaAudience $audience ) {
$display_name = $audience -> getDisplayName ();
if ( 'All Users' === $display_name ) {
return 'all-users' ;
}
if ( 'Purchasers' === $display_name ) {
return 'purchasers' ;
}
$filter_clauses = $audience -> getFilterClauses ();
if ( $filter_clauses ) {
if ( $this -> has_audience_site_kit_identifier (
$filter_clauses ,
'new_visitors'
) ) {
return 'new-visitors' ;
}
if ( $this -> has_audience_site_kit_identifier (
$filter_clauses ,
'returning_visitors'
) ) {
return 'returning-visitors' ;
}
}
// Return an empty string for user defined audiences.
return '' ;
}
/**
* Gets the audience type based on the audience slug .
*
* @ since 1.126 . 0
*
* @ param string $audience_slug The audience slug .
* @ return string The audience type .
*/
private function get_audience_type ( $audience_slug ) {
if ( ! $audience_slug ) {
return 'USER_AUDIENCE' ;
}
switch ( $audience_slug ) {
case 'all-users' :
case 'purchasers' :
return 'DEFAULT_AUDIENCE' ;
case 'new-visitors' :
case 'returning-visitors' :
return 'SITE_KIT_AUDIENCE' ;
}
}
/**
* Checks if an audience Site Kit identifier
* ( e . g . `created_by_googlesitekit:new_visitors` ) exists in a nested array or object .
*
* @ since 1.126 . 0
*
* @ param array | object $data The array or object to search .
* @ param mixed $identifier The identifier to search for .
* @ return bool True if the value exists , false otherwise .
*/
private function has_audience_site_kit_identifier ( $data , $identifier ) {
if ( is_array ( $data ) || is_object ( $data ) ) {
foreach ( $data as $key => $value ) {
if ( is_array ( $value ) || is_object ( $value ) ) {
// Recursively search the nested structure.
if ( $this -> has_audience_site_kit_identifier ( $value , $identifier ) ) {
return true ;
}
} elseif (
'fieldName' === $key &&
'groupId' === $value &&
isset ( $data [ 'stringFilter' ] ) &&
" created_by_googlesitekit: { $identifier } " === $data [ 'stringFilter' ][ 'value' ]
) {
return true ;
}
}
}
return false ;
}
/**
* Returns the Site Kit - created audience display names from the passed list of audiences .
*
* @ since 1.129 . 0
*
* @ param array $audiences List of audiences .
*
* @ return array List of Site Kit - created audience display names .
*/
private function get_site_kit_audiences ( $audiences ) {
// Ensure that audiences are available, otherwise return an empty array.
if ( empty ( $audiences ) || ! is_array ( $audiences ) ) {
return array ();
}
2025-04-25 12:30:07 +02:00
$site_kit_audiences = array_filter ( $audiences , fn ( $audience ) => ! empty ( $audience [ 'audienceType' ] ) && ( 'SITE_KIT_AUDIENCE' === $audience [ 'audienceType' ] ) );
2025-02-28 08:42:11 +01:00
if ( empty ( $site_kit_audiences ) ) {
return array ();
}
return wp_list_pluck ( $site_kit_audiences , 'displayName' );
}
/**
* Populates conversion reporting event data to pass to JS via _googlesitekitModulesData .
*
* @ since 1.139 . 0
2025-08-27 08:44:30 +02:00
* @ since 1.158 . 0 Renamed method to `get_inline_conversion_reporting_events_detection()` , and modified it to return a new array rather than populating a passed filter value .
2025-02-28 08:42:11 +01:00
*
* @ return array Inline modules data .
*/
2025-08-27 08:44:30 +02:00
private function get_inline_conversion_reporting_events_detection () {
2025-02-28 08:42:11 +01:00
if ( ! $this -> is_connected () ) {
2025-08-27 08:44:30 +02:00
return array ();
2025-02-28 08:42:11 +01:00
}
$detected_events = $this -> transients -> get ( Conversion_Reporting_Events_Sync :: DETECTED_EVENTS_TRANSIENT );
$lost_events = $this -> transients -> get ( Conversion_Reporting_Events_Sync :: LOST_EVENTS_TRANSIENT );
$new_events_badge = $this -> transients -> get ( Conversion_Reporting_New_Badge_Events_Sync :: NEW_EVENTS_BADGE_TRANSIENT );
2025-08-27 08:44:30 +02:00
return array (
'newEvents' => is_array ( $detected_events ) ? $detected_events : array (),
'lostEvents' => is_array ( $lost_events ) ? $lost_events : array (),
'newBadgeEvents' => is_array ( $new_events_badge ) ? $new_events_badge [ 'events' ] : array (),
);
}
/**
* Gets required inline data for the module .
*
* @ since 1.158 . 0
* @ since 1.160 . 0 Include $modules_data parameter to match the interface .
*
* @ param array $modules_data Inline modules data .
* @ return array An array of the module ' s inline data .
*/
public function get_inline_data ( $modules_data ) {
if ( ! $this -> is_connected () ) {
return $modules_data ;
}
$inline_data = array ();
// Web data stream availability data.
$settings = $this -> get_settings () -> get ();
$transient_key = 'googlesitekit_web_data_stream_unavailable_' . $settings [ 'webDataStreamID' ];
$is_web_data_stream_unavailable = $this -> transients -> get ( $transient_key );
$inline_data [ 'isWebDataStreamUnavailable' ] = ( bool ) $is_web_data_stream_unavailable ;
$inline_data = array_merge (
$inline_data ,
$this -> get_inline_custom_dimensions_data (),
$this -> get_inline_tag_id_mismatch (),
$this -> get_inline_resource_availability_dates_data (),
$this -> get_inline_conversion_reporting_events_detection ()
);
2025-02-28 08:42:11 +01:00
2025-08-27 08:44:30 +02:00
$modules_data [ self :: MODULE_SLUG ] = $inline_data ;
2025-02-28 08:42:11 +01:00
return $modules_data ;
}
2022-12-15 17:34:08 +01:00
}