6 * Drupal Module: GoogleAnalytics
7 * Adds the required Javascript to the bottom of all your Drupal pages
8 * to allow tracking by the Google Analytics statistics package.
10 * @author: Mike Carter <www.ixis.co.uk/contact>
13 define('GA_TRACKFILES_EXTENSIONS', '7z|aac|arc|arj|asf|asx|avi|bin|csv|doc|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls|xml|z|zip');
15 function googleanalytics_help($path, $arg) {
17 case
'admin/settings/googleanalytics':
18 return t('<a href="@ga_url">Google Analytics</a> is a free statistics package based on the excellent Urchin system. This module provides services to better integrate Drupal with Google Analytics.', array('@ga_url' => 'http://www.google.com/analytics/'));
22 function googleanalytics_perm() {
24 'administer google analytics' => array(
25 'title' => t('Administer Google Analytics'),
26 'description' => t('Perform maintenance tasks for Google Analytics.'),
28 'opt-in or out of tracking' => array(
29 'title' => t('Opt-in or out of tracking'),
30 'description' => t('Allow users to decide if tracking code will be added to pages or not.'),
32 'use PHP for tracking visibility' => array(
33 'title' => t('Use PHP for tracking visibility'),
34 'description' => t('Enter PHP code in the field for tracking visibility settings. %warning', array('%warning' => t('Warning: Give to trusted roles only; this permission has security implications.'))),
39 function googleanalytics_menu() {
40 $items['admin/settings/googleanalytics'] = array(
41 'title' => 'Google Analytics',
42 'description' => 'Configure the settings used to generate your Google Analytics tracking code.',
43 'page callback' => 'drupal_get_form',
44 'page arguments' => array('googleanalytics_admin_settings_form'),
45 'access arguments' => array('administer google analytics'),
46 'type' => MENU_NORMAL_ITEM
,
52 function googleanalytics_init() {
55 $id = variable_get('googleanalytics_account', '');
57 // 1. Check if the GA account number has a value.
58 // 2. Track page views based on visibility value.
59 // 3. Check if we should track the currently active user's role.
60 if (!empty($id) && _googleanalytics_visibility_pages() && _googleanalytics_visibility_user($user)) {
61 $scope = variable_get('googleanalytics_js_scope', 'footer');
63 // Should a local cached copy of ga.js be used?
65 $url = 'http://www.google-analytics.com/'.
$js_file;
67 if (variable_get('googleanalytics_cache', 0) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC
) == FILE_DOWNLOADS_PUBLIC
) && $source = _googleanalytics_cache($url)) {
68 drupal_add_js($source, array('type' => 'file', 'scope' => $scope));
71 $script = 'var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");';
72 $script .
= 'document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/'.
$js_file .
'\' type=\'text/javascript\'%3E%3C/script%3E"));';
73 drupal_add_js($script, array('type' => 'inline', 'scope' => $scope, 'weight' => JS_DEFAULT
- 1));
77 $link_settings = array();
78 if ($track_outgoing = variable_get('googleanalytics_trackoutgoing', 1)) {
79 $link_settings['trackOutgoing'] = $track_outgoing;
81 if ($track_mailto = variable_get('googleanalytics_trackmailto', 1)) {
82 $link_settings['trackMailto'] = $track_mailto;
84 if (($track_download = variable_get('googleanalytics_trackfiles', 1)) && ($trackfiles_extensions = variable_get('googleanalytics_trackfiles_extensions', GA_TRACKFILES_EXTENSIONS
))) {
85 $link_settings['trackDownload'] = $track_download;
86 $link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
88 if (!empty($link_settings)) {
89 drupal_add_js(array('googleanalytics' => $link_settings), array('type' => 'setting', 'scope' => 'header'));
90 drupal_add_js(drupal_get_path('module', 'googleanalytics') .
'/googleanalytics.js', array('type' => 'file', 'scope' => $scope));
94 if (variable_get('googleanalytics_trackadsense', FALSE
)) {
95 drupal_add_js('window.google_analytics_uacct = ' .
drupal_to_js($id) .
';', 'inline', 'header');
101 * Implementation of hook_footer() to insert Javascript at the end of the page.
103 function googleanalytics_footer($main = 0) {
106 $id = variable_get('googleanalytics_account', '');
108 if (!empty($id) && _googleanalytics_visibility_pages() && _googleanalytics_visibility_user($user)) {
110 // Add User profile segmentation values.
111 if (is_array($profile_fields = variable_get('googleanalytics_segmentation', '')) && ($user->uid
> 0)) {
113 $p = module_invoke('profile', 'load_profile', $user);
116 foreach ($profile_fields as
$field => $title) {
117 $value = $user->$field;
119 if (is_array($value)) {
120 $value = implode(',', $value);
123 $fields[$field] = $value;
126 // Only show segmentation variable if there are specified fields.
128 if (count($fields) > 0) {
129 $segmentation = 'pageTracker._setVar('.
drupal_to_js(implode(':', $fields)) .
');';
133 // Site search tracking support.
135 if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE
) && arg(0) == 'search' && $keys = search_get_keys()) {
136 $url_custom = drupal_to_js(url('search/'.
arg(1), array('query' => 'search='.
$keys)));
139 // If this node is a translation of another node, pass the original
141 if (module_exists('translation') && variable_get('googleanalytics_translation_set', 0)) {
142 // Check we have a node object, it supports translation, and its
143 // translated node ID (tnid) doesn't match its own node ID.
144 $node = menu_get_object();
145 if ($node && translation_supported_type($node->type
) && isset($node->tnid
) && ($node->tnid
!= $node->nid
)) {
146 $source_node = node_load($node->tnid
);
147 $languages = language_list();
148 $url_custom = drupal_to_js(url('node/'.
$source_node->nid
, array('language' => $languages[$source_node->language
])));
152 // Track access denied (403) and file not found (404) pages.
153 if (function_exists('drupal_get_headers')) {
154 $headers = drupal_get_headers();
155 if (strstr($headers, 'HTTP/1.1 403 Forbidden')) {
156 // See http://www.google.com/support/analytics/bin/answer.py?answer=86927
157 $url_custom = '"/403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
159 elseif (strstr($headers, 'HTTP/1.1 404 Not Found')) {
160 $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
164 // Add any custom code snippets if specified.
165 $codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
166 $codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');
168 // Build tracker code for footer.
170 $script .
= 'var pageTracker = _gat._getTracker('.
drupal_to_js($id) .
');';
171 if (!empty($segmentation)) {
172 $script .
= $segmentation;
174 if (!empty($codesnippet_before)) {
175 $script .
= $codesnippet_before;
177 $script .
= 'pageTracker._trackPageview('.
$url_custom .
');';
178 if (!empty($codesnippet_after)) {
179 $script .
= $codesnippet_after;
181 $script .
= '} catch(err) {}';
183 drupal_add_js($script, array('type' => 'inline', 'scope' => 'footer'));
188 * Implementation of hook_user().
190 * Allow users to decide if tracking code will be added to pages or not.
192 function googleanalytics_user_form(&$edit, &$account, $category = NULL
) {
193 if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('googleanalytics_custom', 0)) != 0 && _googleanalytics_visibility_roles($account)) {
194 $form['googleanalytics'] = array(
195 '#type' => 'fieldset',
196 '#title' => t('Google Analytics configuration'),
198 '#collapsible' => TRUE
,
204 $description = t('Users are tracked by default, but you are able to opt out.');
208 $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
212 $form['googleanalytics']['custom'] = array(
213 '#type' => 'checkbox',
214 '#title' => t('Enable user tracking'),
215 '#description' => $description,
216 '#default_value' => isset($account->googleanalytics
['custom']) ?
$account->googleanalytics
['custom'] : ($custom == 1)
224 * Implementation of hook_requirements().
226 function googleanalytics_requirements($phase) {
227 $requirements = array();
229 if ($phase == 'runtime') {
230 // Raise warning if Google user account has not been set yet.
231 if (!preg_match('/^UA-\d{4,}-\d+$/', variable_get('googleanalytics_account', 'UA-'))) {
232 $requirements['googleanalytics'] = array(
233 'title' => t('Google Analytics module'),
234 'description' => t('Google Analytics module has not been configured yet. Please configure its settings from the <a href="@url">Google Analytics settings page</a>.', array('@url' => url('admin/settings/googleanalytics'))),
235 'severity' => REQUIREMENT_ERROR
,
236 'value' => t('Not configured'),
241 return $requirements;
245 * Implementation of hook_cron().
247 function googleanalytics_cron() {
248 // Regenerate the google analytics ga.js every day.
249 if (time() - variable_get('googleanalytics_last_cache', 0) >= 86400) {
250 // New google analytics version.
251 file_unmanaged_delete(file_directory_path() .
'/googleanalytics/ga.js');
253 // Clear aggregated JS files.
254 if (variable_get('preprocess_js', 0)) {
255 drupal_clear_js_cache();
258 variable_set('googleanalytics_last_cache', time());
263 * Download and cache the ga.js file locally.
265 * The full URL to the external javascript file.
267 * The path to the local javascript file on success, boolean FALSE on failure.
269 function _googleanalytics_cache($location) {
270 $directory = file_directory_path() .
'/googleanalytics';
271 $file_destination = $directory .
'/'.
basename($location);
272 if (!file_exists($file_destination)) {
273 $result = drupal_http_request($location);
274 if ($result->code
== 200) {
275 // Check that the files directory is writable
276 if (file_check_directory($directory, FILE_CREATE_DIRECTORY
)) {
277 return file_unmanaged_save_data($result->data
, $directory .
'/'.
basename($location), FILE_EXISTS_REPLACE
);
282 return $file_destination;
287 * Tracking visibility check for an user object.
290 * A user object containing an array of roles to check.
292 * A decision on if the current user is being tracked by Google Analytics.
294 function _googleanalytics_visibility_user($account) {
298 // Is current user a member of a role that should be tracked?
299 if (_googleanalytics_visibility_roles($account)) {
301 // Use the user's block visibility setting, if necessary.
302 if (($custom = variable_get('googleanalytics_custom', 0)) != 0) {
303 if ($account->uid
&& isset($account->googleanalytics
['custom'])) {
304 $enabled = $account->googleanalytics
['custom'];
307 $enabled = ($custom == 1);
320 * Based on visibility setting this function returns TRUE if GA code should
321 * be added for the current role and otherwise FALSE.
323 function _googleanalytics_visibility_roles($account) {
326 $roles = variable_get('googleanalytics_roles', array());
328 if (array_sum($roles) > 0) {
329 // One or more roles are selected for tracking.
330 foreach (array_keys($account->roles
) as
$rid) {
331 // Is the current user a member of one role enabled for tracking?
332 if (isset($roles[$rid]) && $rid == $roles[$rid]) {
333 // Current user is a member of a role that should be tracked.
340 // No role is selected for tracking, therefor all roles should be tracked.
348 * Based on visibility setting this function returns TRUE if GA code should
349 * be added to the current page and otherwise FALSE.
351 function _googleanalytics_visibility_pages() {
354 // Cache visibility setting in hook_init for hook_footer.
355 if (!isset($page_match)) {
357 $visibility = variable_get('googleanalytics_visibility', 0);
358 $pages = variable_get('googleanalytics_pages', '');
360 // Match path if necessary.
361 if (!empty($pages)) {
362 if ($visibility < 2) {
363 $path = drupal_get_path_alias($_GET['q']);
364 // Compare with the internal and path alias (if any).
365 $page_match = drupal_match_path($path, $pages);
366 if ($path != $_GET['q']) {
367 $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
369 // When $visibility has a value of 0, the block is displayed on
370 // all pages except those listed in $pages. When set to 1, it
371 // is displayed only on those pages listed in $pages.
372 $page_match = !($visibility xor
$page_match);
375 $page_match = drupal_eval($pages);