@@ -117,6 +117,58 @@ function stanford_basic_page_attachments_alter(array &$attachments) {
117117 }
118118 // Check if dropdown menus are activated
119119 $attachments['#attached']['drupalSettings']['stanford_basic']['nav_dropdown_enabled'] = (bool) theme_get_setting('nav_dropdown_enabled', 'stanford_basic');
120+
121+ // Only add Google Analytics for anonymous users or users without editing
122+ // access while on Acquia environment. Being able to view the toolbar is a
123+ // good indicator that they can edit some part of the site.
124+ if (
125+ isset($_ENV['AH_SITE_ENVIRONMENT']) &&
126+ !\Drupal::currentUser()->hasPermission('access toolbar')
127+ ) {
128+ _stanford_basic_add_ga_tracking($attachments);
129+ }
130+ }
131+
132+ /**
133+ * Add the necessary GA tracking for shared analytics.
134+ *
135+ * @param array $attachments
136+ * Page attachments from hook_page_attachments_alter().
137+ */
138+ function _stanford_basic_add_ga_tracking(array &$attachments) {
139+ $add_ga_file = FALSE;
140+ // Look to see if there's already a Google Analytics tracking file included.
141+ if (isset($attachments['#attached']['html_head'])) {
142+ foreach ($attachments['#attached']['html_head'] as $html_head) {
143+ if ($html_head[1] == 'google_analytics_tracking_file') {
144+ $add_ga_file = TRUE;
145+ break;
146+ }
147+ }
148+ }
149+
150+ // No GA tracking file provided by GA module, we'll add our own.
151+ if (!$add_ga_file) {
152+ $attachments['#attached']['html_head'][] = [
153+ [
154+ '#tag' => 'script',
155+ '#attributes' => [
156+ 'async' => TRUE,
157+ 'src' => '//www.googletagmanager.com/gtag/js?id=G-BECJQXLNCY',
158+ ],
159+ ],
160+ 'stanford_basic_analytics_tracking_file',
161+ ];
162+ }
163+
164+ // Add the shared GA tracking tag.
165+ $attachments['#attached']['html_head'][] = [
166+ [
167+ '#tag' => 'script',
168+ '#value' => 'gtag("config", "G-BECJQXLNCY");',
169+ ],
170+ 'stanford_basic_analytics_tracking',
171+ ];
120172}
121173
122174/**
@@ -159,15 +211,6 @@ function stanford_basic_preprocess_html(&$variables) {
159211
160212 // The base path.
161213 $variables['base_path'] = base_path();
162-
163- // Add global google analytics tracker if the site is on Acquia.
164- if (isset($_ENV['AH_SITE_ENVIRONMENT'])) {
165- $variables['add_global_ga'] = TRUE;
166- if (\Drupal::moduleHandler()->moduleExists('google_analytics')) {
167- $variables['ga_module_enabled'] = !empty(\Drupal::config('google_analytics.settings')
168- ->get('account'));
169- }
170- }
171214}
172215
173216/**
0 commit comments