You are here

function statcounter_page_alter in StatCounter 7.2

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

File

./statcounter.module, line 73
Drupal Module: Statcounter Adds the required Javascript to the bottom of all your Drupal pages to allow tracking by the Statcounter statistics service.

Code

function statcounter_page_alter(&$page) {
  global $user;
  $id = variable_get('statcounter_project_id', '');
  $security_code = variable_get('statcounter_security_code', '');
  $invisibility = variable_get('statcounter_invisible_tracking', 1);

  // 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 statcounter 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) && (_statcounter_visibility_pages() || in_array($status, $trackable_status_codes)) && _statcounter_visibility_user($user)) {
    $scope = variable_get('statcounter_js_scope', 'footer');

    // Build tracker code.
    $inline_script = 'var sc_project=' . $id . ';';
    $inline_script .= 'var sc_invisible=' . $invisibility . ';';
    $inline_script .= 'var sc_security="' . $security_code . '";';

    // Should a local cached copy of the tracking code be used?
    if (variable_get('statcounter_cache', 0) && ($url = _statcounter_cache('http://www.statcounter.com/counter/counter_xhtml.js'))) {

      // 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');
      $file = $url . $query_string;
      $type = 'file';
    }
    else {
      $file = 'http://www.statcounter.com/counter/counter_xhtml.js';
      $type = 'external';
    }

    // Add tracker code to chosen region. We do not use drupal_add_js() here,
    // because it doesn't support regions as scope.
    $page[$scope]['statcounter']['first'] = array(
      '#markup' => $inline_script,
      '#prefix' => '<script type="text/javascript">',
      '#suffix' => '</script>',
    );
    $page[$scope]['statcounter']['second'] = array(
      '#markup' => "<script type=\"text/javascript\" src=\"{$file}\"></script>",
    );
    $page[$scope]['statcounter']['third'] = array(
      '#markup' => '<img class="statcounter" src="http://c.statcounter.com/' . $id . '/0/' . $security_code . '/' . $invisibility . '/" alt="drupal statistics" />',
      '#prefix' => '<noscript><div class="statcounter"><a title="drupal statistics" href="http://statcounter.com/drupal/">',
      '#suffix' => '</a></div></noscript>',
    );
  }
}