googleanalytics.module 26 KB

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