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');
15 function googleanalytics_help($path, $arg) {
17 case
'admin/config/system/googleanalytics':
18 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/'));
22 function googleanalytics_permission() {
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/config/system/googleanalytics'] = array(
41 'title' => 'Google Analytics',
42 'description' => 'Configure tracking behavior to get insights into your website traffic and marketing effectiveness.',
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
,
47 'file' => 'googleanalytics.admin.inc',
54 * Implementation of hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
56 function googleanalytics_page_alter(&$page) {
59 $id = variable_get('googleanalytics_account', '');
61 // Get page status code for visibility filtering.
62 $status = drupal_get_http_header('Status');
63 $trackable_status_codes = array(
68 // 1. Check if the GA account number has a value.
69 // 2. Track page views based on visibility value.
70 // 3. Check if we should track the currently active user's role.
71 // 4. Ignore pages visibility filter for 404 or 403 status codes.
72 if (!empty($id) && (_googleanalytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _googleanalytics_visibility_user($user)) {
74 // We allow different scopes. Default to 'footer' but allow user to override if they really need to.
75 $scope = variable_get('googleanalytics_js_scope', 'header');
77 // Custom tracking. Prepend before all other JavaScript.
78 if (variable_get('googleanalytics_trackadsense', FALSE
)) {
79 $page['footer']['googleanalytics']['#attached']['js']['window.google_analytics_uacct = ' .
drupal_json_encode($id) .
';'] = array(
82 'weight' => JS_LIBRARY
- 21,
87 $link_settings = array();
88 if ($track_outgoing = variable_get('googleanalytics_trackoutgoing', 1)) {
89 $link_settings['trackOutgoing'] = $track_outgoing;
91 if ($track_mailto = variable_get('googleanalytics_trackmailto', 1)) {
92 $link_settings['trackMailto'] = $track_mailto;
94 if (($track_download = variable_get('googleanalytics_trackfiles', 1)) && ($trackfiles_extensions = variable_get('googleanalytics_trackfiles_extensions', GA_TRACKFILES_EXTENSIONS
))) {
95 $link_settings['trackDownload'] = $track_download;
96 $link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
98 if (!empty($link_settings)) {
99 $page['footer']['googleanalytics']['#attached']['js'][] = array(
101 'data' => array('googleanalytics' => $link_settings),
103 $page['footer']['googleanalytics']['#attached']['js'][drupal_get_path('module', 'googleanalytics') .
'/googleanalytics.js'] = array('scope' => $scope);
106 // Add User profile segmentation values.
107 $profile_fields = variable_get('googleanalytics_segmentation', array());
108 if (!empty($profile_fields) && ($user->uid
> 0)) {
109 // Invoke all modules having a hook_user_load() implemented.
110 // If the invoked modules extend the $user object, the additional
111 // data can be tracked.
112 module_invoke_all('user_load', array($user->uid
=> $user));
115 foreach ($profile_fields as
$field => $title) {
116 $fields[$field] = is_array($user->$field) ?
implode(',', $user->$field) : $user->$field;
119 // Only show segmentation variable if there are specified fields.
121 if (count($fields) > 0) {
122 $segmentation = '_gaq.push(["_setVar", ' .
drupal_json_encode(implode(':', $fields)) .
']);';
126 // Site search tracking support.
128 if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE
) && arg(0) == 'search' && $keys = googleanalytics_search_get_keys()) {
129 $url_custom = drupal_json_encode(rawurldecode(url('search/'.
arg(1), array('query' => array('search' => $keys)))));
132 // If this node is a translation of another node, pass the original
134 if (module_exists('translation') && variable_get('googleanalytics_translation_set', 0)) {
135 // Check we have a node object, it supports translation, and its
136 // translated node ID (tnid) doesn't match its own node ID.
137 $node = menu_get_object();
138 if ($node && translation_supported_type($node->type
) && isset($node->tnid
) && ($node->tnid
!= $node->nid
)) {
139 $source_node = node_load($node->tnid
);
140 $languages = language_list();
141 $url_custom = drupal_json_encode(url('node/'.
$source_node->nid
, array('language' => $languages[$source_node->language
])));
145 // Track access denied (403) and file not found (404) pages.
146 if ($status == '403 Forbidden') {
147 // See http://www.google.com/support/analytics/bin/answer.py?answer=86927
148 $url_custom = '"/403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
150 elseif ($status == '404 Not Found') {
151 $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
154 // Add any custom code snippets if specified.
155 $codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
156 $codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');
158 // Build tracker code.
159 $script = 'var _gaq = _gaq || [];';
160 $script .
= '_gaq.push(["_setAccount", ' .
drupal_json_encode($id) .
']);';
161 if (variable_get('googleanalytics_tracker_anonymizeip', 0)) {
162 // FIXME: The Google API is currently broken and "_gat._anonymizeIp" is only
163 // a workaround until "_anonymizeIp" has been implemented/fixed.
164 $script .
= '_gaq.push(["_gat._anonymizeIp"]);';
166 if (!empty($segmentation)) {
167 $script .
= $segmentation;
169 if (!empty($codesnippet_before)) {
170 $script .
= $codesnippet_before;
172 if (empty($url_custom)) {
173 $script .
= '_gaq.push(["_trackPageview"]);';
176 $script .
= '_gaq.push(["_trackPageview", ' .
$url_custom .
']);';
178 if (!empty($codesnippet_after)) {
179 $script .
= $codesnippet_after;
182 $script .
= '(function() {';
183 $script .
= 'var ga = document.createElement("script");';
184 $script .
= 'ga.type = "text/javascript";';
185 $script .
= 'ga.async = true;';
187 // Should a local cached copy of ga.js be used?
188 if (variable_get('googleanalytics_cache', 0) && $url = _googleanalytics_cache('http://www.google-analytics.com/ga.js')) {
189 $script .
= 'ga.src = "' .
$url .
'";';
192 $script .
= 'ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";';
194 $script .
= 'var s = document.getElementsByTagName("script")[0];';
195 $script .
= 's.parentNode.insertBefore(ga, s);';
198 // Add tracker code to scope.
199 $page['footer']['googleanalytics']['#attached']['js'][$script] = array(
207 * Implement hook_form_FORM_ID_alter().
209 * Allow users to decide if tracking code will be added to pages or not.
211 function googleanalytics_form_user_profile_form_alter(&$form, &$form_state) {
212 $account = $form['#user'];
213 $category = $form['#user_category'];
215 if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('googleanalytics_custom', 0)) != 0 && _googleanalytics_visibility_roles($account)) {
216 $form['googleanalytics'] = array(
217 '#type' => 'fieldset',
218 '#title' => t('Google Analytics configuration'),
220 '#collapsible' => TRUE
,
226 $description = t('Users are tracked by default, but you are able to opt out.');
230 $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
234 $form['googleanalytics']['custom'] = array(
235 '#type' => 'checkbox',
236 '#title' => t('Enable user tracking'),
237 '#description' => $description,
238 '#default_value' => isset($account->data
['googleanalytics']['custom']) ?
$account->data
['googleanalytics']['custom'] : ($custom == 1)
246 * Implements hook_user_presave().
248 function googleanalytics_user_presave(&$edit, $account, $category) {
249 if (isset($edit['googleanalytics']['custom'])) {
250 $edit['data']['googleanalytics']['custom'] = $edit['googleanalytics']['custom'];
255 * Implementation of hook_cron().
257 function googleanalytics_cron() {
258 // Regenerate the google analytics ga.js every day.
259 if (time() - variable_get('googleanalytics_last_cache', 0) >= 86400 && variable_get('googleanalytics_cache', 0)) {
260 $path = 'public://googleanalytics';
261 $file_destination = $path .
'/ga.js';
263 // Download the latest ga.js code and replace local file if code have changed.
264 $result = drupal_http_request('http://www.google-analytics.com/ga.js');
266 if ($result->code
== 200 && file_exists($file_destination)) {
267 $data_hash_local = md5(file_get_contents($file_destination));
268 $data_hash_remote = md5($result->data
);
269 // Check that the files directory is writable.
270 if ($data_hash_local != $data_hash_remote && file_prepare_directory($path, FILE_CREATE_DIRECTORY
)) {
271 // Save updated ga.js file to disk.
272 file_unmanaged_save_data($result->data
, $file_destination, FILE_EXISTS_REPLACE
);
273 watchdog('googleanalytics', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO
);
275 // Change query-strings on css/js files to enforce reload for all users.
276 _drupal_flush_css_js();
280 variable_set('googleanalytics_last_cache', time());
285 * Download and cache the ga.js file locally.
287 * The full URL to the external javascript file.
289 * The path to the local javascript file on success, boolean FALSE on failure.
291 function _googleanalytics_cache($location) {
292 // A dummy query-string is added to filenames, to gain control over
293 // browser-caching. The string changes on every update or full cache
294 // flush, forcing browsers to load a new copy of the files, as the
296 $query_string = '?' .
variable_get('css_js_query_string', '0');
298 $path = 'public://googleanalytics';
299 $file_destination = $path .
'/'.
basename($location);
300 if (!file_exists($file_destination)) {
301 $result = drupal_http_request($location);
302 if ($result->code
== 200) {
303 // Check that the files directory is writable.
304 if (file_prepare_directory($path, FILE_CREATE_DIRECTORY
)) {
305 return file_create_url(file_unmanaged_save_data($result->data
, $file_destination, FILE_EXISTS_REPLACE
)) .
$query_string;
310 return file_create_url($file_destination) .
$query_string;
315 * Delete cached files and directory.
317 function googleanalytics_clear_js_cache() {
318 $path = 'public://googleanalytics';
319 if (file_prepare_directory($directory)) {
320 file_scan_directory($path, '/.*/', array('callback' => 'file_delete'));
323 // Change query-strings on css/js files to enforce reload for all users.
324 _drupal_flush_css_js();
329 * Helper function for grabbing search keys. Function is missing in D7.
331 * http://api.drupal.org/api/function/search_get_keys/6
333 function googleanalytics_search_get_keys() {
335 if (!isset($return)) {
336 // Extract keys as remainder of path
337 // Note: support old GET format of searches for existing links.
338 $path = explode('/', $_GET['q'], 3);
339 $keys = empty($_REQUEST['keys']) ?
'' : $_REQUEST['keys'];
340 $return = count($path) == 3 ?
$path[2] : $keys;
346 * Tracking visibility check for an user object.
349 * A user object containing an array of roles to check.
351 * A decision on if the current user is being tracked by Google Analytics.
353 function _googleanalytics_visibility_user($account) {
357 // Is current user a member of a role that should be tracked?
358 if (_googleanalytics_visibility_roles($account)) {
360 // Use the user's block visibility setting, if necessary.
361 if (($custom = variable_get('googleanalytics_custom', 0)) != 0) {
362 if ($account->uid
&& isset($account->data
['googleanalytics']['custom'])) {
363 $enabled = $account->data
['googleanalytics']['custom'];
366 $enabled = ($custom == 1);
379 * Based on visibility setting this function returns TRUE if GA code should
380 * be added for the current role and otherwise FALSE.
382 function _googleanalytics_visibility_roles($account) {
385 $roles = variable_get('googleanalytics_roles', array());
387 if (array_sum($roles) > 0) {
388 // One or more roles are selected for tracking.
389 foreach (array_keys($account->roles
) as
$rid) {
390 // Is the current user a member of one role enabled for tracking?
391 if (isset($roles[$rid]) && $rid == $roles[$rid]) {
392 // Current user is a member of a role that should be tracked.
399 // No role is selected for tracking, therefor all roles should be tracked.
407 * Based on visibility setting this function returns TRUE if GA code should
408 * be added to the current page and otherwise FALSE.
410 function _googleanalytics_visibility_pages() {
413 // Cache visibility setting in hook_init for hook_footer.
414 if (!isset($page_match)) {
416 $visibility = variable_get('googleanalytics_visibility', 0);
417 $pages = variable_get('googleanalytics_pages', '');
419 // Match path if necessary.
420 if (!empty($pages)) {
421 if ($visibility < 2) {
422 $path = drupal_get_path_alias($_GET['q']);
423 // Compare with the internal and path alias (if any).
424 $page_match = drupal_match_path($path, $pages);
425 if ($path != $_GET['q']) {
426 $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
428 // When $visibility has a value of 0, the block is displayed on
429 // all pages except those listed in $pages. When set to 1, it
430 // is displayed only on those pages listed in $pages.
431 $page_match = !($visibility xor
$page_match);
434 $page_match = drupal_eval($pages);