You are here

function googleanalytics_add_js in Google Analytics 6.4

Adds Google Analytics tracking scripts.

1 string reference to 'googleanalytics_add_js'
googleanalytics_theme_registry_alter in ./googleanalytics.module
Implementation of hook_theme_registry_alter().

File

./googleanalytics.module, line 90
Drupal Module: Google Analytics

Code

function googleanalytics_add_js(&$vars, $hook) {
  global $user;
  $id = variable_get('googleanalytics_account', '');

  // Get page status code for visibility filtering.
  $status = _googleanalytics_get_http_header('Status');
  $trackable_status_codes = array(
    '403 Forbidden',
    '404 Not Found',
  );

  // 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) && (_googleanalytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _googleanalytics_visibility_user($user)) {
    $debug = variable_get('googleanalytics_debug', 0);
    $url_custom = '';

    // Add link tracking.
    $link_settings = array();
    if ($track_outbound = variable_get('googleanalytics_trackoutgoing', 1)) {
      $link_settings['trackOutbound'] = $track_outbound;
    }
    if ($track_mailto = variable_get('googleanalytics_trackmailto', 1)) {
      $link_settings['trackMailto'] = $track_mailto;
    }
    if (($track_download = variable_get('googleanalytics_trackfiles', 1)) && ($trackfiles_extensions = variable_get('googleanalytics_trackfiles_extensions', GOOGLEANALYTICS_TRACKFILES_EXTENSIONS))) {
      $link_settings['trackDownload'] = $track_download;
      $link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
    }
    if ($track_domain_mode = variable_get('googleanalytics_domain_mode', 0)) {
      $link_settings['trackDomainMode'] = (int) $track_domain_mode;
    }
    if ($track_cross_domains = variable_get('googleanalytics_cross_domains', '')) {
      $link_settings['trackCrossDomains'] = preg_split('/(\\r\\n?|\\n)/', $track_cross_domains);
    }
    if ($track_url_fragments = variable_get('googleanalytics_trackurlfragments', 0)) {
      $link_settings['trackUrlFragments'] = $track_url_fragments;
      $url_custom = 'location.pathname + location.search + location.hash';
    }
    if (!empty($link_settings)) {
      drupal_add_js(array(
        'googleanalytics' => $link_settings,
      ), 'setting');

      // Add debugging code.
      if ($debug) {
        drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.debug.js');

        // Add the JS test in development to the page.

        //drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.test.js');
      }
      else {
        drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.js');
      }
    }

    // Add messages tracking.
    $message_events = '';
    if ($message_types = variable_get('googleanalytics_trackmessages', array())) {
      $message_types = array_values(array_filter($message_types));
      $status_heading = array(
        'status' => t('Status message'),
        'warning' => t('Warning message'),
        'error' => t('Error message'),
      );
      foreach (drupal_get_messages(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", ' . drupal_to_js(t('Messages')) . ', ' . drupal_to_js($status_heading[$type]) . ', ' . drupal_to_js(strip_tags($message)) . ');';
          }
        }
      }
    }

    // Site search tracking support.
    if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && ($keys = search_get_keys())) {

      // hook_preprocess_search_results() is not executed if search result is
      // empty. Make sure the counter is set to 0 if there are no results.
      $url_custom = '(window.googleanalytics_search_results) ? ' . drupal_to_js(url('search/' . arg(1), array(
        'query' => 'search=' . drupal_urlencode($keys),
      ))) . ' : ' . drupal_to_js(url('search/' . arg(1), array(
        'query' => 'search=no-results:' . drupal_urlencode($keys) . '&cat=no-results',
      )));
    }

    // If this node is a translation of another node, pass the original
    // node instead.
    if (module_exists('translation') && variable_get('googleanalytics_translation_set', 0)) {

      // Check we have a node object, it supports translation, and its
      // translated node ID (tnid) doesn't match its own node ID.
      $node = menu_get_object();
      if ($node && translation_supported_type($node->type) && isset($node->tnid) && $node->tnid != $node->nid) {
        $source_node = node_load($node->tnid);
        $languages = language_list();
        $url_custom = drupal_to_js(url('node/' . $source_node->nid, array(
          'language' => $languages[$source_node->language],
        )));
      }
    }

    // Track access denied (403) and file not found (404) pages.
    if ($status == '403 Forbidden') {

      // See https://www.google.com/support/analytics/bin/answer.py?answer=86927
      $url_custom = '"/403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
    }
    elseif ($status == '404 Not Found') {
      $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
    }

    // Add custom dimensions and metrics.
    $custom_var = '';
    foreach (array(
      'dimension',
      'metric',
    ) as $googleanalytics_custom_type) {
      $googleanalytics_custom_vars = variable_get('googleanalytics_custom_' . $googleanalytics_custom_type, array());

      // Are there dimensions or metrics configured?
      if (!empty($googleanalytics_custom_vars)) {

        // Add all the configured variables to the content.
        foreach ($googleanalytics_custom_vars as $googleanalytics_custom_var) {
          if (module_exists('token')) {
            $types = array(
              'global' => NULL,
              'user' => $user,
            );
            $node = menu_get_object();
            if (is_object($node)) {
              $types += array(
                'node' => $node,
              );
            }
            $googleanalytics_custom_var['value'] = token_replace_multiple($googleanalytics_custom_var['value'], $types, '[', ']', array(
              'clear' => TRUE,
            ));
          }

          // Suppress empty custom names and/or variables.
          if (!drupal_strlen(trim($googleanalytics_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 ($googleanalytics_custom_type == 'dimension' && drupal_strlen($googleanalytics_custom_var['value']) > 150) {
            $googleanalytics_custom_var['value'] = substr($googleanalytics_custom_var['value'], 0, 150);
          }

          // Cast metric values for json_encode to data type numeric.
          if ($googleanalytics_custom_type == 'metric') {
            settype($googleanalytics_custom_var['value'], 'float');
          }
          $custom_var .= 'ga("set", ' . drupal_to_js($googleanalytics_custom_type . $googleanalytics_custom_var['index']) . ', ' . drupal_to_js($googleanalytics_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 = '//www.google-analytics.com/' . ($debug ? 'analytics_debug.js' : 'analytics.js');
    $library_cache_url = 'http:' . $library_tracker_url;

    // Should a local cached copy of analytics.js be used?
    if (variable_get('googleanalytics_cache', 0) && ($url = _googleanalytics_cache($library_cache_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 = '?' . substr(variable_get('css_js_query_string', '0'), 0, 1);
      $script .= '"' . $url . $query_string . '"';
    }
    else {
      $script .= '"' . $library_tracker_url . '"';
    }
    $script .= ',"ga");';

    // Add any custom code snippets if specified.
    $codesnippet_create = variable_get('googleanalytics_codesnippet_create', array());
    $codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
    $codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');

    // Build the create only fields list.
    $create_only_fields = array(
      'cookieDomain' => 'auto',
    );
    $create_only_fields = array_merge($create_only_fields, $codesnippet_create);

    // Domain tracking type.
    global $cookie_domain;
    $domain_mode = variable_get('googleanalytics_domain_mode', 0);
    $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, array(
        'cookieDomain' => $cookie_domain,
      ));
      $googleanalytics_adsense_script .= 'window.google_analytics_domain_name = ' . drupal_to_js($cookie_domain) . ';';
    }
    elseif ($domain_mode == 2) {

      // Cross Domain tracking. 'autoLinker' need to be enabled in 'create'.
      $create_only_fields = array_merge($create_only_fields, array(
        'allowLinker' => TRUE,
      ));
      $googleanalytics_adsense_script .= 'window.google_analytics_domain_name = "none";';
    }

    // Track logged in users across all devices.
    if (variable_get('googleanalytics_trackuserid', 0) && user_is_logged_in()) {

      // The USER_ID value should be a unique, persistent, and non-personally
      // identifiable string identifier that represents a user or signed-in
      // account across devices.
      $create_only_fields['userId'] = _googleanalytics_hmac_base64($user->uid, drupal_get_private_key() . _googleanalytics_get_hash_salt());
    }

    // Create a tracker.
    $script .= 'ga("create", ' . drupal_to_js($id) . ', ' . drupal_to_js($create_only_fields) . ');';

    // Prepare Adsense tracking.
    $googleanalytics_adsense_script .= 'window.google_analytics_uacct = ' . drupal_to_js($id) . ';';

    // Add enhanced link attribution after 'create', but before 'pageview' send.
    // @see https://support.google.com/analytics/answer/2558867
    if (variable_get('googleanalytics_tracklinkid', 0)) {
      $script .= 'ga("require", "linkid", "linkid.js");';
    }

    // Add display features after 'create', but before 'pageview' send.
    // @see https://support.google.com/analytics/answer/2444872
    if (variable_get('googleanalytics_trackdoubleclick', 0)) {
      $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", ' . drupal_to_js($link_settings['trackCrossDomains']) . ');';
    }
    if (variable_get('googleanalytics_tracker_anonymizeip', 1)) {
      $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 (variable_get('googleanalytics_trackadsense', FALSE)) {

      // Custom tracking. Prepend before all other JavaScript.
      // @TODO: https://support.google.com/adsense/answer/98142
      // sounds like it could be appended to $script.
      drupal_add_js($googleanalytics_adsense_script, 'inline', 'header');
    }
    drupal_add_js($script, 'inline', 'header');
  }
}