googleanalytics.module 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. <?php
  2. /*
  3. * @file
  4. * Drupal Module: GoogleAnalytics
  5. * Adds the required Javascript to the bottom of all your Drupal pages
  6. * to allow tracking by the Google Analytics statistics package.
  7. *
  8. * @author: Alexander Hass <http://drupal.org/user/85918>
  9. */
  10. 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');
  11. // Remove tracking from all administrative pages, see http://drupal.org/node/34970.
  12. define('GOOGLEANALYTICS_PAGES', "admin\nadmin/*\nbatch\nnode/add*\nnode/*/*\nuser/*/*");
  13. /**
  14. * Implements hook_help().
  15. */
  16. function googleanalytics_help($path, $arg) {
  17. switch ($path) {
  18. case 'admin/config/system/googleanalytics':
  19. 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/'));
  20. }
  21. }
  22. /**
  23. * Implements hook_theme().
  24. */
  25. function googleanalytics_theme() {
  26. return array(
  27. 'googleanalytics_admin_custom_var_table' => array(
  28. 'render element' => 'form',
  29. ),
  30. );
  31. }
  32. /**
  33. * Implements hook_permission().
  34. */
  35. function googleanalytics_permission() {
  36. return array(
  37. 'administer google analytics' => array(
  38. 'title' => t('Administer Google Analytics'),
  39. 'description' => t('Perform maintenance tasks for Google Analytics.'),
  40. ),
  41. 'opt-in or out of tracking' => array(
  42. 'title' => t('Opt-in or out of tracking'),
  43. 'description' => t('Allow users to decide if tracking code will be added to pages or not.'),
  44. ),
  45. 'use PHP for tracking visibility' => array(
  46. 'title' => t('Use PHP for tracking visibility'),
  47. 'description' => t('Enter PHP code in the field for tracking visibility settings.'),
  48. 'restrict access' => TRUE,
  49. ),
  50. );
  51. }
  52. /**
  53. * Implements hook_menu().
  54. */
  55. function googleanalytics_menu() {
  56. $items['admin/config/system/googleanalytics'] = array(
  57. 'title' => 'Google Analytics',
  58. 'description' => 'Configure tracking behavior to get insights into your website traffic and marketing effectiveness.',
  59. 'page callback' => 'drupal_get_form',
  60. 'page arguments' => array('googleanalytics_admin_settings_form'),
  61. 'access arguments' => array('administer google analytics'),
  62. 'type' => MENU_NORMAL_ITEM,
  63. 'file' => 'googleanalytics.admin.inc',
  64. );
  65. return $items;
  66. }
  67. /**
  68. * Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
  69. */
  70. function googleanalytics_page_alter(&$page) {
  71. global $user;
  72. $id = variable_get('googleanalytics_account', '');
  73. // Get page status code for visibility filtering.
  74. $status = drupal_get_http_header('Status');
  75. $trackable_status_codes = array(
  76. '403 Forbidden',
  77. '404 Not Found',
  78. );
  79. // 1. Check if the GA account number has a value.
  80. // 2. Track page views based on visibility value.
  81. // 3. Check if we should track the currently active user's role.
  82. // 4. Ignore pages visibility filter for 404 or 403 status codes.
  83. if (!empty($id) && (_googleanalytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _googleanalytics_visibility_user($user)) {
  84. // We allow different scopes. Default to 'header' but allow user to override if they really need to.
  85. $scope = variable_get('googleanalytics_js_scope', 'header');
  86. if (variable_get('googleanalytics_trackadsense', FALSE)) {
  87. // Custom tracking. Prepend before all other JavaScript.
  88. drupal_add_js('window.google_analytics_uacct = ' . drupal_json_encode($id) . ';', array('type' => 'inline', 'group' => JS_LIBRARY-1));
  89. }
  90. // Add link tracking.
  91. $link_settings = array();
  92. if ($track_outbound = variable_get('googleanalytics_trackoutbound', 1)) {
  93. $link_settings['trackOutbound'] = $track_outbound;
  94. }
  95. if ($track_mailto = variable_get('googleanalytics_trackmailto', 1)) {
  96. $link_settings['trackMailto'] = $track_mailto;
  97. }
  98. if (($track_download = variable_get('googleanalytics_trackfiles', 1)) && ($trackfiles_extensions = variable_get('googleanalytics_trackfiles_extensions', GOOGLEANALYTICS_TRACKFILES_EXTENSIONS))) {
  99. $link_settings['trackDownload'] = $track_download;
  100. $link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
  101. }
  102. if ($track_domain_mode = variable_get('googleanalytics_domain_mode', 0)) {
  103. $link_settings['trackDomainMode'] = $track_domain_mode;
  104. }
  105. if ($track_cross_domains = variable_get('googleanalytics_cross_domains', '')) {
  106. $link_settings['trackCrossDomains'] = preg_split('/(\r\n?|\n)/', $track_cross_domains);
  107. }
  108. if (!empty($link_settings)) {
  109. drupal_add_js(array('googleanalytics' => $link_settings), 'setting');
  110. drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.js');
  111. }
  112. // Add messages tracking.
  113. $message_events = '';
  114. if ($message_types = variable_get('googleanalytics_trackmessages', array())) {
  115. $message_types = array_values(array_filter($message_types));
  116. $status_heading = array(
  117. 'status' => t('Status message'),
  118. 'warning' => t('Warning message'),
  119. 'error' => t('Error message'),
  120. );
  121. foreach (drupal_get_messages(NULL, FALSE) as $type => $messages) {
  122. // Track only the selected message types.
  123. if (in_array($type, $message_types)) {
  124. foreach ($messages as $message) {
  125. $message_events .= '_gaq.push(["_trackEvent", ' . drupal_json_encode(t('Messages')) . ', ' . drupal_json_encode($status_heading[$type]) . ', ' . drupal_json_encode(strip_tags($message)) . ']);';
  126. }
  127. }
  128. }
  129. }
  130. // Site search tracking support.
  131. $url_custom = '';
  132. if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = googleanalytics_search_get_keys()) {
  133. $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'))));
  134. }
  135. // If this node is a translation of another node, pass the original
  136. // node instead.
  137. if (module_exists('translation') && variable_get('googleanalytics_translation_set', 0)) {
  138. // Check we have a node object, it supports translation, and its
  139. // translated node ID (tnid) doesn't match its own node ID.
  140. $node = menu_get_object();
  141. if ($node && translation_supported_type($node->type) && !empty($node->tnid) && ($node->tnid != $node->nid)) {
  142. $source_node = node_load($node->tnid);
  143. $languages = language_list();
  144. $url_custom = drupal_json_encode(url('node/' . $source_node->nid, array('language' => $languages[$source_node->language])));
  145. }
  146. }
  147. // Track access denied (403) and file not found (404) pages.
  148. if ($status == '403 Forbidden') {
  149. // See http://www.google.com/support/analytics/bin/answer.py?answer=86927
  150. $url_custom = '"/403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
  151. }
  152. elseif ($status == '404 Not Found') {
  153. $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
  154. }
  155. // Add any custom code snippets if specified.
  156. $codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
  157. $codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');
  158. // Add custom variables.
  159. $googleanalytics_custom_vars = variable_get('googleanalytics_custom_var', array());
  160. $custom_var = '';
  161. for ($i = 1; $i < 6; $i++) {
  162. $custom_var_name = !empty($googleanalytics_custom_vars['slots'][$i]['name']) ? $googleanalytics_custom_vars['slots'][$i]['name'] : '';
  163. if (!empty($custom_var_name)) {
  164. $custom_var_value = !empty($googleanalytics_custom_vars['slots'][$i]['value']) ? $googleanalytics_custom_vars['slots'][$i]['value'] : '';
  165. $custom_var_scope = !empty($googleanalytics_custom_vars['slots'][$i]['scope']) ? $googleanalytics_custom_vars['slots'][$i]['scope'] : 3;
  166. $types = array();
  167. $node = menu_get_object();
  168. if (is_object($node)) {
  169. $types += array('node' => $node);
  170. }
  171. $custom_var_name = token_replace($custom_var_name, $types, array('clear' => TRUE));
  172. $custom_var_value = token_replace($custom_var_value, $types, array('clear' => TRUE));
  173. // Suppress empty custom names and/or variables.
  174. if (!drupal_strlen(trim($custom_var_name)) || !drupal_strlen(trim($custom_var_value))) {
  175. continue;
  176. }
  177. // The length of the string used for the 'name' and the length of the
  178. // string used for the 'value' must not exceed 128 bytes after url encoding.
  179. $name_length = drupal_strlen(rawurlencode($custom_var_name));
  180. $tmp_value = rawurlencode($custom_var_value);
  181. $value_length = drupal_strlen($tmp_value);
  182. if ($name_length + $value_length > 128) {
  183. // Trim value and remove fragments of url encoding.
  184. $tmp_value = rtrim(substr($tmp_value, 0, 127 - $name_length), '%0..9A..F');
  185. $custom_var_value = urldecode($tmp_value);
  186. }
  187. $custom_var_name = drupal_json_encode($custom_var_name);
  188. $custom_var_value = drupal_json_encode($custom_var_value);
  189. $custom_var .= "_gaq.push(['_setCustomVar', $i, $custom_var_name, $custom_var_value, $custom_var_scope]);";
  190. }
  191. }
  192. // Build tracker code.
  193. $script = 'var _gaq = _gaq || [];';
  194. $script .= '_gaq.push(["_setAccount", ' . drupal_json_encode($id) . ']);';
  195. if (variable_get('googleanalytics_tracker_anonymizeip', 0)) {
  196. // FIXME: The Google API is currently broken and "_gat._anonymizeIp" is only
  197. // a workaround until "_anonymizeIp" has been implemented/fixed.
  198. $script .= '_gaq.push(["_gat._anonymizeIp"]);';
  199. }
  200. // Domain tracking type.
  201. global $cookie_domain;
  202. $domain_mode = variable_get('googleanalytics_domain_mode', 0);
  203. // Per RFC 2109, cookie domains must contain at least one dot other than the
  204. // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
  205. if ($domain_mode == 1 && count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
  206. $script .= '_gaq.push(["_setDomainName", ' . drupal_json_encode($cookie_domain) . ']);';
  207. }
  208. elseif ($domain_mode == 2) {
  209. $script .= '_gaq.push(["_setDomainName", "none"]);';
  210. $script .= '_gaq.push(["_setAllowLinker", true]);';
  211. }
  212. if (!empty($custom_var)) {
  213. $script .= $custom_var;
  214. }
  215. if (!empty($codesnippet_before)) {
  216. $script .= $codesnippet_before;
  217. }
  218. if (empty($url_custom)) {
  219. $script .= '_gaq.push(["_trackPageview"]);';
  220. }
  221. else {
  222. $script .= '_gaq.push(["_trackPageview", ' . $url_custom . ']);';
  223. }
  224. if (!empty($message_events)) {
  225. $script .= $message_events;
  226. }
  227. if (!empty($codesnippet_after)) {
  228. $script .= $codesnippet_after;
  229. }
  230. $script .= '(function() {';
  231. $script .= 'var ga = document.createElement("script");';
  232. $script .= 'ga.type = "text/javascript";';
  233. $script .= 'ga.async = true;';
  234. // Which version of the tracking library should be used?
  235. if ($trackdoubleclick = variable_get('googleanalytics_trackdoubleclick', FALSE)) {
  236. $library_tracker_url = 'stats.g.doubleclick.net/dc.js';
  237. $library_cache_url = 'http://' . $library_tracker_url;
  238. }
  239. else {
  240. $library_tracker_url = '.google-analytics.com/ga.js';
  241. $library_cache_url = 'http://www' . $library_tracker_url;
  242. }
  243. // Should a local cached copy of ga.js be used?
  244. if (variable_get('googleanalytics_cache', 0) && $url = _googleanalytics_cache($library_cache_url)) {
  245. // A dummy query-string is added to filenames, to gain control over
  246. // browser-caching. The string changes on every update or full cache
  247. // flush, forcing browsers to load a new copy of the files, as the
  248. // URL changed.
  249. $query_string = '?' . variable_get('css_js_query_string', '0');
  250. $script .= 'ga.src = "' . $url . $query_string . '";';
  251. }
  252. else {
  253. // Library paths do not follow the same naming convention.
  254. if ($trackdoubleclick) {
  255. $script .= 'ga.src = ("https:" == document.location.protocol ? "https://" : "http://") + "' . $library_tracker_url . '";';
  256. }
  257. else {
  258. $script .= 'ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + "' . $library_tracker_url . '";';
  259. }
  260. }
  261. $script .= 'var s = document.getElementsByTagName("script")[0];';
  262. $script .= 's.parentNode.insertBefore(ga, s);';
  263. $script .= '})();';
  264. drupal_add_js($script, array('scope' => $scope, 'type' => 'inline'));
  265. }
  266. }
  267. /**
  268. * Implements hook_field_extra_fields().
  269. */
  270. function googleanalytics_field_extra_fields() {
  271. $extra['user']['user']['form']['googleanalytics'] = array(
  272. 'label' => t('Google Analytics configuration'),
  273. 'description' => t('Google Analytics module form element.'),
  274. 'weight' => 3,
  275. );
  276. return $extra;
  277. }
  278. /**
  279. * Implements hook_form_FORM_ID_alter().
  280. *
  281. * Allow users to decide if tracking code will be added to pages or not.
  282. */
  283. function googleanalytics_form_user_profile_form_alter(&$form, &$form_state) {
  284. $account = $form['#user'];
  285. $category = $form['#user_category'];
  286. if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('googleanalytics_custom', 0)) != 0 && _googleanalytics_visibility_roles($account)) {
  287. $form['googleanalytics'] = array(
  288. '#type' => 'fieldset',
  289. '#title' => t('Google Analytics configuration'),
  290. '#weight' => 3,
  291. '#collapsible' => TRUE,
  292. '#tree' => TRUE
  293. );
  294. switch ($custom) {
  295. case 1:
  296. $description = t('Users are tracked by default, but you are able to opt out.');
  297. break;
  298. case 2:
  299. $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
  300. break;
  301. }
  302. // Disable tracking for visitors who have opted out from tracking via DNT (Do-Not-Track) header.
  303. $disabled = FALSE;
  304. if (variable_get('googleanalytics_privacy_donottrack', 1) && !empty($_SERVER['HTTP_DNT'])) {
  305. $disabled = TRUE;
  306. // Override settings value.
  307. $account->data['googleanalytics']['custom'] = FALSE;
  308. $description .= '<span class="admin-disabled">';
  309. $description .= ' ' . t('You have opted out from tracking via browser privacy settings.');
  310. $description .= '</span>';
  311. }
  312. $form['googleanalytics']['custom'] = array(
  313. '#type' => 'checkbox',
  314. '#title' => t('Enable user tracking'),
  315. '#description' => $description,
  316. '#default_value' => isset($account->data['googleanalytics']['custom']) ? $account->data['googleanalytics']['custom'] : ($custom == 1),
  317. '#disabled' => $disabled,
  318. );
  319. return $form;
  320. }
  321. }
  322. /**
  323. * Implements hook_user_presave().
  324. */
  325. function googleanalytics_user_presave(&$edit, $account, $category) {
  326. if (isset($edit['googleanalytics']['custom'])) {
  327. $edit['data']['googleanalytics']['custom'] = $edit['googleanalytics']['custom'];
  328. }
  329. }
  330. /**
  331. * Implements hook_cron().
  332. */
  333. function googleanalytics_cron() {
  334. // Regenerate the tracking code file every day.
  335. if (REQUEST_TIME - variable_get('googleanalytics_last_cache', 0) >= 86400 && variable_get('googleanalytics_cache', 0)) {
  336. // Which version of the tracking library should be used?
  337. if (variable_get('googleanalytics_trackdoubleclick', FALSE)) {
  338. _googleanalytics_cache('http://stats.g.doubleclick.net/dc.js', TRUE);
  339. }
  340. else {
  341. _googleanalytics_cache('http://www.google-analytics.com/ga.js', TRUE);
  342. }
  343. variable_set('googleanalytics_last_cache', REQUEST_TIME);
  344. }
  345. }
  346. /**
  347. * Implements hook_preprocess_search_results().
  348. *
  349. * Collects and adds the number of search results to the head.
  350. */
  351. function googleanalytics_preprocess_search_results(&$variables) {
  352. // There is no search result $variable available that hold the number of items
  353. // found. But the pager item mumber can tell the number of search results.
  354. global $pager_total_items;
  355. drupal_add_js('window.googleanalytics_search_results = ' . intval($pager_total_items[0]) . ';', array('type' => 'inline', 'group' => JS_LIBRARY-1));
  356. }
  357. /**
  358. * Helper function for grabbing search keys. Function is missing in D7.
  359. *
  360. * http://api.drupal.org/api/function/search_get_keys/6
  361. */
  362. function googleanalytics_search_get_keys() {
  363. static $return;
  364. if (!isset($return)) {
  365. // Extract keys as remainder of path
  366. // Note: support old GET format of searches for existing links.
  367. $path = explode('/', $_GET['q'], 3);
  368. $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
  369. $return = count($path) == 3 ? $path[2] : $keys;
  370. }
  371. return $return;
  372. }
  373. /**
  374. * Download/Synchronize/Cache tracking code file locally.
  375. *
  376. * @param $location
  377. * The full URL to the external javascript file.
  378. * @param $sync_cached_file
  379. * Synchronize tracking code and update if remote file have changed.
  380. * @return mixed
  381. * The path to the local javascript file on success, boolean FALSE on failure.
  382. */
  383. function _googleanalytics_cache($location, $sync_cached_file = FALSE) {
  384. $path = 'public://googleanalytics';
  385. $file_destination = $path . '/' . basename($location);
  386. if (!file_exists($file_destination) || $sync_cached_file) {
  387. // Download the latest tracking code.
  388. $result = drupal_http_request($location);
  389. if ($result->code == 200) {
  390. if (file_exists($file_destination)) {
  391. // Synchronize tracking code and and replace local file if outdated.
  392. $data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
  393. $data_hash_remote = drupal_hash_base64($result->data);
  394. // Check that the files directory is writable.
  395. if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
  396. // Save updated tracking code file to disk.
  397. file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
  398. watchdog('googleanalytics', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);
  399. // Change query-strings on css/js files to enforce reload for all users.
  400. _drupal_flush_css_js();
  401. }
  402. }
  403. else {
  404. // Check that the files directory is writable.
  405. if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
  406. // There is no need to flush JS here as core refreshes JS caches
  407. // automatically, if new files are added.
  408. file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
  409. watchdog('googleanalytics', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);
  410. // Return the local JS file path.
  411. return file_create_url($file_destination);
  412. }
  413. }
  414. }
  415. }
  416. else {
  417. // Return the local JS file path.
  418. return file_create_url($file_destination);
  419. }
  420. }
  421. /**
  422. * Delete cached files and directory.
  423. */
  424. function googleanalytics_clear_js_cache() {
  425. $path = 'public://googleanalytics';
  426. if (file_prepare_directory($path)) {
  427. file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
  428. drupal_rmdir($path);
  429. // Change query-strings on css/js files to enforce reload for all users.
  430. _drupal_flush_css_js();
  431. watchdog('googleanalytics', 'Local cache has been purged.', array(), WATCHDOG_INFO);
  432. }
  433. }
  434. /**
  435. * Tracking visibility check for an user object.
  436. *
  437. * @param $account
  438. * A user object containing an array of roles to check.
  439. * @return boolean
  440. * A decision on if the current user is being tracked by Google Analytics.
  441. */
  442. function _googleanalytics_visibility_user($account) {
  443. $enabled = FALSE;
  444. // Is current user a member of a role that should be tracked?
  445. if (_googleanalytics_visibility_header($account) && _googleanalytics_visibility_roles($account)) {
  446. // Use the user's block visibility setting, if necessary.
  447. if (($custom = variable_get('googleanalytics_custom', 0)) != 0) {
  448. if ($account->uid && isset($account->data['googleanalytics']['custom'])) {
  449. $enabled = $account->data['googleanalytics']['custom'];
  450. }
  451. else {
  452. $enabled = ($custom == 1);
  453. }
  454. }
  455. else {
  456. $enabled = TRUE;
  457. }
  458. }
  459. return $enabled;
  460. }
  461. /**
  462. * Based on visibility setting this function returns TRUE if GA code should
  463. * be added for the current role and otherwise FALSE.
  464. */
  465. function _googleanalytics_visibility_roles($account) {
  466. $visibility = variable_get('googleanalytics_visibility_roles', 0);
  467. $enabled = $visibility;
  468. $roles = variable_get('googleanalytics_roles', array());
  469. if (array_sum($roles) > 0) {
  470. // One or more roles are selected.
  471. foreach (array_keys($account->roles) as $rid) {
  472. // Is the current user a member of one of these roles?
  473. if (isset($roles[$rid]) && $rid == $roles[$rid]) {
  474. // Current user is a member of a role that should be tracked/excluded from tracking.
  475. $enabled = !$visibility;
  476. break;
  477. }
  478. }
  479. }
  480. else {
  481. // No role is selected for tracking, therefore all roles should be tracked.
  482. $enabled = TRUE;
  483. }
  484. return $enabled;
  485. }
  486. /**
  487. * Based on visibility setting this function returns TRUE if GA code should
  488. * be added to the current page and otherwise FALSE.
  489. */
  490. function _googleanalytics_visibility_pages() {
  491. static $page_match;
  492. // Cache visibility result if function is called more than once.
  493. if (!isset($page_match)) {
  494. $visibility = variable_get('googleanalytics_visibility_pages', 0);
  495. $setting_pages = variable_get('googleanalytics_pages', GOOGLEANALYTICS_PAGES);
  496. // Match path if necessary.
  497. if (!empty($setting_pages)) {
  498. // Convert path to lowercase. This allows comparison of the same path
  499. // with different case. Ex: /Page, /page, /PAGE.
  500. $pages = drupal_strtolower($setting_pages);
  501. if ($visibility < 2) {
  502. // Convert the Drupal path to lowercase
  503. $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
  504. // Compare the lowercase internal and lowercase path alias (if any).
  505. $page_match = drupal_match_path($path, $pages);
  506. if ($path != $_GET['q']) {
  507. $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
  508. }
  509. // When $visibility has a value of 0, the tracking code is displayed on
  510. // all pages except those listed in $pages. When set to 1, it
  511. // is displayed only on those pages listed in $pages.
  512. $page_match = !($visibility xor $page_match);
  513. }
  514. elseif (module_exists('php')) {
  515. $page_match = php_eval($setting_pages);
  516. }
  517. else {
  518. $page_match = FALSE;
  519. }
  520. }
  521. else {
  522. $page_match = TRUE;
  523. }
  524. }
  525. return $page_match;
  526. }
  527. /**
  528. * Based on headers send by clients this function returns TRUE if GA code should
  529. * be added to the current page and otherwise FALSE.
  530. */
  531. function _googleanalytics_visibility_header($account) {
  532. if (($account->uid || variable_get('cache', 0) == 0) && variable_get('googleanalytics_privacy_donottrack', 1) && !empty($_SERVER['HTTP_DNT'])) {
  533. // Disable tracking if caching is disabled or a visitors is logged in and
  534. // have opted out from tracking via DNT (Do-Not-Track) header.
  535. return FALSE;
  536. }
  537. return TRUE;
  538. }