<?php
-// $Id$
-/*
+/**
* @file
- * Drupal Module: GoogleAnalytics
- * Adds the required Javascript to the bottom of all your Drupal pages
- * to allow tracking by the Google Analytics statistics package.
+ * Drupal Module: Google Analytics
+ *
+ * Adds the required Javascript to all your Drupal pages to allow tracking by
+ * the Google Analytics statistics package.
*
- * @author: Mike Carter <www.ixis.co.uk/contact>
+ * @author: Alexander Hass <http://drupal.org/user/85918>
+ */
+
+/**
+ * Define the default file extension list that should be tracked as download.
*/
+define('GOOGLEANALYTICS_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');
-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');
+/**
+ * Define default path exclusion list to remove tracking from admin pages,
+ * see http://drupal.org/node/34970 for more information.
+ */
+define('GOOGLEANALYTICS_PAGES', "admin\nadmin/*\nbatch\nnode/add*\nnode/*/*\nuser/*/*");
+/**
+ * Implements hook_help().
+ */
function googleanalytics_help($path, $arg) {
switch ($path) {
case 'admin/config/system/googleanalytics':
- 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/'));
+ 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/'));
}
}
-function googleanalytics_perm() {
+/**
+ * Implements hook_theme().
+ */
+function googleanalytics_theme() {
+ return array(
+ 'googleanalytics_admin_custom_var_table' => array(
+ 'render element' => 'form',
+ ),
+ );
+}
+
+/**
+ * Implements hook_permission().
+ */
+function googleanalytics_permission() {
return array(
'administer google analytics' => array(
'title' => t('Administer Google Analytics'),
),
'use PHP for tracking visibility' => array(
'title' => t('Use PHP for tracking visibility'),
- '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.'))),
+ 'description' => t('Enter PHP code in the field for tracking visibility settings.'),
+ 'restrict access' => TRUE,
),
);
}
+/**
+ * Implements hook_menu().
+ */
function googleanalytics_menu() {
$items['admin/config/system/googleanalytics'] = array(
'title' => 'Google Analytics',
- 'description' => 'Configure the settings used to generate your Google Analytics tracking code.',
+ 'description' => 'Configure tracking behavior to get insights into your website traffic and marketing effectiveness.',
'page callback' => 'drupal_get_form',
'page arguments' => array('googleanalytics_admin_settings_form'),
'access arguments' => array('administer google analytics'),
return $items;
}
-function googleanalytics_init() {
+/**
+ * Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
+ */
+function googleanalytics_page_alter(&$page) {
global $user;
$id = variable_get('googleanalytics_account', '');
+ // Get page status code for visibility filtering.
+ $status = drupal_get_http_header('Status');
+ $trackable_status_codes = array(
+ '403 Forbidden',
+ '404 Not Found',
+ );
+
// 1. Check if the GA account number has a value.
// 2. Track page views based on visibility value.
// 3. Check if we should track the currently active user's role.
- if (!empty($id) && _googleanalytics_visibility_pages() && _googleanalytics_visibility_user($user)) {
- $scope = variable_get('googleanalytics_js_scope', 'footer');
-
- // Should a local cached copy of ga.js be used?
- $js_file = 'ga.js';
- $url = 'http://www.google-analytics.com/'. $js_file;
+ // 4. Ignore pages visibility filter for 404 or 403 status codes.
+ if (!empty($id) && (_googleanalytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _googleanalytics_visibility_user($user)) {
- if (variable_get('googleanalytics_cache', 0) && $source = _googleanalytics_cache($url)) {
- drupal_add_js($source, array('type' => 'file', 'scope' => $scope));
- }
- else {
- $script = 'var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");';
- $script .= 'document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/'. $js_file .'\' type=\'text/javascript\'%3E%3C/script%3E"));';
- drupal_add_js($script, array('type' => 'inline', 'scope' => $scope, 'weight' => JS_DEFAULT - 1));
- }
+ // We allow different scopes. Default to 'header' but allow user to override if they really need to.
+ // @todo: footer may no longer suppored
+ $scope = variable_get('googleanalytics_js_scope', 'header');
// Add link tracking.
$link_settings = array();
- if ($track_outgoing = variable_get('googleanalytics_trackoutgoing', 1)) {
- $link_settings['trackOutgoing'] = $track_outgoing;
+ if ($track_outbound = variable_get('googleanalytics_trackoutbound', 1)) {
+ $link_settings['trackOutbound'] = $track_outbound;
}
if ($track_mailto = variable_get('googleanalytics_trackmailto', 1)) {
$link_settings['trackMailto'] = $track_mailto;
}
- if (($track_download = variable_get('googleanalytics_trackfiles', 1)) && ($trackfiles_extensions = variable_get('googleanalytics_trackfiles_extensions', GA_TRACKFILES_EXTENSIONS))) {
+ if (($track_download = variable_get('googleanalytics_trackfiles', 1)) && ($trackfiles_extensions = variable_get('googleanalytics_trackfiles_extensions', GOOGLEANALYTICS_TRACKFILES_EXTENSIONS))) {
$link_settings['trackDownload'] = $track_download;
$link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
}
- if (!empty($link_settings)) {
- drupal_add_js(array('googleanalytics' => $link_settings), array('type' => 'setting', 'scope' => 'header'));
- drupal_add_js(drupal_get_path('module', 'googleanalytics') .'/googleanalytics.js', array('type' => 'file', 'scope' => $scope));
+ if ($track_domain_mode = variable_get('googleanalytics_domain_mode', 0)) {
+ $link_settings['trackDomainMode'] = $track_domain_mode;
}
-
- // Custom tracking.
- if (variable_get('googleanalytics_trackadsense', FALSE)) {
- drupal_add_js('window.google_analytics_uacct = ' . drupal_json_encode($id) . ';', array('type' => 'inline', 'scope' => 'header'));
+ if ($track_cross_domains = variable_get('googleanalytics_cross_domains', '')) {
+ $link_settings['trackCrossDomains'] = preg_split('/(\r\n?|\n)/', $track_cross_domains);
}
- }
-}
-
-/**
- * Implementation of hook_page_alter() to insert Javascript at the bottom of the page.
- */
-function googleanalytics_page_alter(&$page) {
- global $user;
-
- $id = variable_get('googleanalytics_account', '');
- if (!empty($id) && _googleanalytics_visibility_pages() && _googleanalytics_visibility_user($user)) {
-
- // Add User profile segmentation values.
- if (is_array($profile_fields = variable_get('googleanalytics_segmentation', '')) && ($user->uid > 0)) {
-
- $p = module_invoke('profile', 'load_profile', $user);
+ if (!empty($link_settings)) {
+ drupal_add_js(array('googleanalytics' => $link_settings), 'setting');
+ drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.js');
+ }
- $fields = array();
- foreach ($profile_fields as $field => $title) {
- $value = $user->$field;
+ // Add messages tracking.
+ $message_events = '';
+ if ($message_types = variable_get('googleanalytics_trackmessages', array())) {
+ $message_types = array_values(array_filter($message_types));
+ $status_heading = array(
+ 'status' => t('Status message'),
+ 'warning' => t('Warning message'),
+ 'error' => t('Error message'),
+ );
- if (is_array($value)) {
- $value = implode(',', $value);
+ foreach (drupal_get_messages(NULL, FALSE) as $type => $messages) {
+ // Track only the selected message types.
+ if (in_array($type, $message_types)) {
+ foreach ($messages as $message) {
+ // @todo: Track as exceptions?
+ $message_events .= 'ga("send", "event", ' . drupal_json_encode(t('Messages')) . ', ' . drupal_json_encode($status_heading[$type]) . ', ' . drupal_json_encode(strip_tags($message)) . ');';
+ }
}
-
- $fields[$field] = $value;
- }
-
- // Only show segmentation variable if there are specified fields.
- $segmentation = '';
- if (count($fields) > 0) {
- $segmentation = 'pageTracker._setVar('. drupal_json_encode(implode(':', $fields)) .');';
}
}
// Site search tracking support.
$url_custom = '';
- if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = search_get_keys()) {
- $url_custom = drupal_json_encode(url('search/'. arg(1), array('query' => 'search='. $keys)));
+ if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = googleanalytics_search_get_keys()) {
+ // hook_preprocess_search_results() is not executed if search result is
+ // empty. Make sure the counter is set to 0 if there are no results.
+ $url_custom = '(window.googleanalytics_search_results) ? ' . drupal_json_encode(url('search/' . arg(1), array('query' => array('search' => $keys)))) . ' : ' . drupal_json_encode(url('search/' . arg(1), array('query' => array('search' => 'no-results:' . $keys, 'cat' => 'no-results'))));
}
// If this node is a translation of another node, pass the original
// Check we have a node object, it supports translation, and its
// translated node ID (tnid) doesn't match its own node ID.
$node = menu_get_object();
- if ($node && translation_supported_type($node->type) && isset($node->tnid) && ($node->tnid != $node->nid)) {
+ if ($node && translation_supported_type($node->type) && !empty($node->tnid) && ($node->tnid != $node->nid)) {
$source_node = node_load($node->tnid);
$languages = language_list();
- $url_custom = drupal_json_encode(url('node/'. $source_node->nid, array('language' => $languages[$source_node->language])));
+ $url_custom = drupal_json_encode(url('node/' . $source_node->nid, array('language' => $languages[$source_node->language])));
}
}
// Track access denied (403) and file not found (404) pages.
- if (function_exists('drupal_get_headers')) {
- $headers = drupal_get_headers();
- if (strstr($headers, 'HTTP/1.1 403 Forbidden')) {
- // See http://www.google.com/support/analytics/bin/answer.py?answer=86927
- $url_custom = '"/403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
- }
- elseif (strstr($headers, 'HTTP/1.1 404 Not Found')) {
- $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
- }
+ if ($status == '403 Forbidden') {
+ // See http://www.google.com/support/analytics/bin/answer.py?answer=86927
+ $url_custom = '"/403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
+ }
+ elseif ($status == '404 Not Found') {
+ $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
}
// Add any custom code snippets if specified.
$codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
$codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');
- // Build tracker code for footer.
- $script = 'try{';
- $script .= 'var pageTracker = _gat._getTracker('. drupal_json_encode($id) .');';
- if (!empty($segmentation)) {
- $script .= $segmentation;
+ // Add custom variables.
+ /* @todo: Needs upgrade to custom dimensions
+ $googleanalytics_custom_vars = variable_get('googleanalytics_custom_var', array());
+ $custom_var = '';
+ for ($i = 1; $i < 6; $i++) {
+ $custom_var_name = !empty($googleanalytics_custom_vars['slots'][$i]['name']) ? $googleanalytics_custom_vars['slots'][$i]['name'] : '';
+ if (!empty($custom_var_name)) {
+ $custom_var_value = !empty($googleanalytics_custom_vars['slots'][$i]['value']) ? $googleanalytics_custom_vars['slots'][$i]['value'] : '';
+ $custom_var_scope = !empty($googleanalytics_custom_vars['slots'][$i]['scope']) ? $googleanalytics_custom_vars['slots'][$i]['scope'] : 3;
+
+ $types = array();
+ $node = menu_get_object();
+ if (is_object($node)) {
+ $types += array('node' => $node);
+ }
+ $custom_var_name = token_replace($custom_var_name, $types, array('clear' => TRUE));
+ $custom_var_value = token_replace($custom_var_value, $types, array('clear' => TRUE));
+
+ // Suppress empty custom names and/or variables.
+ if (!drupal_strlen(trim($custom_var_name)) || !drupal_strlen(trim($custom_var_value))) {
+ continue;
+ }
+
+ // The length of the string used for the 'name' and the length of the
+ // string used for the 'value' must not exceed 128 bytes after url encoding.
+ $name_length = drupal_strlen(rawurlencode($custom_var_name));
+ $tmp_value = rawurlencode($custom_var_value);
+ $value_length = drupal_strlen($tmp_value);
+ if ($name_length + $value_length > 128) {
+ // Trim value and remove fragments of url encoding.
+ $tmp_value = rtrim(substr($tmp_value, 0, 127 - $name_length), '%0..9A..F');
+ $custom_var_value = urldecode($tmp_value);
+ }
+
+ $custom_var_name = drupal_json_encode($custom_var_name);
+ $custom_var_value = drupal_json_encode($custom_var_value);
+
+ $custom_var .= "ga('set', 'dimension" . $i . "', $custom_var_name);"; // Max 150 bytes
+ $custom_var .= "ga('set', 'metric" . $i . "', $custom_var_value);";
+ }
+ } */
+
+ // Build tracker code.
+ $script = '(function(i,s,o,g,r,a,m){';
+ $script .= 'i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){';
+ $script .= '(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),';
+ $script .= 'm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)';
+ $script .= '})(window,document,"script",';
+
+ // Which version of the tracking library should be used?
+ $library_tracker_url = '//www.google-analytics.com/analytics.js';
+ $library_cache_url = 'http:' . $library_tracker_url;
+
+ // Should a local cached copy of analytics.js be used?
+ if (variable_get('googleanalytics_cache', 0) && $url = _googleanalytics_cache($library_cache_url)) {
+ // A dummy query-string is added to filenames, to gain control over
+ // browser-caching. The string changes on every update or full cache
+ // flush, forcing browsers to load a new copy of the files, as the
+ // URL changed.
+ $query_string = '?' . variable_get('css_js_query_string', '0');
+
+ $script .= '"' . $url . $query_string . '"';
+ }
+ else {
+ $script .= '"' . $library_tracker_url . '"';
+ }
+ $script .= ',"ga");';
+
+ // Create a tracker.
+ $script .= 'ga("create", ' . drupal_json_encode($id) . ');';
+
+ if (variable_get('googleanalytics_tracker_anonymizeip', 0)) {
+ $script .= 'ga("set", "anonymizeIp", 1);';
+ }
+
+ // Prepare Adsense tracking.
+ $googleanalytics_adsense_script = 'window.google_analytics_uacct = ' . drupal_json_encode($id) . ';';
+
+ // Domain tracking type.
+ global $cookie_domain;
+ $domain_mode = variable_get('googleanalytics_domain_mode', 0);
+
+ // Per RFC 2109, cookie domains must contain at least one dot other than the
+ // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
+ if ($domain_mode == 1 && count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
+ $script .= 'ga("set", "cookieDomain", ' . drupal_json_encode($cookie_domain) . ');';
+ $googleanalytics_adsense_script .= 'window.google_analytics_domain_name = ' . drupal_json_encode($cookie_domain) . ';';
+ }
+ elseif ($domain_mode == 2) {
+ // @todo: unclear, cookieDomain = "none" is not documented.
+ $script .= 'ga("set", "cookieDomain", "none");';
+ $script .= 'ga("set", "allowLinker", true);';
+ $googleanalytics_adsense_script .= 'window.google_analytics_domain_name = "none";';
+ }
+
+ if (!empty($custom_var)) {
+ $script .= $custom_var;
}
if (!empty($codesnippet_before)) {
$script .= $codesnippet_before;
}
- $script .= 'pageTracker._trackPageview('. $url_custom .');';
+ if (!empty($url_custom)) {
+ $script .= 'ga("set", "page", ' . $url_custom . ');';
+ }
+ $script .= 'ga("send", "pageview");';
+
+ if (!empty($message_events)) {
+ $script .= $message_events;
+ }
if (!empty($codesnippet_after)) {
$script .= $codesnippet_after;
}
- $script .= '} catch(err) {}';
- drupal_add_js($script, array('type' => 'inline', 'scope' => 'footer'));
+ // @TODO: not available yet, comming soon per Google.
+ //if (variable_get('googleanalytics_trackadsense', FALSE)) {
+ // Custom tracking. Prepend before all other JavaScript.
+ // @TODO: http://support.google.com/adsense/bin/answer.py?answer=98142
+ // sounds like it could be appended to $script.
+ //drupal_add_js($googleanalytics_adsense_script, array('type' => 'inline', 'group' => JS_LIBRARY-1));
+ //}
+
+ drupal_add_js($script, array('scope' => $scope, 'type' => 'inline'));
}
}
/**
- * Implement hook_form_FORM_ID_alter().
+ * Implements hook_field_extra_fields().
+ */
+function googleanalytics_field_extra_fields() {
+ $extra['user']['user']['form']['googleanalytics'] = array(
+ 'label' => t('Google Analytics configuration'),
+ 'description' => t('Google Analytics module form element.'),
+ 'weight' => 3,
+ );
+
+ return $extra;
+}
+
+/**
+ * Implements hook_form_FORM_ID_alter().
*
* Allow users to decide if tracking code will be added to pages or not.
*/
break;
}
+ // Disable tracking for visitors who have opted out from tracking via DNT (Do-Not-Track) header.
+ $disabled = FALSE;
+ if (variable_get('googleanalytics_privacy_donottrack', 1) && !empty($_SERVER['HTTP_DNT'])) {
+ $disabled = TRUE;
+
+ // Override settings value.
+ $account->data['googleanalytics']['custom'] = FALSE;
+
+ $description .= '<span class="admin-disabled">';
+ $description .= ' ' . t('You have opted out from tracking via browser privacy settings.');
+ $description .= '</span>';
+ }
+
$form['googleanalytics']['custom'] = array(
'#type' => 'checkbox',
'#title' => t('Enable user tracking'),
'#description' => $description,
- '#default_value' => isset($account->googleanalytics['custom']) ? $account->googleanalytics['custom'] : ($custom == 1)
+ '#default_value' => isset($account->data['googleanalytics']['custom']) ? $account->data['googleanalytics']['custom'] : ($custom == 1),
+ '#disabled' => $disabled,
);
return $form;
}
/**
- * Implementation of hook_requirements().
+ * Implements hook_user_presave().
*/
-function googleanalytics_requirements($phase) {
- $requirements = array();
-
- if ($phase == 'runtime') {
- // Raise warning if Google user account has not been set yet.
- if (!preg_match('/^UA-\d{4,}-\d+$/', variable_get('googleanalytics_account', 'UA-'))) {
- $requirements['googleanalytics'] = array(
- 'title' => t('Google Analytics module'),
- '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/config/system/googleanalytics'))),
- 'severity' => REQUIREMENT_ERROR,
- 'value' => t('Not configured'),
- );
- }
+function googleanalytics_user_presave(&$edit, $account, $category) {
+ if (isset($edit['googleanalytics']['custom'])) {
+ $edit['data']['googleanalytics']['custom'] = $edit['googleanalytics']['custom'];
}
-
- return $requirements;
}
/**
- * Implementation of hook_cron().
+ * Implements hook_cron().
*/
function googleanalytics_cron() {
- // Regenerate the google analytics ga.js every day.
- if (time() - variable_get('googleanalytics_last_cache', 0) >= 86400) {
- // New google analytics version.
- file_unmanaged_delete('public://googleanalytics/ga.js');
-
- // Clear aggregated JS files.
- if (variable_get('preprocess_js', 0)) {
- drupal_clear_js_cache();
- }
+ // Regenerate the tracking code file every day.
+ if (REQUEST_TIME - variable_get('googleanalytics_last_cache', 0) >= 86400 && variable_get('googleanalytics_cache', 0)) {
+ _googleanalytics_cache('http://www.google-analytics.com/analytics.js', TRUE);
+ variable_set('googleanalytics_last_cache', REQUEST_TIME);
+ }
+}
+
+/**
+ * Implements hook_preprocess_search_results().
+ *
+ * Collects and adds the number of search results to the head.
+ */
+function googleanalytics_preprocess_search_results(&$variables) {
+ // There is no search result $variable available that hold the number of items
+ // found. But the pager item mumber can tell the number of search results.
+ global $pager_total_items;
+
+ drupal_add_js('window.googleanalytics_search_results = ' . intval($pager_total_items[0]) . ';', array('type' => 'inline', 'group' => JS_LIBRARY-1));
+}
- variable_set('googleanalytics_last_cache', time());
+/**
+ * Helper function for grabbing search keys. Function is missing in D7.
+ *
+ * http://api.drupal.org/api/function/search_get_keys/6
+ */
+function googleanalytics_search_get_keys() {
+ static $return;
+ if (!isset($return)) {
+ // Extract keys as remainder of path
+ // Note: support old GET format of searches for existing links.
+ $path = explode('/', $_GET['q'], 3);
+ $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
+ $return = count($path) == 3 ? $path[2] : $keys;
}
+ return $return;
}
/**
- * Download and cache the ga.js file locally.
+ * Download/Synchronize/Cache tracking code file locally.
+ *
* @param $location
* The full URL to the external javascript file.
+ * @param $sync_cached_file
+ * Synchronize tracking code and update if remote file have changed.
* @return mixed
* The path to the local javascript file on success, boolean FALSE on failure.
*/
-function _googleanalytics_cache($location) {
+function _googleanalytics_cache($location, $sync_cached_file = FALSE) {
$path = 'public://googleanalytics';
- $file_destination = $path .'/'. basename($location);
- if (!file_exists($file_destination)) {
+ $file_destination = $path . '/' . basename($location);
+
+ if (!file_exists($file_destination) || $sync_cached_file) {
+ // Download the latest tracking code.
$result = drupal_http_request($location);
+
if ($result->code == 200) {
- // Check that the files directory is writable
- if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
- return file_unmanaged_save_data($result->data, $path .'/'. basename($location), FILE_EXISTS_REPLACE);
+ if (file_exists($file_destination)) {
+ // Synchronize tracking code and and replace local file if outdated.
+ $data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
+ $data_hash_remote = drupal_hash_base64($result->data);
+ // Check that the files directory is writable.
+ if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
+ // Save updated tracking code file to disk.
+ file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
+ watchdog('googleanalytics', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);
+
+ // Change query-strings on css/js files to enforce reload for all users.
+ _drupal_flush_css_js();
+ }
+ }
+ else {
+ // Check that the files directory is writable.
+ if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
+ // There is no need to flush JS here as core refreshes JS caches
+ // automatically, if new files are added.
+ file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
+ watchdog('googleanalytics', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);
+
+ // Return the local JS file path.
+ return file_create_url($file_destination);
+ }
}
}
}
else {
- return $file_destination;
+ // Return the local JS file path.
+ return file_create_url($file_destination);
+ }
+}
+
+/**
+ * Delete cached files and directory.
+ */
+function googleanalytics_clear_js_cache() {
+ $path = 'public://googleanalytics';
+ if (file_prepare_directory($path)) {
+ file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
+ drupal_rmdir($path);
+
+ // Change query-strings on css/js files to enforce reload for all users.
+ _drupal_flush_css_js();
+
+ watchdog('googleanalytics', 'Local cache has been purged.', array(), WATCHDOG_INFO);
}
}
$enabled = FALSE;
// Is current user a member of a role that should be tracked?
- if (_googleanalytics_visibility_roles($account)) {
+ if (_googleanalytics_visibility_header($account) && _googleanalytics_visibility_roles($account)) {
// Use the user's block visibility setting, if necessary.
if (($custom = variable_get('googleanalytics_custom', 0)) != 0) {
- if ($account->uid && isset($account->googleanalytics['custom'])) {
- $enabled = $account->googleanalytics['custom'];
+ if ($account->uid && isset($account->data['googleanalytics']['custom'])) {
+ $enabled = $account->data['googleanalytics']['custom'];
}
else {
$enabled = ($custom == 1);
*/
function _googleanalytics_visibility_roles($account) {
- $enabled = FALSE;
+ $visibility = variable_get('googleanalytics_visibility_roles', 0);
+ $enabled = $visibility;
$roles = variable_get('googleanalytics_roles', array());
if (array_sum($roles) > 0) {
- // One or more roles are selected for tracking.
+ // One or more roles are selected.
foreach (array_keys($account->roles) as $rid) {
- // Is the current user a member of one role enabled for tracking?
+ // Is the current user a member of one of these roles?
if (isset($roles[$rid]) && $rid == $roles[$rid]) {
- // Current user is a member of a role that should be tracked.
- $enabled = TRUE;
+ // Current user is a member of a role that should be tracked/excluded from tracking.
+ $enabled = !$visibility;
break;
}
}
}
else {
- // No role is selected for tracking, therefor all roles should be tracked.
+ // No role is selected for tracking, therefore all roles should be tracked.
$enabled = TRUE;
}
function _googleanalytics_visibility_pages() {
static $page_match;
- // Cache visibility setting in hook_init for hook_footer.
+ // Cache visibility result if function is called more than once.
if (!isset($page_match)) {
- $visibility = variable_get('googleanalytics_visibility', 0);
- $pages = variable_get('googleanalytics_pages', '');
+ $visibility = variable_get('googleanalytics_visibility_pages', 0);
+ $setting_pages = variable_get('googleanalytics_pages', GOOGLEANALYTICS_PAGES);
// Match path if necessary.
- if (!empty($pages)) {
+ if (!empty($setting_pages)) {
+ // Convert path to lowercase. This allows comparison of the same path
+ // with different case. Ex: /Page, /page, /PAGE.
+ $pages = drupal_strtolower($setting_pages);
if ($visibility < 2) {
- $path = drupal_get_path_alias($_GET['q']);
- // Compare with the internal and path alias (if any).
+ // Convert the Drupal path to lowercase
+ $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
+ // Compare the lowercase internal and lowercase path alias (if any).
$page_match = drupal_match_path($path, $pages);
if ($path != $_GET['q']) {
$page_match = $page_match || drupal_match_path($_GET['q'], $pages);
}
- // When $visibility has a value of 0, the block is displayed on
+ // When $visibility has a value of 0, the tracking code is displayed on
// all pages except those listed in $pages. When set to 1, it
// is displayed only on those pages listed in $pages.
$page_match = !($visibility xor $page_match);
}
+ elseif (module_exists('php')) {
+ $page_match = php_eval($setting_pages);
+ }
else {
- $page_match = drupal_eval($pages);
+ $page_match = FALSE;
}
}
else {
}
return $page_match;
}
+
+/**
+ * Based on headers send by clients this function returns TRUE if GA code should
+ * be added to the current page and otherwise FALSE.
+ */
+function _googleanalytics_visibility_header($account) {
+
+ if (($account->uid || variable_get('cache', 0) == 0) && variable_get('googleanalytics_privacy_donottrack', 1) && !empty($_SERVER['HTTP_DNT'])) {
+ // Disable tracking if caching is disabled or a visitors is logged in and
+ // have opted out from tracking via DNT (Do-Not-Track) header.
+ return FALSE;
+ }
+
+ return TRUE;
+}