You are here

function googleanalytics_page_alter in Google Analytics 7

Same name and namespace in other branches
  1. 7.2 googleanalytics.module \googleanalytics_page_alter()

Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.

File

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

Code

function googleanalytics_page_alter(&$page) {
  global $user;
  $id = variable_get('googleanalytics_account', '');

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

  // 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.
  // 4. Ignore pages visibility filter for 404 or 403 status codes.
  if (!empty($id) && (_googleanalytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _googleanalytics_visibility_user($user)) {

    // We allow different scopes. Default to 'header' but allow user to override if they really need to.
    $scope = variable_get('googleanalytics_js_scope', 'header');

    // Add link tracking.
    $link_settings = array();
    if ($track_outbound = variable_get('googleanalytics_trackoutbound', 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'] = $track_domain_mode;
    }
    if ($track_cross_domains = variable_get('googleanalytics_cross_domains', '')) {
      $link_settings['trackCrossDomains'] = preg_split('/(\\r\\n?|\\n)/', $track_cross_domains);
    }
    if (!empty($link_settings)) {
      drupal_add_js(array(
        'googleanalytics' => $link_settings,
      ), 'setting');
      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) {
            $message_events .= '_gaq.push(["_trackEvent", ' . drupal_json_encode(t('Messages')) . ', ' . drupal_json_encode($status_heading[$type]) . ', ' . drupal_json_encode(strip_tags($message)) . ']);';
          }
        }
      }
    }

    // Site search tracking support.
    $url_custom = '';
    if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && ($keys = googleanalytics_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_json_encode(url('search/' . arg(1), array(
        'query' => array(
          'search' => $keys,
        ),
      ))) . ' : ' . drupal_json_encode(url('search/' . arg(1), array(
        'query' => array(
          'search' => 'no-results:' . $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) && !empty($node->tnid) && $node->tnid != $node->nid) {
        $source_node = node_load($node->tnid);
        $languages = language_list();
        $url_custom = drupal_json_encode(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 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 ($status == '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;
        $types = array();
        $node = menu_get_object();
        if (is_object($node)) {
          $types += array(
            'node' => $node,
          );
        }
        $custom_var_name = token_replace($custom_var_name, $types, array(
          'clear' => TRUE,
        ));
        $custom_var_value = token_replace($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_json_encode($custom_var_name);
        $custom_var_value = drupal_json_encode($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 || [];';

    // Add enhanced link attribution before '_trackPageview'.
    // @see https://support.google.com/analytics/answer/2558867
    if (variable_get('googleanalytics_tracklinkid', 0)) {
      $script .= 'var pluginUrl = "//www.google-analytics.com/plugins/ga/inpage_linkid.js";';
      $script .= '_gaq.push(["_require", "inpage_linkid", pluginUrl]);';
    }
    $script .= '_gaq.push(["_setAccount", ' . drupal_json_encode($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"]);';
    }

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

    // 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_json_encode($cookie_domain) . ']);';
      $googleanalytics_adsense_script .= 'window.google_analytics_domain_name = ' . drupal_json_encode($cookie_domain) . ';';
    }
    elseif ($domain_mode == 2) {
      $script .= '_gaq.push(["_setDomainName", "none"]);';
      $script .= '_gaq.push(["_setAllowLinker", true]);';
      $googleanalytics_adsense_script .= 'window.google_analytics_domain_name = "none";';
    }
    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($message_events)) {
      $script .= $message_events;
    }
    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 = '?' . variable_get('css_js_query_string', '0');
      $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 .= '})();';
    if (variable_get('googleanalytics_trackadsense', FALSE)) {

      // Custom tracking. Prepend before all other JavaScript.
      // @TODO: http://support.google.com/adsense/bin/answer.py?answer=98142
      // sounds like it could be appended to $script.
      drupal_add_js($googleanalytics_adsense_script, array(
        'type' => 'inline',
        'group' => JS_LIBRARY - 1,
      ));
    }
    drupal_add_js($script, array(
      'scope' => $scope,
      'type' => 'inline',
    ));
  }
}