googleanalytics.module 26 KB

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