google_analytics.module in Google Analytics 4.x
Same filename and directory in other branches
Drupal Module: Google Analytics.
Adds the required Javascript to all your Drupal pages to allow tracking by the Google Analytics statistics package.
File
google_analytics.moduleView source
<?php
/**
* @file
* Drupal Module: Google Analytics.
*
* Adds the required Javascript to all your Drupal pages to allow tracking by
* the Google Analytics statistics package.
*
*/
use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\node\NodeInterface;
use GuzzleHttp\Exception\RequestException;
use Drupal\google_analytics\Component\Render\GoogleAnalyticsJavaScriptSnippet;
use Drupal\Core\File\FileSystemInterface;
/**
* Advertise the supported google analytics api details.
*/
function google_analytics_api() {
return [
'api' => 'gtag.js',
];
}
/**
* Implements hook_help().
*/
function google_analytics_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.google_analytics':
$output = '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Google Analytics adds a web statistics tracking system to your website. This system incorporates numerous statistical features. For an extensive listing of these features see the <a href=":project">Google Analytics</a> project site. Beyond that, additional information can be found at the <a href=":documentation">Drupal - Google Analytics documentation</a>.', [
':documentation' => 'https://www.drupal.org/node/37694',
':project' => 'https://www.drupal.org/project/google_analytics',
]) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dt>' . t('Configuring Google Analytics') . '</dt>';
$output .= '<dd>' . t('All settings for this module can be found on the <a href=":ga_settings">Google Analytics settings</a> page. When entering the Google Analytics account number here, it will automatically add the required JavaScript to every page generated. The <em>General Settings</em> section on this page provides additional instruction about setting up tracking thru the Google account.', [
':ga_settings' => Url::fromRoute('google_analytics.admin_settings_form')
->toString(),
]) . '</dd>';
$output .= '<dt>' . t('Additional features') . '</dt>';
$output .= '<dd>' . t('The Google Analytics module offers a bit more than basic tracking. <em>Page Tracking</em> for instance allows you to provide a list of pages to track, or a list of pages not to track. Role and Link tracking features are also available. For a comprehensive discussion on the setup and use of its many feature see the <a href=":documentation">Drupal - Google Analytics documentation</a>.', [
':documentation' => 'https://www.drupal.org/node/37694',
]) . '</dd>';
return $output;
case 'google_analytics.admin_settings_form':
return t('<a href=":ga_url">Google Analytics</a> is a free (registration required) website traffic and marketing effectiveness service.', [
':ga_url' => 'https://marketingplatform.google.com/about/analytics/',
]);
}
}
/**
* Implements hook_page_attachments().
*
* Insert JavaScript to the appropriate scope/region of the page.
*/
function google_analytics_page_attachments(array &$page) {
$account = \Drupal::currentUser();
$config = \Drupal::config('google_analytics.settings');
$request = \Drupal::request();
//$ga_javascript = \Drupal::service('google_analytics.javascript');
/** @var \Drupal\google_analytics\Helpers\VisiblityTracker $visibilityTracker */
$visibilityTracker = \Drupal::service('google_analytics.visibility');
/** @var \Drupal\google_analytics\Helpers\GoogleAnalyticsAccounts $ga_accounts */
$ga_accounts = \Drupal::service('google_analytics.accounts');
$base_path = base_path();
// Add module cache tags.
$page['#cache']['tags'] = Cache::mergeTags(isset($page['#cache']['tags']) ? $page['#cache']['tags'] : [], $config
->getCacheTags());
// Get page http status code for visibility filtering.
$status = NULL;
if ($exception = $request->attributes
->get('exception')) {
$status = $exception
->getStatusCode();
}
$trackable_status_codes = [
// "Forbidden" status code.
'403',
// "Not Found" status code.
'404',
];
// 1. Check if the GA account number has a valid value.
// 2. Track page views based on visibility value.
// 3. Check if we should track the currently active user's role.
// 4. Ignore pages visibility filter for 404 or 403 status codes.
if ($ga_accounts
->getDefaultMeasurementId() && ($visibilityTracker
->getVisibilityPages() || in_array($status, $trackable_status_codes)) && $visibilityTracker
->getUserVisibilty($account)) {
$default_id = $ga_accounts
->getDefaultMeasurementId();
// Init variables.
$debug = $config
->get('debug');
$url_custom = '';
// Add link tracking.
$link_settings = [
'account' => $default_id,
];
if ($track_outbound = $config
->get('track.outbound')) {
$link_settings['trackOutbound'] = $track_outbound;
}
if ($track_mailto = $config
->get('track.mailto')) {
$link_settings['trackMailto'] = $track_mailto;
}
if (($track_download = $config
->get('track.files')) && ($trackfiles_extensions = $config
->get('track.files_extensions'))) {
$link_settings['trackDownload'] = $track_download;
$link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
}
if (\Drupal::moduleHandler()
->moduleExists('colorbox') && ($track_colorbox = $config
->get('track.colorbox'))) {
$link_settings['trackColorbox'] = $track_colorbox;
}
if ($track_domain_mode = $config
->get('domain_mode')) {
$link_settings['trackDomainMode'] = $track_domain_mode;
}
if ($track_cross_domains = $config
->get('cross_domains')) {
$link_settings['trackCrossDomains'] = preg_split('/(\\r\\n?|\\n)/', $track_cross_domains);
}
if ($track_url_fragments = $config
->get('track.urlfragments')) {
$link_settings['trackUrlFragments'] = $track_url_fragments;
$url_custom = 'location.pathname + location.search + location.hash';
}
if (!empty($link_settings)) {
$page['#attached']['drupalSettings']['google_analytics'] = $link_settings;
// Add debugging code.
if ($debug) {
$page['#attached']['library'][] = 'google_analytics/google_analytics.debug';
// phpcs:disable
// Add the JS test in development to the page.
// $page['#attached']['library'][] = 'google_analytics/google_analytics.test';
// phpcs:enable
}
else {
$page['#attached']['library'][] = 'google_analytics/google_analytics';
}
}
// Add messages tracking.
$message_events = '';
if ($message_types = $config
->get('track.messages')) {
$message_types = array_values(array_filter($message_types));
$status_heading = [
'status' => t('Status message'),
'warning' => t('Warning message'),
'error' => t('Error message'),
];
foreach (\Drupal::messenger()
->all() as $type => $messages) {
// Track only the selected message types.
if (in_array($type, $message_types)) {
foreach ($messages as $message) {
// @todo: Track as exceptions?
$event = [];
$event['event_category'] = t('Messages');
$event['event_label'] = strip_tags((string) $message);
$message_events .= 'gtag("event", ' . Json::encode($status_heading[$type]) . ', ' . Json::encode($event) . ');';
}
}
}
}
// Site search tracking support.
if (\Drupal::moduleHandler()
->moduleExists('search') && $config
->get('track.site_search') && strpos(\Drupal::routeMatch()
->getRouteName(), 'search.view') === 0 && ($keys = $request->query
->has('keys') ? trim($request
->get('keys')) : '')) {
// hook_item_list__search_results() is not executed if search result is
// empty. Make sure the counter is set to 0 if there are no results.
$entity_id = \Drupal::routeMatch()
->getParameter('entity')
->id();
$url_custom = '(window.google_analytics_search_results) ? ' . Json::encode(Url::fromRoute('search.view_' . $entity_id, [], [
'query' => [
'search' => $keys,
],
])
->toString()) . ' : ' . Json::encode(Url::fromRoute('search.view_' . $entity_id, [
'query' => [
'search' => 'no-results:' . $keys,
'cat' => 'no-results',
],
])
->toString());
}
// If this node is a translation of another node, pass the original
// node instead.
if (\Drupal::moduleHandler()
->moduleExists('content_translation') && $config
->get('translation_set')) {
// Check if we have a node object, it has translation enabled, and its
// language code does not match its source language code.
if ($request->attributes
->has('node')) {
$node = $request->attributes
->get('node');
if ($node instanceof NodeInterface && \Drupal::service('entity.repository')
->getTranslationFromContext($node) !== $node
->getUntranslated()) {
$url_custom = Json::encode(Url::fromRoute('entity.node.canonical', [
'node' => $node
->id(),
], [
'language' => $node
->getUntranslated()
->language(),
])
->toString());
}
}
}
// Track access denied (403) and file not found (404) pages.
if ($status == '403') {
// See https://www.google.com/support/analytics/bin/answer.py?answer=86927
$url_custom = '"' . $base_path . '403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
}
elseif ($status == '404') {
$url_custom = '"' . $base_path . '404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
}
// #2693595: User has entered an invalid login and clicked on forgot
// password link. This link contains the username or email address and may
// get send to Google if we do not override it. Override only if 'name'
// query param exists. Last custom url condition, this need to win.
//
// URLs to protect are:
// - user/password?name=username
// - user/password?name=foo@example.com
if (\Drupal::routeMatch()
->getRouteName() == 'user.pass' && $request->query
->has('name')) {
$url_custom = '"' . $base_path . 'user/password"';
}
// Add custom dimensions and metrics.
$custom_map = [];
$custom_vars = [];
foreach ([
'dimension',
'metric',
] as $google_analytics_custom_type) {
$google_analytics_custom_vars = $config
->get('custom.' . $google_analytics_custom_type);
// Are there dimensions or metrics configured?
if (!empty($google_analytics_custom_vars)) {
// Add all the configured variables to the content.
foreach ($google_analytics_custom_vars as $google_analytics_custom_var) {
// Replace tokens in values.
$types = [];
if ($request->attributes
->has('node')) {
$node = $request->attributes
->get('node');
if ($node instanceof NodeInterface) {
$types += [
'node' => $node,
];
}
}
$google_analytics_custom_var['value'] = \Drupal::token()
->replace($google_analytics_custom_var['value'], $types, [
'clear' => TRUE,
]);
// Suppress empty values.
if (!mb_strlen(trim($google_analytics_custom_var['name'])) || !mb_strlen(trim($google_analytics_custom_var['value']))) {
continue;
}
// Per documentation the max length of a dimension is 150 bytes.
// A metric has no length limitation. It's not documented if this
// limit means 150 bytes after url encoding or before.
// See https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#customs
if ($google_analytics_custom_type == 'dimension' && mb_strlen($google_analytics_custom_var['value']) > 150) {
$google_analytics_custom_var['value'] = substr($google_analytics_custom_var['value'], 0, 150);
}
// Cast metric values for json_encode to data type numeric.
if ($google_analytics_custom_type == 'metric') {
settype($google_analytics_custom_var['value'], 'float');
}
// Build the arrays of values.
$custom_map['custom_map'][$google_analytics_custom_type . $google_analytics_custom_var['index']] = $google_analytics_custom_var['name'];
$custom_vars[$google_analytics_custom_var['name']] = $google_analytics_custom_var['value'];
}
}
}
$custom_var = '';
if (!empty($custom_map)) {
// Add custom variables to tracker.
$custom_var .= 'gtag("config", ' . Json::encode($default_id) . ', ' . Json::encode($custom_map) . ');';
$custom_var .= 'gtag("event", "custom", ' . Json::encode($custom_vars) . ');';
}
// Build tracker code.
$script = 'window.dataLayer = window.dataLayer || [];';
$script .= 'function gtag(){dataLayer.push(arguments)};';
$script .= 'gtag("js", new Date());';
$script .= 'gtag("set", "developer_id.dMDhkMT", true);';
// Add any custom code snippets if specified.
$codesnippet_parameters = $config
->get('codesnippet.create') ?? [];
$codesnippet_before = $config
->get('codesnippet.before');
$codesnippet_after = $config
->get('codesnippet.after');
// Build the arguments fields list.
// https://developers.google.com/analytics/devguides/collection/gtagjs/sending-data
$arguments = [
'groups' => 'default',
];
$arguments = array_merge($arguments, $codesnippet_parameters);
// Domain tracking type.
global $cookie_domain;
$domain_mode = $config
->get('domain_mode');
$googleanalytics_adsense_script = '';
// Per RFC 2109, cookie domains must contain at least one dot other than the
// first. For hosts such as 'localhost' or IP Addresses we don't set a
// cookie domain.
if ($domain_mode == 1 && count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
$arguments = array_merge($arguments, [
'cookie_domain' => $cookie_domain,
]);
$googleanalytics_adsense_script .= 'window.google_analytics_domain_name = ' . Json::encode($cookie_domain) . ';';
}
elseif ($domain_mode == 2) {
// Cross Domain tracking
// https://developers.google.com/analytics/devguides/collection/gtagjs/cross-domain
$arguments['linker'] = [
'domains' => $link_settings['trackCrossDomains'],
];
$googleanalytics_adsense_script .= 'window.google_analytics_domain_name = "none";';
}
// Track logged in users across all devices.
if ($config
->get('track.userid') && $account
->isAuthenticated()) {
$arguments['user_id'] = $ga_accounts
->getUserIdHash($account
->id());
}
// Eliminate for GA 4.x
if ($config
->get('privacy.anonymizeip')) {
$arguments['anonymize_ip'] = TRUE;
}
if (!empty($url_custom)) {
$arguments['page_path'] = 'PLACEHOLDER_URL_CUSTOM';
}
// Add enhanced link attribution after 'create', but before 'pageview' send.
// @see https://developers.google.com/analytics/devguides/collection/gtagjs/enhanced-link-attribution
if ($config
->get('track.linkid')) {
$arguments['link_attribution'] = TRUE;
}
// Disabling display features.
// @see https://developers.google.com/analytics/devguides/collection/gtagjs/display-features
if (!$config
->get('track.displayfeatures')) {
$arguments['allow_ad_personalization_signals'] = FALSE;
}
// Convert array to JSON format.
$arguments_json = Json::encode($arguments);
// Json::encode() cannot convert every data type properly.
$arguments_json = str_replace('"PLACEHOLDER_URL_CUSTOM"', $url_custom, $arguments_json);
// Create a tracker.
if (!empty($codesnippet_before)) {
$script .= $codesnippet_before;
}
$script .= 'gtag("config", ' . Json::encode($default_id) . ', ' . $arguments_json . ');';
// Prepare Adsense tracking.
$googleanalytics_adsense_script .= 'window.google_analytics_uacct = ' . Json::encode($default_id) . ';';
if (!empty($custom_var)) {
$script .= $custom_var;
}
if (!empty($message_events)) {
$script .= $message_events;
}
if (!empty($codesnippet_after)) {
$script .= $codesnippet_after;
}
if ($config
->get('track.adsense')) {
// Custom tracking. Prepend before all other JavaScript.
// @TODO: https://support.google.com/adsense/answer/98142
// sounds like it could be appended to $script.
$script = $googleanalytics_adsense_script . $script;
}
// Add additional Accounts to gTag.
foreach ($ga_accounts
->getAdditionalAccounts() as $additionalAccount) {
$script .= 'gtag("config", ' . Json::encode($additionalAccount) . ');';
}
// Prepend tracking library directly before script code.
$javascript_service = \Drupal::service('google_analytics.javascript_cache');
$page['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#attributes' => [
'async' => TRUE,
'src' => $javascript_service
->fetchGoogleAnalyticsJavascript($default_id),
],
],
'google_analytics_tracking_file',
];
$page['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#value' => new GoogleAnalyticsJavaScriptSnippet($script),
],
'google_analytics_tracking_script',
];
}
}
/**
* Implements hook_entity_extra_field_info().
*/
function google_analytics_entity_extra_field_info() {
$extra['user']['user']['form']['google_analytics'] = [
'label' => t('Google Analytics settings'),
'description' => t('Google Analytics module form element.'),
'weight' => 3,
];
return $extra;
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function google_analytics_form_user_form_alter(&$form, FormStateInterface $form_state) {
$config = \Drupal::config('google_analytics.settings');
/** @var Drupal\user\ProfileForm $profileForm */
$profileForm = $form_state
->getFormObject();
/** @var Drupal\user\Entity\User $account */
$account = $profileForm
->getEntity();
/** @var \Drupal\google_analytics\Helper\VisiblityTracker $visibilityTracker */
$visibilityTracker = \Drupal::service('google_analytics.visibility');
if ($account
->hasPermission('opt-in or out of google analytics tracking') && ($visibility_user_account_mode = $config
->get('visibility.user_account_mode')) != 0 && $visibilityTracker
->getVisibilityRoles($account)) {
$account_data_google_analytics = \Drupal::service('user.data')
->get('google_analytics', $account
->id());
$form['google_analytics'] = [
'#type' => 'details',
'#title' => t('Google Analytics settings'),
'#weight' => 3,
'#open' => TRUE,
];
$description = '';
switch ($visibility_user_account_mode) {
case 1:
$description = t('Users are tracked by default, but you are able to opt out.');
break;
case 2:
$description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
break;
}
$form['google_analytics']['user_account_users'] = [
'#type' => 'checkbox',
'#title' => t('Enable user tracking'),
'#description' => $description,
'#default_value' => isset($account_data_google_analytics['user_account_users']) ? $account_data_google_analytics['user_account_users'] : $visibility_user_account_mode == 1,
];
// hook_user_update() is missing in D8, add custom submit handler.
$form['actions']['submit']['#submit'][] = 'google_analytics_user_profile_form_submit';
}
}
/**
* Submit callback for user profile form to save the Google Analytics setting.
*/
function google_analytics_user_profile_form_submit($form, FormStateInterface $form_state) {
/** @var Drupal\user\ProfileForm $profileForm */
$profileForm = $form_state
->getFormObject();
/** @var Drupal\user\Entity\User $account */
$account = $profileForm
->getEntity();
if ($account
->id() && $form_state
->hasValue('user_account_users')) {
\Drupal::service('user.data')
->set('google_analytics', $account
->id(), 'user_account_users', (int) $form_state
->getValue('user_account_users'));
}
}
/**
* Implements hook_cron().
*/
function google_analytics_cron() {
$config = \Drupal::config('google_analytics.settings');
$request_time = \Drupal::time()
->getRequestTime();
$javascript_service = \Drupal::service('google_analytics.javascript_cache');
$ga_accounts = \Drupal::service('google_analytics.accounts');
// Return prematurely if no default measurement ID was found.
if (empty($ga_accounts
->getDefaultMeasurementId())) {
return;
}
// Regenerate the tracking code file every day.
if ($request_time - \Drupal::state()
->get('google_analytics.last_cache') >= 86400 && $config
->get('cache')) {
$javascript_service
->fetchGoogleAnalyticsJavascript($ga_accounts
->getDefaultMeasurementId(), TRUE);
\Drupal::state()
->set('google_analytics.last_cache', $request_time);
}
}
/**
* Implements hook_preprocess_item_list__search_results().
*
* Collects and adds the number of search results to the head.
*/
function google_analytics_preprocess_item_list__search_results(&$variables) {
$config = \Drupal::config('google_analytics.settings');
// Only run on search results list.
if ($config
->get('track.site_search')) {
// Get the pager manager to give us the number of items returned.
/** @var \Drupal\Core\Pager\PagerManagerInterface $pager_manager */
$pager_manager = \Drupal::service('pager.manager');
$items = 0;
if ($pager_manager
->getPager()) {
$items = $pager_manager
->getPager()
->getTotalItems();
}
$variables['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#value' => 'window.google_analytics_search_results = ' . $items . ';',
'#weight' => JS_LIBRARY - 1,
],
'google_analytics_search_script',
];
}
}
Functions
Name | Description |
---|---|
google_analytics_api | Advertise the supported google analytics api details. |
google_analytics_cron | Implements hook_cron(). |
google_analytics_entity_extra_field_info | Implements hook_entity_extra_field_info(). |
google_analytics_form_user_form_alter | Implements hook_form_FORM_ID_alter(). |
google_analytics_help | Implements hook_help(). |
google_analytics_page_attachments | Implements hook_page_attachments(). |
google_analytics_preprocess_item_list__search_results | Implements hook_preprocess_item_list__search_results(). |
google_analytics_user_profile_form_submit | Submit callback for user profile form to save the Google Analytics setting. |