You are here

function googleanalytics_footer in Google Analytics 6.3

Same name and namespace in other branches
  1. 5 googleanalytics.module \googleanalytics_footer()
  2. 6 googleanalytics.module \googleanalytics_footer()
  3. 6.2 googleanalytics.module \googleanalytics_footer()

Implementation of hook_footer() to insert JavaScript at the end of the page.

File

./googleanalytics.module, line 124
Drupal Module: GoogleAnalytics Adds the required Javascript to the bottom of all your Drupal pages to allow tracking by the Google Analytics statistics package.

Code

function googleanalytics_footer($main = 0) {
  global $user;
  $id = variable_get('googleanalytics_account', '');

  // 1. Check if the GA account number has a value.
  // 2. Track page views based on visibility value.
  // 3. Check if we should track the currently active user's role.
  if (!empty($id) && _googleanalytics_visibility_pages() && _googleanalytics_visibility_user($user)) {

    // Site search tracking support.
    $url_custom = '';
    if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && ($keys = search_get_keys())) {
      $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.
    $headers = drupal_get_headers();
    if (strstr($headers, '403 Forbidden')) {

      // See http://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 (strstr($headers, '404 Not Found')) {
      $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
    }

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

    // Add custom variables.
    $googleanalytics_custom_vars = variable_get('googleanalytics_custom_var', array());
    $custom_var = '';
    for ($i = 1; $i < 6; $i++) {
      $custom_var_name = !empty($googleanalytics_custom_vars['slots'][$i]['name']) ? $googleanalytics_custom_vars['slots'][$i]['name'] : '';
      if (!empty($custom_var_name)) {
        $custom_var_value = !empty($googleanalytics_custom_vars['slots'][$i]['value']) ? $googleanalytics_custom_vars['slots'][$i]['value'] : '';
        $custom_var_scope = !empty($googleanalytics_custom_vars['slots'][$i]['scope']) ? $googleanalytics_custom_vars['slots'][$i]['scope'] : 3;
        if (module_exists('token')) {
          $types = array(
            'global' => NULL,
            'user' => $user,
          );
          $node = menu_get_object();
          if (is_object($node)) {
            $types += array(
              'node' => $node,
            );
          }
          $custom_var_name = token_replace_multiple($custom_var_name, $types, '[', ']', array(
            'clear' => TRUE,
          ));
          $custom_var_value = token_replace_multiple($custom_var_value, $types, '[', ']', array(
            'clear' => TRUE,
          ));
        }

        // Suppress empty custom names and/or variables.
        if (!drupal_strlen(trim($custom_var_name)) || !drupal_strlen(trim($custom_var_value))) {
          continue;
        }

        // The length of the string used for the 'name' and the length of the
        // string used for the 'value' must not exceed 128 bytes after url encoding.
        $name_length = drupal_strlen(rawurlencode($custom_var_name));
        $tmp_value = rawurlencode($custom_var_value);
        $value_length = drupal_strlen($tmp_value);
        if ($name_length + $value_length > 128) {

          // Trim value and remove fragments of url encoding.
          $tmp_value = rtrim(substr($tmp_value, 0, 127 - $name_length), '%0..9A..F');
          $custom_var_value = urldecode($tmp_value);
        }
        $custom_var_name = drupal_to_js($custom_var_name);
        $custom_var_value = drupal_to_js($custom_var_value);
        $custom_var .= "_gaq.push(['_setCustomVar', {$i}, {$custom_var_name}, {$custom_var_value}, {$custom_var_scope}]);";
      }
    }

    // Build tracker code.
    $script = 'var _gaq = _gaq || [];';
    $script .= '_gaq.push(["_setAccount", ' . drupal_to_js($id) . ']);';
    if (variable_get('googleanalytics_tracker_anonymizeip', 0)) {

      // FIXME: The Google API is currently broken and "_gat._anonymizeIp" is only
      // a workaround until "_anonymizeIp" has been implemented/fixed.
      $script .= '_gaq.push(["_gat._anonymizeIp"]);';
    }

    // Domain tracking type.
    global $cookie_domain;
    $domain_mode = variable_get('googleanalytics_domain_mode', 0);

    // 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))) {
      $script .= '_gaq.push(["_setDomainName", ' . drupal_to_js($cookie_domain) . ']);';
    }
    if (!empty($custom_var)) {
      $script .= $custom_var;
    }
    if (!empty($codesnippet_before)) {
      $script .= $codesnippet_before;
    }
    if (empty($url_custom)) {
      $script .= '_gaq.push(["_trackPageview"]);';
    }
    else {
      $script .= '_gaq.push(["_trackPageview", ' . $url_custom . ']);';
    }
    if (!empty($codesnippet_after)) {
      $script .= $codesnippet_after;
    }
    $script .= '(function() {';
    $script .= 'var ga = document.createElement("script");';
    $script .= 'ga.type = "text/javascript";';
    $script .= 'ga.async = true;';

    // Which version of the tracking library should be used?
    if ($trackdoubleclick = variable_get('googleanalytics_trackdoubleclick', FALSE)) {
      $library_tracker_url = 'stats.g.doubleclick.net/dc.js';
      $library_cache_url = 'http://' . $library_tracker_url;
    }
    else {
      $library_tracker_url = '.google-analytics.com/ga.js';
      $library_cache_url = 'http://www' . $library_tracker_url;
    }

    // Should a local cached copy of ga.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 .= 'ga.src = "' . $url . $query_string . '";';
    }
    else {

      // Library paths do not follow the same naming convention.
      if ($trackdoubleclick) {
        $script .= 'ga.src = ("https:" == document.location.protocol ? "https://" : "http://") + "' . $library_tracker_url . '";';
      }
      else {
        $script .= 'ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + "' . $library_tracker_url . '";';
      }
    }
    $script .= 'var s = document.getElementsByTagName("script")[0];';
    $script .= 's.parentNode.insertBefore(ga, s);';
    $script .= '})();';
    drupal_add_js($script, 'inline', 'footer');
  }
}