<?php
// $Id: googleanalytics.module,v 1.9.2.2 2006/09/12 17:49:41 budda Exp $
/*
 * Drupal Module: GoogleAnalytics
 * Adds the required Javascript to the bottom of all your Drupal pages
 * to allow tracking by the Google Analytics statistics package.
 *
 * @author: Mike Carter <www.ixis.co.uk/contact>
 */


function googleanalytics_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      return t('Adds tracking code to all pages of your site');
    case 'admin/settings/googleanalytics':
      return t('Google Analytics is a free statistics package based on the excellent Urchin system.');
  }
}

/**
 * Implementation of hook_footer()  to insert Javascript at the end of the page
 */
function googleanalytics_footer($main = 0) {
  global $user;

  $id = variable_get('googleanalytics_account', '');

  // Check if we should track the currently active user's role
  $track = 0;
  foreach($user->roles as $role) {
    $track += variable_get("googleanalytics_track_{$role}", FALSE);
  }

  // Don't track page views in the admin sections
  if($id && (arg(0) != 'admin') && $track > 0) {

    $prefix = '://www';

    // Are we on a secure page?
    if($_SERVER['HTTPS']) {
      $prefix = 's://ssl';
    }

    // Add User profile segmentation values
    if(is_array($profile_fields = variable_get('googleanalytics_segmentation', '')) && ($user->uid > 0)) {;

      $p = profile_load_profile($user);

      $fields = array();
      foreach($profile_fields as $field => $title) {
        $value = $user->$field;

        if(is_array($value)) {
          $value = implode('.', $value);
        }

        $fields[$field] = $value;
      }
      $segmentation = "__utmSetVar('".implode(':', $fields)."');";
		}
		
		// Add any custom code snippets if specified
		$codesnippet = variable_get('googleanalytics_codesnippet', '');
		
    return '<script type="text/javascript" src="http' . $prefix . '.google-analytics.com/urchin.js"></script><script type="text/javascript">_uacct = "'.$id."\";{$segmentation}{$codesnippet}urchinTracker();</script>";
  }
  
}


/**
 * Implementation of hook_settings() for configuring the module
 */
function googleanalytics_settings() {
  $form['account'] = array(
        '#type' => 'fieldset',
        '#title' => t('Analytics Account Settings'),
        '#collapsible' => FALSE,
      );

  $form['account']['googleanalytics_account'] = array(
      '#type' => 'textfield',
      '#title' => t('User ID'),
      '#default_value' => variable_get('googleanalytics_account','UA-'),
      '#size' => 15,
      '#maxlength' => 20,
      '#required' => TRUE,
      '#description' => t('The user account is unique to the websites domain. You can obtain a user account from the %url website.', array('%url' => '<a href="http://www.google.com/analytics/">Google Analytics</a>'))
    );

   // Render the role overview.
  $result = db_query('SELECT * FROM {role} ORDER BY name');

  $form['roles'] = array(
        '#type' => 'fieldset',
        '#title' => t('User Role Tracking'),
        '#collapsible' => TRUE,
        '#description' => t('Define what user roles should be tracked by Google Analytics.')
  );

  while ($role = db_fetch_object($result)) {
    $form['roles']["googleanalytics_track_{$role->name}"] = array(
      '#type' => 'checkbox',
      '#title' => t($role->name),
      '#default_value' => variable_get("googleanalytics_track_{$role->name}", FALSE),
    );
  }

  $form['segmentation'] = array(
        '#type' => 'fieldset',
        '#title' => t('User Segmentation'),
        '#collapsible' => TRUE,
        '#description' => t('If your users have profile fields completed, you can track your logged in users based on a defined profile field.')
  );

  if(!module_exist('profile')) {
    $form['segmentation']['profile'] = array(
          '#value' => t('You need to activate the %profile to use this feature.', array('%profile' => l('profile.module', 'admin/modules')) )
    );
  } else {
    // Compile a list of fields to show.
    $fields = array('uid' => 'User ID', 'name' => 'Username');
    $result = db_query('SELECT name, title, type, weight FROM {profile_fields} ORDER BY weight');
    while ($record = db_fetch_object($result)) {
      $fields[$record->name] = $record->title;
    }

    $form['segmentation']["googleanalytics_segmentation"] = array(
      '#type' => 'select',
      '#title' => t('Track'),
      '#description' => t('Selecting one or more values allows you to track users by profile values rather than simply an IP address.'),
      '#default_value' => variable_get("googleanalytics_segmentation", ''),
      '#options' => $fields,
      '#size' => 10,
      '#multiple' => TRUE
    );
  }
  
  $form['advanced'] = array(
        '#type' => 'fieldset',
        '#title' => t('Advanced'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#description' => t('You can add custom Google Analytic code here.')
  );
  $form['advanced']['googleanalytics_codesnippet'] = array(
      '#type' => 'textarea',
      '#title' => t('JavaScript Code'),
      '#default_value' => variable_get('googleanalytics_codesnippet',''),
      '#rows' => 15,
      '#description' => t('Paste %snippets here. These will be added to every page that Google Analytics appears on. For help with this feature see the %blog. <strong>Do not include the &lt;script&gt; tags</strong>, and always end your code with a semicolon (;).', array('%snippets' => l(t('custom code snippets'), 'http://drupal.org/node/39282'), '%blog' => l(t('cutroni.com blog'), 'http://cutroni.com/blog/') ) )
  );
    
  return $form;
}
?>