function google_analytics_page_attachments in Google Analytics 8.2
Same name and namespace in other branches
- 8.3 google_analytics.module \google_analytics_page_attachments()
- 4.x google_analytics.module \google_analytics_page_attachments()
Implements hook_page_attachments().
Insert JavaScript to the appropriate scope/region of the page.
File
- ./
google_analytics.module, line 59 - Drupal Module: Google Analytics.
Code
function google_analytics_page_attachments(array &$page) {
$account = \Drupal::currentUser();
$config = \Drupal::config('google_analytics.settings');
$id = $config
->get('account');
$request = \Drupal::request();
$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 (preg_match('/^UA-\\d+-\\d+$/', $id) && (_google_analytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _google_analytics_visibility_user($account)) {
// Init variables.
$debug = $config
->get('debug');
$url_custom = '';
// Add link tracking.
$link_settings = [];
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(NULL, FALSE) as $type => $messages) {
// Track only the selected message types.
if (in_array($type, $message_types)) {
foreach ($messages as $message) {
// @todo: Track as exceptions?
$message_events .= 'ga("send", "event", ' . Json::encode(t('Messages')) . ', ' . Json::encode($status_heading[$type]) . ', ' . Json::encode(strip_tags((string) $message)) . ');';
}
}
}
}
// 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_var = '';
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['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');
}
// Add variables to tracker.
$custom_var .= 'ga("set", ' . Json::encode($google_analytics_custom_type . $google_analytics_custom_var['index']) . ', ' . Json::encode($google_analytics_custom_var['value']) . ');';
}
}
}
// Build tracker code.
$script = '(function(i,s,o,g,r,a,m){';
$script .= 'i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){';
$script .= '(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),';
$script .= 'm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)';
$script .= '})(window,document,"script",';
// Which version of the tracking library should be used?
$library_tracker_url = 'https://www.google-analytics.com/' . ($debug ? 'analytics_debug.js' : 'analytics.js');
// Should a local cached copy of analytics.js be used?
if ($config
->get('cache') && ($url = _google_analytics_cache($library_tracker_url))) {
// A dummy query-string is added to filenames, to gain control over
// browser-caching. The string changes on every update or full cache
// flush, forcing browsers to load a new copy of the files, as the
// URL changed.
$query_string = '?' . (\Drupal::state()
->get('system.css_js_query_string') ?: '0');
$script .= '"' . $url . $query_string . '"';
}
else {
$script .= '"' . $library_tracker_url . '"';
}
$script .= ',"ga");';
// Add any custom code snippets if specified.
$codesnippet_create = $config
->get('codesnippet.create');
$codesnippet_before = $config
->get('codesnippet.before');
$codesnippet_after = $config
->get('codesnippet.after');
// Build the create only fields list.
$create_only_fields = [
'cookieDomain' => 'auto',
];
$create_only_fields = array_merge($create_only_fields, $codesnippet_create);
// 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))) {
$create_only_fields = array_merge($create_only_fields, [
'cookieDomain' => $cookie_domain,
]);
$googleanalytics_adsense_script .= 'window.google_analytics_domain_name = ' . Json::encode($cookie_domain) . ';';
}
elseif ($domain_mode == 2) {
// Cross Domain tracking. 'autoLinker' need to be enabled in 'create'.
$create_only_fields = array_merge($create_only_fields, [
'allowLinker' => TRUE,
]);
$googleanalytics_adsense_script .= 'window.google_analytics_domain_name = "none";';
}
// Track logged in users across all devices.
if ($config
->get('track.userid') && $account
->isAuthenticated()) {
$create_only_fields['userId'] = google_analytics_user_id_hash($account
->id());
}
// Create a tracker.
$script .= 'ga("create", ' . Json::encode($id) . ', ' . Json::encode($create_only_fields) . ');';
// Prepare Adsense tracking.
$googleanalytics_adsense_script .= 'window.google_analytics_uacct = ' . Json::encode($id) . ';';
// Add enhanced link attribution after 'create', but before 'pageview' send.
// @see https://support.google.com/analytics/answer/2558867
if ($config
->get('track.linkid')) {
$script .= 'ga("require", "linkid", "linkid.js");';
}
// Add display features after 'create', but before 'pageview' send.
// @see https://support.google.com/analytics/answer/2444872
if ($config
->get('track.displayfeatures')) {
$script .= 'ga("require", "displayfeatures");';
}
// Domain tracking type.
if ($domain_mode == 2) {
// Cross Domain tracking
// https://developers.google.com/analytics/devguides/collection/upgrade/reference/gajs-analyticsjs#cross-domain
$script .= 'ga("require", "linker");';
$script .= 'ga("linker:autoLink", ' . Json::encode($link_settings['trackCrossDomains']) . ');';
}
if ($config
->get('privacy.anonymizeip')) {
$script .= 'ga("set", "anonymizeIp", true);';
}
if (!empty($custom_var)) {
$script .= $custom_var;
}
if (!empty($codesnippet_before)) {
$script .= $codesnippet_before;
}
if (!empty($url_custom)) {
$script .= 'ga("set", "page", ' . $url_custom . ');';
}
$script .= 'ga("send", "pageview");';
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;
}
$page['#attached']['html_head'][] = [
[
'#tag' => 'script',
'#value' => new GoogleAnalyticsJavaScriptSnippet($script),
],
'google_analytics_tracking_script',
];
}
}