Commit 8a74b59b authored by Riccardo Padovani's avatar Riccardo Padovani

Added Google Analytics module

parent 452f25e9
This diff is collapsed.
Module: Google Analytics
Author: Alexander Hass <http://drupal.org/user/85918>
Description
===========
Adds the Google Analytics tracking system to your website.
Requirements
============
* Google Analytics user account
Installation
============
* Copy the 'googleanalytics' module directory in to your Drupal
sites/all/modules directory as usual.
Usage
=====
In the settings page enter your Google Analytics account number.
All pages will now have the required JavaScript added to the
HTML footer can confirm this by viewing the page source from
your browser.
New approach to page tracking in 5.x-1.5 and 6.x-1.1
====================================================
With 5.x-1.5 and 6.x-1.1 there are new settings on the settings page at
admin/config/system/googleanalytics. The "Page specific tracking" area now
comes with an interface that copies Drupal's block visibility settings.
The default is set to "Add to every page except the listed pages". By
default the following pages are listed for exclusion:
admin
admin/*
batch
node/add*
node/*/*
user/*/*
These defaults are changeable by the website administrator or any other
user with 'administer google analytics' permission.
Like the blocks visibility settings in Drupal core, there is now a
choice for "Add if the following PHP code returns TRUE." Sample PHP snippets
that can be used in this textarea can be found on the handbook page
"Overview-approach to block visibility" at http://drupal.org/node/64135.
Custom variables
=================
One example for custom variables tracking is the "User roles" tracking. Enter
the below configuration data into the custom variables settings form under
admin/config/system/googleanalytics.
Slot: 1
Name: User roles
Value: [current-user:role-names]
Scope: Visitor
More details about Custom variables can be found in the Google API documentation at
http://code.google.com/intl/en/apis/analytics/docs/tracking/gaTrackingCustomVariables.html
Advanced Settings
=================
You can include additional JavaScript snippets in the custom javascript
code textarea. These can be found on the official Google Analytics pages
and a few examples at http://drupal.org/node/248699. Support is not
provided for any customisations you include.
To speed up page loading you may also cache the Analytics ga.js
file locally.
This diff is collapsed.
(function ($) {
/**
* Provide the summary information for the tracking settings vertical tabs.
*/
Drupal.behaviors.trackingSettingsSummary = {
attach: function (context) {
// Make sure this behavior is processed only if drupalSetSummary is defined.
if (typeof jQuery.fn.drupalSetSummary == 'undefined') {
return;
}
$('fieldset#edit-page-vis-settings', context).drupalSetSummary(function (context) {
var $radio = $('input[name="googleanalytics_visibility_pages"]:checked', context);
if ($radio.val() == 0) {
if (!$('textarea[name="googleanalytics_pages"]', context).val()) {
return Drupal.t('Not restricted');
}
else {
return Drupal.t('All pages with exceptions');
}
}
else {
return Drupal.t('Restricted to certain pages');
}
});
$('fieldset#edit-role-vis-settings', context).drupalSetSummary(function (context) {
var vals = [];
$('input[type="checkbox"]:checked', context).each(function () {
vals.push($.trim($(this).next('label').text()));
});
if (!vals.length) {
return Drupal.t('Not restricted');
}
else if ($('input[name="googleanalytics_visibility_roles"]:checked', context).val() == 1) {
return Drupal.t('Excepted: @roles', {'@roles' : vals.join(', ')});
}
else {
return vals.join(', ');
}
});
$('fieldset#edit-user-vis-settings', context).drupalSetSummary(function (context) {
var $radio = $('input[name="googleanalytics_custom"]:checked', context);
if ($radio.val() == 0) {
return Drupal.t('Not customizable');
}
else if ($radio.val() == 1) {
return Drupal.t('On by default with opt out');
}
else {
return Drupal.t('Off by default with opt in');
}
});
$('fieldset#edit-linktracking', context).drupalSetSummary(function (context) {
var vals = [];
if ($('input#edit-googleanalytics-trackoutbound', context).is(':checked')) {
vals.push(Drupal.t('Outbound links'));
}
if ($('input#edit-googleanalytics-trackmailto', context).is(':checked')) {
vals.push(Drupal.t('Mailto links'));
}
if ($('input#edit-googleanalytics-trackfiles', context).is(':checked')) {
vals.push(Drupal.t('Downloads'));
}
if (!vals.length) {
return Drupal.t('Not tracked');
}
return Drupal.t('@items enabled', {'@items' : vals.join(', ')});
});
$('fieldset#edit-messagetracking', context).drupalSetSummary(function (context) {
var vals = [];
$('input[type="checkbox"]:checked', context).each(function () {
vals.push($.trim($(this).next('label').text()));
});
if (!vals.length) {
return Drupal.t('Not tracked');
}
return Drupal.t('@items enabled', {'@items' : vals.join(', ')});
});
$('fieldset#edit-search-and-advertising', context).drupalSetSummary(function (context) {
var vals = [];
if ($('input#edit-googleanalytics-site-search', context).is(':checked')) {
vals.push(Drupal.t('Site search'));
}
if ($('input#edit-googleanalytics-trackadsense', context).is(':checked')) {
vals.push(Drupal.t('AdSense ads'));
}
if ($('input#edit-googleanalytics-trackdoubleclick', context).is(':checked')) {
vals.push(Drupal.t('DoubleClick data'));
}
if (!vals.length) {
return Drupal.t('Not tracked');
}
return Drupal.t('@items enabled', {'@items' : vals.join(', ')});
});
$('fieldset#edit-domain-tracking', context).drupalSetSummary(function (context) {
var $radio = $('input[name="googleanalytics_domain_mode"]:checked', context);
if ($radio.val() == 0) {
return Drupal.t('A single domain');
}
else if ($radio.val() == 1) {
return Drupal.t('One domain with multiple subdomains');
}
else {
return Drupal.t('Multiple top-level domains');
}
});
$('fieldset#edit-privacy', context).drupalSetSummary(function (context) {
var vals = [];
if ($('input#edit-googleanalytics-tracker-anonymizeip', context).is(':checked')) {
vals.push(Drupal.t('Anonymize IP'));
}
if ($('input#edit-googleanalytics-privacy-donottrack', context).is(':checked')) {
vals.push(Drupal.t('Universal web tracking opt-out'));
}
if (!vals.length) {
return Drupal.t('No privacy');
}
return Drupal.t('@items enabled', {'@items' : vals.join(', ')});
});
}
};
})(jQuery);
name = Google Analytics
description = Allows your site to be tracked by Google Analytics by adding a Javascript tracking code to every page.
core = 7.x
package = Statistics
configure = admin/config/system/googleanalytics
files[] = googleanalytics.test
test_dependencies[] = token
; Information added by drupal.org packaging script on 2013-10-17
version = "7.x-1.4"
core = "7.x"
project = "google_analytics"
datestamp = "1382021586"
This diff is collapsed.
(function ($) {
$(document).ready(function() {
// Expression to check for absolute internal links.
var isInternal = new RegExp("^(https?):\/\/" + window.location.host, "i");
// Attach onclick event to document only and catch clicks on all elements.
$(document.body).click(function(event) {
// Catch the closest surrounding link of a clicked element.
$(event.target).closest("a,area").each(function() {
var ga = Drupal.settings.googleanalytics;
// Expression to check for special links like gotwo.module /go/* links.
var isInternalSpecial = new RegExp("(\/go\/.*)$", "i");
// Expression to check for download links.
var isDownload = new RegExp("\\.(" + ga.trackDownloadExtensions + ")$", "i");
// Is the clicked URL internal?
if (isInternal.test(this.href)) {
// Skip 'click' tracking, if custom tracking events are bound.
if ($(this).is('.colorbox')) {
// Do nothing here. The custom event will handle all tracking.
}
// Is download tracking activated and the file extension configured for download tracking?
else if (ga.trackDownload && isDownload.test(this.href)) {
// Download link clicked.
var extension = isDownload.exec(this.href);
_gaq.push(["_trackEvent", "Downloads", extension[1].toUpperCase(), this.href.replace(isInternal, '')]);
}
else if (isInternalSpecial.test(this.href)) {
// Keep the internal URL for Google Analytics website overlay intact.
_gaq.push(["_trackPageview", this.href.replace(isInternal, '')]);
}
}
else {
if (ga.trackMailto && $(this).is("a[href^='mailto:'],area[href^='mailto:']")) {
// Mailto link clicked.
_gaq.push(["_trackEvent", "Mails", "Click", this.href.substring(7)]);
}
else if (ga.trackOutbound && this.href.match(/^\w+:\/\//i)) {
if (ga.trackDomainMode == 2 && isCrossDomain(this.hostname, ga.trackCrossDomains)) {
// Top-level cross domain clicked. document.location is handled by _link internally.
event.preventDefault();
_gaq.push(["_link", this.href]);
}
else {
// External link clicked.
_gaq.push(["_trackEvent", "Outbound links", "Click", this.href]);
}
}
}
});
});
// Colorbox: This event triggers when the transition has completed and the
// newly loaded content has been revealed.
$(document).bind("cbox_complete", function() {
var href = $.colorbox.element().attr("href");
if (href) {
_gaq.push(["_trackPageview", href.replace(isInternal, '')]);
}
});
});
/**
* Check whether the hostname is part of the cross domains or not.
*
* @param string hostname
* The hostname of the clicked URL.
* @param array crossDomains
* All cross domain hostnames as JS array.
*
* @return boolean
*/
function isCrossDomain(hostname, crossDomains) {
/**
* jQuery < 1.6.3 bug: $.inArray crushes IE6 and Chrome if second argument is
* `null` or `undefined`, http://bugs.jquery.com/ticket/10076,
* https://github.com/jquery/jquery/commit/a839af034db2bd934e4d4fa6758a3fed8de74174
*
* @todo: Remove/Refactor in D8
*/
if (!crossDomains) {
return false;
}
else {
return $.inArray(hostname, crossDomains) > -1 ? true : false;
}
}
})(jQuery);
This diff is collapsed.
This diff is collapsed.
<?php
/**
* @file
* Builds placeholder replacement tokens for user-related data.
*/
/**
* Implements hook_token_info().
*/
function googleanalytics_token_info() {
$user['role-names'] = array(
'name' => t('User role names'),
'description' => t('The role names the user account is a member of as comma separated list.'),
'needs-data' => 'user',
);
$user['role-ids'] = array(
'name' => t('User role ids'),
'description' => t('The role ids the user account is a member of as comma separated list.'),
'needs-data' => 'user',
);
return array(
'tokens' => array('user' => $user),
);
}
/**
* Implements hook_tokens().
*/
function googleanalytics_tokens($type, $tokens, array $data = array(), array $options = array()) {
$sanitize = !empty($options['sanitize']);
$replacements = array();
if ($type == 'user' && !empty($data['user']->roles)) {
$account = $data['user'];
foreach ($tokens as $name => $original) {
switch ($name) {
// Basic user account information.
case 'role-names':
$names = implode(',', $account->roles);
$replacements[$original] = $sanitize ? check_plain($names) : $names;
break;
case 'role-ids':
$ids = implode(',', array_keys($account->roles));
$replacements[$original] = $sanitize ? check_plain($ids) : $ids;
break;
}
}
}
return $replacements;
}
<?php
/**
* @file
* Definition of variables for Variable API module.
*/
/**
* Implements hook_variable_info().
*/
function googleanalytics_variable_info($options) {
$variables['googleanalytics_account'] = array(
'type' => 'string',
'title' => t('Web Property ID', array(), $options),
'default' => 'UA-',
'description' => t('This ID is unique to each site you want to track separately, and is in the form of UA-xxxxxxx-yy. To get a Web Property ID, <a href="@analytics">register your site with Google Analytics</a>, or if you already have registered your site, go to your Google Analytics Settings page to see the ID next to every site profile. <a href="@webpropertyid">Find more information in the documentation</a>.', array('@analytics' => 'http://www.google.com/analytics/', '@webpropertyid' => url('https://developers.google.com/analytics/resources/concepts/gaConceptsAccounts', array('fragment' => 'webProperty'))), $options),
'required' => TRUE,
'group' => 'googleanalytics',
'localize' => TRUE,
'multidomain' => TRUE,
'validate callback' => 'googleanalytics_validate_googleanalytics_account',
);
return $variables;
}
/**
* Implements hook_variable_group_info().
*/
function googleanalytics_variable_group_info() {
$groups['googleanalytics'] = array(
'title' => t('Google Analytics'),
'description' => t('Configure tracking behavior to get insights into your website traffic and marketing effectiveness.'),
'access' => 'administer google analytics',
'path' => array('admin/config/system/googleanalytics'),
);
return $groups;
}
/**
* Validate Web Property ID variable.
*/
function googleanalytics_validate_googleanalytics_account($variable) {
// Replace all type of dashes (n-dash, m-dash, minus) with the normal dashes.
$variable['value'] = str_replace(array('–', '—', '−'), '-', $variable['value']);
if (!preg_match('/^UA-\d{4,}-\d+$/', $variable['value'])) {
return t('A valid Google Analytics Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy.');
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment