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: Alexander Hass <http://drupal.org/user/85918>
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');
16 * Implements hook_help().
18 function googleanalytics_help($path, $arg) {
20 case
'admin/config/system/googleanalytics':
21 return t('<a href="@ga_url">Google Analytics</a> is a free (registration required) website traffic and marketing effectiveness service.', array('@ga_url' => 'http://www.google.com/analytics/'));
26 * Implements hook_theme().
28 function googleanalytics_theme() {
30 'googleanalytics_admin_custom_var_table' => array(
31 'render element' => 'form',
37 * Implements hook_permission().
39 function googleanalytics_permission() {
41 'administer google analytics' => array(
42 'title' => t('Administer Google Analytics'),
43 'description' => t('Perform maintenance tasks for Google Analytics.'),
45 'opt-in or out of tracking' => array(
46 'title' => t('Opt-in or out of tracking'),
47 'description' => t('Allow users to decide if tracking code will be added to pages or not.'),
49 'use PHP for tracking visibility' => array(
50 'title' => t('Use PHP for tracking visibility'),
51 '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.'))),
57 * Implements hook_menu().
59 function googleanalytics_menu() {
60 $items['admin/config/system/googleanalytics'] = array(
61 'title' => 'Google Analytics',
62 'description' => 'Configure tracking behavior to get insights into your website traffic and marketing effectiveness.',
63 'page callback' => 'drupal_get_form',
64 'page arguments' => array('googleanalytics_admin_settings_form'),
65 'access arguments' => array('administer google analytics'),
66 'type' => MENU_NORMAL_ITEM
,
67 'file' => 'googleanalytics.admin.inc',
74 * Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
76 function googleanalytics_page_alter(&$page) {
79 $id = variable_get('googleanalytics_account', '');
81 // Get page status code for visibility filtering.
82 $status = drupal_get_http_header('Status');
83 $trackable_status_codes = array(
88 // 1. Check if the GA account number has a value.
89 // 2. Track page views based on visibility value.
90 // 3. Check if we should track the currently active user's role.
91 // 4. Ignore pages visibility filter for 404 or 403 status codes.
92 if (!empty($id) && (_googleanalytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _googleanalytics_visibility_user($user)) {
94 // We allow different scopes. Default to 'header' but allow user to override if they really need to.
95 $scope = variable_get('googleanalytics_js_scope', 'header');
97 if (variable_get('googleanalytics_trackadsense', FALSE
)) {
98 // Custom tracking. Prepend before all other JavaScript.
99 drupal_add_js('window.google_analytics_uacct = ' .
drupal_json_encode($id) .
';', array('type' => 'inline', 'group' => JS_LIBRARY
-1));
102 // Add link tracking.
103 $link_settings = array();
104 if ($track_outgoing = variable_get('googleanalytics_trackoutgoing', 1)) {
105 $link_settings['trackOutgoing'] = $track_outgoing;
107 if ($track_mailto = variable_get('googleanalytics_trackmailto', 1)) {
108 $link_settings['trackMailto'] = $track_mailto;
110 if (($track_download = variable_get('googleanalytics_trackfiles', 1)) && ($trackfiles_extensions = variable_get('googleanalytics_trackfiles_extensions', GA_TRACKFILES_EXTENSIONS
))) {
111 $link_settings['trackDownload'] = $track_download;
112 $link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
114 if (!empty($link_settings)) {
115 drupal_add_js(array('googleanalytics' => $link_settings), 'setting');
116 drupal_add_js(drupal_get_path('module', 'googleanalytics') .
'/googleanalytics.js');
119 // Add User profile segmentation values.
120 $profile_fields = variable_get('googleanalytics_segmentation', array());
121 if (!empty($profile_fields)) {
122 // Invoke all modules having a hook_user_load() implemented.
123 // If the invoked modules extend the $user object, the additional
124 // data can be tracked.
125 module_invoke_all('user_load', array($user->uid
=> $user));
128 foreach ($profile_fields as
$field => $title) {
129 $fields[$field] = is_array($user->$field) ?
implode(',', $user->$field) : $user->$field;
132 // Only show segmentation variable if there are specified fields.
134 if (count($fields) > 0) {
135 $segmentation = '_gaq.push(["_setVar", ' .
drupal_json_encode(implode(':', $fields)) .
']);';
139 // Site search tracking support.
141 if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE
) && arg(0) == 'search' && $keys = googleanalytics_search_get_keys()) {
142 $url_custom = drupal_json_encode(rawurldecode(url('search/' .
arg(1), array('query' => array('search' => $keys)))));
145 // If this node is a translation of another node, pass the original
147 if (module_exists('translation') && variable_get('googleanalytics_translation_set', 0)) {
148 // Check we have a node object, it supports translation, and its
149 // translated node ID (tnid) doesn't match its own node ID.
150 $node = menu_get_object();
151 if ($node && translation_supported_type($node->type
) && isset($node->tnid
) && ($node->tnid
!= $node->nid
)) {
152 $source_node = node_load($node->tnid
);
153 $languages = language_list();
154 $url_custom = drupal_json_encode(url('node/' .
$source_node->nid
, array('language' => $languages[$source_node->language
])));
158 // Track access denied (403) and file not found (404) pages.
159 if ($status == '403 Forbidden') {
160 // See http://www.google.com/support/analytics/bin/answer.py?answer=86927
161 $url_custom = '"/403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
163 elseif ($status == '404 Not Found') {
164 $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
167 // Add any custom code snippets if specified.
168 $codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
169 $codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');
171 // Add custom variables.
172 $googleanalytics_custom_vars = variable_get('googleanalytics_custom_var', array());
174 for ($i = 1; $i < 6; $i++) {
175 $custom_var_name = !empty($googleanalytics_custom_vars['slots'][$i]['name']) ?
$googleanalytics_custom_vars['slots'][$i]['name'] : '';
176 if (!empty($custom_var_name)) {
177 $custom_var_value = !empty($googleanalytics_custom_vars['slots'][$i]['value']) ?
$googleanalytics_custom_vars['slots'][$i]['value'] : '';
178 $custom_var_scope = !empty($googleanalytics_custom_vars['slots'][$i]['scope']) ?
$googleanalytics_custom_vars['slots'][$i]['scope'] : 3;
180 $node = menu_get_object();
181 $custom_var_value = token_replace($custom_var_value, array('node' => $node), array('clear' => TRUE
));
183 // Suppress empty custom variables.
184 if (!is_numeric($custom_var_value) && empty($custom_var_value)) {
188 // The length of the string used for the 'name' and the length of the
189 // string used for the 'value' must not exceed 64 bytes after url encoding.
190 $name_length = drupal_strlen(rawurlencode($custom_var_name));
191 $tmp_value = rawurlencode($custom_var_value);
192 $value_length = drupal_strlen($tmp_value);
193 if ($name_length + $value_length > 64) {
194 // Trim value and remove fragments of url encoding.
195 $tmp_value = rtrim(substr($tmp_value, 0, 63 - $name_length), '%0..9A..F');
196 $custom_var_value = urldecode($tmp_value);
199 $custom_var_name = drupal_json_encode($custom_var_name);
200 $custom_var_value = drupal_json_encode($custom_var_value);
201 $custom_var .
= "_gaq.push(['_setCustomVar', $i, $custom_var_name, $custom_var_value, $custom_var_scope]);";
205 // Build tracker code.
206 $script = 'var _gaq = _gaq || [];';
207 $script .
= '_gaq.push(["_setAccount", ' .
drupal_json_encode($id) .
']);';
208 if (variable_get('googleanalytics_tracker_anonymizeip', 0)) {
209 // FIXME: The Google API is currently broken and "_gat._anonymizeIp" is only
210 // a workaround until "_anonymizeIp" has been implemented/fixed.
211 $script .
= '_gaq.push(["_gat._anonymizeIp"]);';
213 if (!empty($segmentation)) {
214 $script .
= $segmentation;
216 if (!empty($codesnippet_before)) {
217 $script .
= $codesnippet_before;
219 if (!empty($custom_var)) {
220 $script .
= $custom_var;
222 if (empty($url_custom)) {
223 $script .
= '_gaq.push(["_trackPageview"]);';
226 $script .
= '_gaq.push(["_trackPageview", ' .
$url_custom .
']);';
228 if (!empty($codesnippet_after)) {
229 $script .
= $codesnippet_after;
232 $script .
= '(function() {';
233 $script .
= 'var ga = document.createElement("script");';
234 $script .
= 'ga.type = "text/javascript";';
235 $script .
= 'ga.async = true;';
237 // A dummy query-string is added to filenames, to gain control over
238 // browser-caching. The string changes on every update or full cache
239 // flush, forcing browsers to load a new copy of the files, as the
241 $query_string = '?' .
variable_get('css_js_query_string', '0');
243 // Should a local cached copy of ga.js be used?
244 if (variable_get('googleanalytics_cache', 0) && $url = _googleanalytics_cache('http://www.google-analytics.com/ga.js')) {
245 $script .
= 'ga.src = "' .
$url .
$query_string .
'";';
248 $script .
= 'ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";';
250 $script .
= 'var s = document.getElementsByTagName("script")[0];';
251 $script .
= 's.parentNode.insertBefore(ga, s);';
254 drupal_add_js($script, array('scope' => $scope, 'type' => 'inline'));
259 * Implements hook_form_FORM_ID_alter().
261 * Allow users to decide if tracking code will be added to pages or not.
263 function googleanalytics_form_user_profile_form_alter(&$form, &$form_state) {
264 $account = $form['#user'];
265 $category = $form['#user_category'];
267 if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('googleanalytics_custom', 0)) != 0 && _googleanalytics_visibility_roles($account)) {
268 $form['googleanalytics'] = array(
269 '#type' => 'fieldset',
270 '#title' => t('Google Analytics configuration'),
272 '#collapsible' => TRUE
,
278 $description = t('Users are tracked by default, but you are able to opt out.');
282 $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
286 $form['googleanalytics']['custom'] = array(
287 '#type' => 'checkbox',
288 '#title' => t('Enable user tracking'),
289 '#description' => $description,
290 '#default_value' => isset($account->data
['googleanalytics']['custom']) ?
$account->data
['googleanalytics']['custom'] : ($custom == 1)
298 * Implements hook_user_presave().
300 function googleanalytics_user_presave(&$edit, $account, $category) {
301 if (isset($edit['googleanalytics']['custom'])) {
302 $edit['data']['googleanalytics']['custom'] = $edit['googleanalytics']['custom'];
307 * Implements hook_cron().
309 function googleanalytics_cron() {
310 // Regenerate the tracking code file every day.
311 if (REQUEST_TIME
- variable_get('googleanalytics_last_cache', 0) >= 86400 && variable_get('googleanalytics_cache', 0)) {
312 _googleanalytics_cache('http://www.google-analytics.com/ga.js', TRUE
);
313 variable_set('googleanalytics_last_cache', REQUEST_TIME
);
318 * Download/Synchronize/Cache tracking code file locally.
321 * The full URL to the external javascript file.
322 * @param $sync_cached_file
323 * Synchronize tracking code and update if remote file have changed.
325 * The path to the local javascript file on success, boolean FALSE on failure.
327 function _googleanalytics_cache($location, $sync_cached_file = FALSE
) {
328 $path = 'public://googleanalytics';
329 $file_destination = $path .
'/' .
basename($location);
331 if (!file_exists($file_destination) || $sync_cached_file) {
332 // Download the latest tracking code.
333 $result = drupal_http_request($location);
335 if ($result->code
== 200) {
336 if (file_exists($file_destination)) {
337 // Synchronize tracking code and and replace local file if outdated.
338 $data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
339 $data_hash_remote = drupal_hash_base64($result->data
);
340 // Check that the files directory is writable.
341 if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
342 // Save updated tracking code file to disk.
343 file_unmanaged_save_data($result->data
, $file_destination, FILE_EXISTS_REPLACE
);
344 watchdog('googleanalytics', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO
);
346 // Change query-strings on css/js files to enforce reload for all users.
347 _drupal_flush_css_js();
351 // Check that the files directory is writable.
352 if (file_prepare_directory($path, FILE_CREATE_DIRECTORY
)) {
353 // There is no need to flush JS here as core refreshes JS caches
354 // automatically, if new files are added.
355 file_unmanaged_save_data($result->data
, $file_destination, FILE_EXISTS_REPLACE
);
356 watchdog('googleanalytics', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO
);
358 // Return the local JS file path.
359 return file_create_url($file_destination);
365 // Return the local JS file path.
366 return file_create_url($file_destination);
371 * Delete cached files and directory.
373 function googleanalytics_clear_js_cache() {
374 $path = 'public://googleanalytics';
375 if (file_prepare_directory($path)) {
376 file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
379 // Change query-strings on css/js files to enforce reload for all users.
380 _drupal_flush_css_js();
382 watchdog('googleanalytics', 'Local cache has been purged.', array(), WATCHDOG_INFO
);
387 * Helper function for grabbing search keys. Function is missing in D7.
389 * http://api.drupal.org/api/function/search_get_keys/6
391 function googleanalytics_search_get_keys() {
393 if (!isset($return)) {
394 // Extract keys as remainder of path
395 // Note: support old GET format of searches for existing links.
396 $path = explode('/', $_GET['q'], 3);
397 $keys = empty($_REQUEST['keys']) ?
'' : $_REQUEST['keys'];
398 $return = count($path) == 3 ?
$path[2] : $keys;
404 * Tracking visibility check for an user object.
407 * A user object containing an array of roles to check.
409 * A decision on if the current user is being tracked by Google Analytics.
411 function _googleanalytics_visibility_user($account) {
415 // Is current user a member of a role that should be tracked?
416 if (_googleanalytics_visibility_roles($account)) {
418 // Use the user's block visibility setting, if necessary.
419 if (($custom = variable_get('googleanalytics_custom', 0)) != 0) {
420 if ($account->uid
&& isset($account->data
['googleanalytics']['custom'])) {
421 $enabled = $account->data
['googleanalytics']['custom'];
424 $enabled = ($custom == 1);
437 * Based on visibility setting this function returns TRUE if GA code should
438 * be added for the current role and otherwise FALSE.
440 function _googleanalytics_visibility_roles($account) {
443 $roles = variable_get('googleanalytics_roles', array());
445 if (array_sum($roles) > 0) {
446 // One or more roles are selected for tracking.
447 foreach (array_keys($account->roles
) as
$rid) {
448 // Is the current user a member of one role enabled for tracking?
449 if (isset($roles[$rid]) && $rid == $roles[$rid]) {
450 // Current user is a member of a role that should be tracked.
457 // No role is selected for tracking, therefor all roles should be tracked.
465 * Based on visibility setting this function returns TRUE if GA code should
466 * be added to the current page and otherwise FALSE.
468 function _googleanalytics_visibility_pages() {
471 // Cache visibility result if function is called more than once.
472 if (!isset($page_match)) {
474 $visibility = variable_get('googleanalytics_visibility', 0);
475 $pages = variable_get('googleanalytics_pages', '');
477 // Match path if necessary.
478 if (!empty($pages)) {
479 if ($visibility < 2) {
480 $path = drupal_get_path_alias($_GET['q']);
481 // Compare with the internal and path alias (if any).
482 $page_match = drupal_match_path($path, $pages);
483 if ($path != $_GET['q']) {
484 $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
486 // When $visibility has a value of 0, the block is displayed on
487 // all pages except those listed in $pages. When set to 1, it
488 // is displayed only on those pages listed in $pages.
489 $page_match = !($visibility xor
$page_match);
492 $page_match = php_eval($pages);