googleanalytics.module 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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 <https://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 https://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' => 'https://marketingplatform.google.com/about/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 $base_path, $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'] = (int) $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 https://www.google.com/support/analytics/bin/answer.py?answer=86927
  183. $url_custom = '"' . $base_path . '403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
  184. }
  185. elseif ($status == '404 Not Found') {
  186. $url_custom = '"' . $base_path . '404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
  187. }
  188. // #2693595: User has entered an invalid login and clicked on forgot
  189. // password link. This link contains the username or email address and may
  190. // get send to Google if we do not override it. Override only if 'name'
  191. // query param exists. Last custom url condition, this need to win.
  192. //
  193. // URLs to protect are:
  194. // - user/password?name=username
  195. // - user/password?name=foo@example.com
  196. if (arg(0) == 'user' && arg(1) == 'password' && array_key_exists('name', drupal_get_query_parameters())) {
  197. $url_custom = '"' . $base_path . 'user/password"';
  198. }
  199. // Add custom dimensions and metrics.
  200. $custom_var = '';
  201. foreach (array('dimension', 'metric') as $googleanalytics_custom_type) {
  202. $googleanalytics_custom_vars = variable_get('googleanalytics_custom_' . $googleanalytics_custom_type, array());
  203. // Are there dimensions or metrics configured?
  204. if (!empty($googleanalytics_custom_vars)) {
  205. // Add all the configured variables to the content.
  206. foreach ($googleanalytics_custom_vars as $googleanalytics_custom_var) {
  207. // Replace tokens in values.
  208. $types = array();
  209. $node = menu_get_object();
  210. if (is_object($node)) {
  211. $types += array('node' => $node);
  212. }
  213. $googleanalytics_custom_var['value'] = token_replace($googleanalytics_custom_var['value'], $types, array('clear' => TRUE));
  214. // Suppress empty values.
  215. if (!drupal_strlen(trim($googleanalytics_custom_var['value']))) {
  216. continue;
  217. }
  218. // Per documentation the max length of a dimension is 150 bytes.
  219. // A metric has no length limitation. It's not documented if this
  220. // limit means 150 bytes after url encoding or before.
  221. // See https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#customs
  222. if ($googleanalytics_custom_type == 'dimension' && drupal_strlen($googleanalytics_custom_var['value']) > 150) {
  223. $googleanalytics_custom_var['value'] = substr($googleanalytics_custom_var['value'], 0, 150);
  224. }
  225. // Cast metric values for json_encode to data type numeric.
  226. if ($googleanalytics_custom_type == 'metric') {
  227. settype($googleanalytics_custom_var['value'], 'float');
  228. };
  229. // Add variables to tracker.
  230. $custom_var .= 'ga("set", ' . drupal_json_encode($googleanalytics_custom_type . $googleanalytics_custom_var['index']) . ', ' . drupal_json_encode($googleanalytics_custom_var['value']) . ');';
  231. }
  232. }
  233. }
  234. // Build tracker code.
  235. $script = '(function(i,s,o,g,r,a,m){';
  236. $script .= 'i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){';
  237. $script .= '(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),';
  238. $script .= 'm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)';
  239. $script .= '})(window,document,"script",';
  240. // Which version of the tracking library should be used?
  241. $library_tracker_url = 'https://www.google-analytics.com/' . ($debug ? 'analytics_debug.js' : 'analytics.js');
  242. // Should a local cached copy of analytics.js be used?
  243. if (variable_get('googleanalytics_cache', 0) && $url = _googleanalytics_cache($library_tracker_url)) {
  244. // A dummy query-string is added to filenames, to gain control over
  245. // browser-caching. The string changes on every update or full cache
  246. // flush, forcing browsers to load a new copy of the files, as the
  247. // URL changed.
  248. $query_string = '?' . variable_get('css_js_query_string', '0');
  249. $script .= '"' . $url . $query_string . '"';
  250. }
  251. else {
  252. $script .= '"' . $library_tracker_url . '"';
  253. }
  254. $script .= ',"ga");';
  255. // Add any custom code snippets if specified.
  256. $codesnippet_create = variable_get('googleanalytics_codesnippet_create', array());
  257. $codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
  258. $codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');
  259. // Build the create only fields list.
  260. $create_only_fields = array('cookieDomain' => 'auto');
  261. $create_only_fields = array_merge($create_only_fields, $codesnippet_create);
  262. // Domain tracking type.
  263. global $cookie_domain;
  264. $domain_mode = variable_get('googleanalytics_domain_mode', 0);
  265. $googleanalytics_adsense_script = '';
  266. // Per RFC 2109, cookie domains must contain at least one dot other than the
  267. // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
  268. if ($domain_mode == 1 && count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
  269. $create_only_fields = array_merge($create_only_fields, array('cookieDomain' => $cookie_domain));
  270. $googleanalytics_adsense_script .= 'window.google_analytics_domain_name = ' . drupal_json_encode($cookie_domain) . ';';
  271. }
  272. elseif ($domain_mode == 2) {
  273. // Cross Domain tracking. 'autoLinker' need to be enabled in 'create'.
  274. $create_only_fields = array_merge($create_only_fields, array('allowLinker' => TRUE));
  275. $googleanalytics_adsense_script .= 'window.google_analytics_domain_name = "none";';
  276. }
  277. // Track logged in users across all devices.
  278. if (variable_get('googleanalytics_trackuserid', 0) && user_is_logged_in()) {
  279. $create_only_fields['userId'] = google_analytics_user_id_hash($user->uid);
  280. }
  281. // Create a tracker.
  282. $script .= 'ga("create", ' . drupal_json_encode($id) . ', ' . drupal_json_encode($create_only_fields) .');';
  283. // Prepare Adsense tracking.
  284. $googleanalytics_adsense_script .= 'window.google_analytics_uacct = ' . drupal_json_encode($id) . ';';
  285. // Add enhanced link attribution after 'create', but before 'pageview' send.
  286. // @see https://support.google.com/analytics/answer/2558867
  287. if (variable_get('googleanalytics_tracklinkid', 0)) {
  288. $script .= 'ga("require", "linkid", "linkid.js");';
  289. }
  290. // Add display features after 'create', but before 'pageview' send.
  291. // @see https://support.google.com/analytics/answer/2444872
  292. if (variable_get('googleanalytics_trackdoubleclick', 0)) {
  293. $script .= 'ga("require", "displayfeatures");';
  294. }
  295. // Domain tracking type.
  296. if ($domain_mode == 2) {
  297. // Cross Domain tracking
  298. // https://developers.google.com/analytics/devguides/collection/upgrade/reference/gajs-analyticsjs#cross-domain
  299. $script .= 'ga("require", "linker");';
  300. $script .= 'ga("linker:autoLink", ' . drupal_json_encode($link_settings['trackCrossDomains']) . ');';
  301. }
  302. if (variable_get('googleanalytics_tracker_anonymizeip', 1)) {
  303. $script .= 'ga("set", "anonymizeIp", true);';
  304. }
  305. if (!empty($custom_var)) {
  306. $script .= $custom_var;
  307. }
  308. if (!empty($codesnippet_before)) {
  309. $script .= $codesnippet_before;
  310. }
  311. if (!empty($url_custom)) {
  312. $script .= 'ga("set", "page", ' . $url_custom . ');';
  313. }
  314. $script .= 'ga("send", "pageview");';
  315. if (!empty($message_events)) {
  316. $script .= $message_events;
  317. }
  318. if (!empty($codesnippet_after)) {
  319. $script .= $codesnippet_after;
  320. }
  321. if (variable_get('googleanalytics_trackadsense', FALSE)) {
  322. // Custom tracking. Prepend before all other JavaScript.
  323. // @TODO: https://support.google.com/adsense/answer/98142
  324. // sounds like it could be appended to $script.
  325. drupal_add_js($googleanalytics_adsense_script, array('type' => 'inline', 'group' => JS_LIBRARY-1, 'requires_jquery' => FALSE));
  326. }
  327. drupal_add_js($script, array('scope' => 'header', 'type' => 'inline', 'requires_jquery' => FALSE));
  328. }
  329. }
  330. /**
  331. * Generate user id hash to implement USER_ID.
  332. *
  333. * The USER_ID value should be a unique, persistent, and non-personally
  334. * identifiable string identifier that represents a user or signed-in
  335. * account across devices.
  336. *
  337. * @param int $uid
  338. * User id.
  339. *
  340. * @return string
  341. * User id hash.
  342. */
  343. function google_analytics_user_id_hash($uid) {
  344. return drupal_hmac_base64($uid, drupal_get_private_key() . drupal_get_hash_salt());
  345. }
  346. /**
  347. * Implements hook_field_extra_fields().
  348. */
  349. function googleanalytics_field_extra_fields() {
  350. $extra['user']['user']['form']['googleanalytics'] = array(
  351. 'label' => t('Google Analytics configuration'),
  352. 'description' => t('Google Analytics module form element.'),
  353. 'weight' => 3,
  354. );
  355. return $extra;
  356. }
  357. /**
  358. * Implements hook_form_FORM_ID_alter().
  359. *
  360. * Allow users to decide if tracking code will be added to pages or not.
  361. */
  362. function googleanalytics_form_user_profile_form_alter(&$form, &$form_state) {
  363. $account = $form['#user'];
  364. $category = $form['#user_category'];
  365. if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('googleanalytics_custom', 0)) != 0 && _googleanalytics_visibility_roles($account)) {
  366. $form['googleanalytics'] = array(
  367. '#type' => 'fieldset',
  368. '#title' => t('Google Analytics configuration'),
  369. '#weight' => 3,
  370. '#collapsible' => TRUE,
  371. '#tree' => TRUE
  372. );
  373. switch ($custom) {
  374. case 1:
  375. $description = t('Users are tracked by default, but you are able to opt out.');
  376. break;
  377. case 2:
  378. $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
  379. break;
  380. }
  381. // Disable tracking for visitors who have opted out from tracking via DNT (Do-Not-Track) header.
  382. $disabled = FALSE;
  383. if (variable_get('googleanalytics_privacy_donottrack', 1) && !empty($_SERVER['HTTP_DNT'])) {
  384. $disabled = TRUE;
  385. // Override settings value.
  386. $account->data['googleanalytics']['custom'] = FALSE;
  387. $description .= '<span class="admin-disabled">';
  388. $description .= ' ' . t('You have opted out from tracking via browser privacy settings.');
  389. $description .= '</span>';
  390. }
  391. $form['googleanalytics']['custom'] = array(
  392. '#type' => 'checkbox',
  393. '#title' => t('Enable user tracking'),
  394. '#description' => $description,
  395. '#default_value' => isset($account->data['googleanalytics']['custom']) ? $account->data['googleanalytics']['custom'] : ($custom == 1),
  396. '#disabled' => $disabled,
  397. );
  398. return $form;
  399. }
  400. }
  401. /**
  402. * Implements hook_user_presave().
  403. */
  404. function googleanalytics_user_presave(&$edit, $account, $category) {
  405. if (isset($edit['googleanalytics']['custom'])) {
  406. $edit['data']['googleanalytics']['custom'] = $edit['googleanalytics']['custom'];
  407. }
  408. }
  409. /**
  410. * Implements hook_cron().
  411. */
  412. function googleanalytics_cron() {
  413. // Regenerate the tracking code file every day.
  414. if (REQUEST_TIME - variable_get('googleanalytics_last_cache', 0) >= 86400 && variable_get('googleanalytics_cache', 0)) {
  415. _googleanalytics_cache('https://www.google-analytics.com/analytics.js', TRUE);
  416. variable_set('googleanalytics_last_cache', REQUEST_TIME);
  417. }
  418. }
  419. /**
  420. * Implements hook_preprocess_search_results().
  421. *
  422. * Collects and adds the number of search results to the head.
  423. */
  424. function googleanalytics_preprocess_search_results(&$variables) {
  425. if (variable_get('googleanalytics_site_search', FALSE)) {
  426. // There is no search result $variable available that hold the number of items
  427. // found. But the pager item mumber can tell the number of search results.
  428. global $pager_total_items;
  429. drupal_add_js('window.googleanalytics_search_results = ' . intval($pager_total_items[0]) . ';', array('type' => 'inline', 'group' => JS_LIBRARY-1, 'requires_jquery' => FALSE));
  430. }
  431. }
  432. /**
  433. * Helper function for grabbing search keys. Function is missing in D7.
  434. *
  435. * https://api.drupal.org/api/function/search_get_keys/6
  436. */
  437. function googleanalytics_search_get_keys() {
  438. static $return;
  439. if (!isset($return)) {
  440. // Extract keys as remainder of path
  441. // Note: support old GET format of searches for existing links.
  442. $path = explode('/', $_GET['q'], 3);
  443. $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
  444. $return = count($path) == 3 ? $path[2] : $keys;
  445. }
  446. return $return;
  447. }
  448. /**
  449. * Download/Synchronize/Cache tracking code file locally.
  450. *
  451. * @param $location
  452. * The full URL to the external javascript file.
  453. * @param $synchronize
  454. * Synchronize to local cache if remote file has changed.
  455. * @return mixed
  456. * The path to the local javascript file on success, boolean FALSE on failure.
  457. */
  458. function _googleanalytics_cache($location, $synchronize = FALSE) {
  459. $path = 'public://googleanalytics';
  460. $file_destination = $path . '/' . basename($location);
  461. if (!file_exists($file_destination) || $synchronize) {
  462. // Download the latest tracking code.
  463. $result = drupal_http_request($location);
  464. if ($result->code == 200) {
  465. if (file_exists($file_destination)) {
  466. // Synchronize tracking code and and replace local file if outdated.
  467. $data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
  468. $data_hash_remote = drupal_hash_base64($result->data);
  469. // Check that the files directory is writable.
  470. if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
  471. // Save updated tracking code file to disk.
  472. file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
  473. // Based on Drupal Core drupal_build_css_cache().
  474. if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
  475. file_unmanaged_save_data(gzencode($result->data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE);
  476. }
  477. watchdog('googleanalytics', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);
  478. // Change query-strings on css/js files to enforce reload for all users.
  479. _drupal_flush_css_js();
  480. }
  481. }
  482. else {
  483. // Check that the files directory is writable.
  484. if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
  485. // There is no need to flush JS here as core refreshes JS caches
  486. // automatically, if new files are added.
  487. file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
  488. // Based on Drupal Core drupal_build_css_cache().
  489. if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
  490. file_unmanaged_save_data(gzencode($result->data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE);
  491. }
  492. watchdog('googleanalytics', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);
  493. // Return the local JS file path.
  494. return file_create_url($file_destination);
  495. }
  496. }
  497. }
  498. }
  499. else {
  500. // Return the local JS file path.
  501. return file_create_url($file_destination);
  502. }
  503. }
  504. /**
  505. * Delete cached files and directory.
  506. */
  507. function googleanalytics_clear_js_cache() {
  508. $path = 'public://googleanalytics';
  509. if (file_prepare_directory($path)) {
  510. file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
  511. drupal_rmdir($path);
  512. // Change query-strings on css/js files to enforce reload for all users.
  513. _drupal_flush_css_js();
  514. watchdog('googleanalytics', 'Local cache has been purged.', array(), WATCHDOG_INFO);
  515. }
  516. }
  517. /**
  518. * Tracking visibility check for an user object.
  519. *
  520. * @param $account
  521. * A user object containing an array of roles to check.
  522. * @return boolean
  523. * A decision on if the current user is being tracked by Google Analytics.
  524. */
  525. function _googleanalytics_visibility_user($account) {
  526. $enabled = FALSE;
  527. // Is current user a member of a role that should be tracked?
  528. if (_googleanalytics_visibility_header($account) && _googleanalytics_visibility_roles($account)) {
  529. // Use the user's block visibility setting, if necessary.
  530. if (($custom = variable_get('googleanalytics_custom', 0)) != 0) {
  531. if ($account->uid && isset($account->data['googleanalytics']['custom'])) {
  532. $enabled = $account->data['googleanalytics']['custom'];
  533. }
  534. else {
  535. $enabled = ($custom == 1);
  536. }
  537. }
  538. else {
  539. $enabled = TRUE;
  540. }
  541. }
  542. return $enabled;
  543. }
  544. /**
  545. * Based on visibility setting this function returns TRUE if GA code should
  546. * be added for the current role and otherwise FALSE.
  547. */
  548. function _googleanalytics_visibility_roles($account) {
  549. $visibility = variable_get('googleanalytics_visibility_roles', 0);
  550. $enabled = $visibility;
  551. $roles = variable_get('googleanalytics_roles', array());
  552. if (array_sum($roles) > 0) {
  553. // One or more roles are selected.
  554. foreach (array_keys($account->roles) as $rid) {
  555. // Is the current user a member of one of these roles?
  556. if (isset($roles[$rid]) && $rid == $roles[$rid]) {
  557. // Current user is a member of a role that should be tracked/excluded from tracking.
  558. $enabled = !$visibility;
  559. break;
  560. }
  561. }
  562. }
  563. else {
  564. // No role is selected for tracking, therefore all roles should be tracked.
  565. $enabled = TRUE;
  566. }
  567. return $enabled;
  568. }
  569. /**
  570. * Based on visibility setting this function returns TRUE if GA code should
  571. * be added to the current page and otherwise FALSE.
  572. */
  573. function _googleanalytics_visibility_pages() {
  574. static $page_match;
  575. // Cache visibility result if function is called more than once.
  576. if (!isset($page_match)) {
  577. $visibility = variable_get('googleanalytics_visibility_pages', 0);
  578. $setting_pages = variable_get('googleanalytics_pages', GOOGLEANALYTICS_PAGES);
  579. // Match path if necessary.
  580. if (!empty($setting_pages)) {
  581. // Convert path to lowercase. This allows comparison of the same path
  582. // with different case. Ex: /Page, /page, /PAGE.
  583. $pages = drupal_strtolower($setting_pages);
  584. if ($visibility < 2) {
  585. // Convert the Drupal path to lowercase
  586. $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
  587. // Compare the lowercase internal and lowercase path alias (if any).
  588. $page_match = drupal_match_path($path, $pages);
  589. if ($path != $_GET['q']) {
  590. $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
  591. }
  592. // When $visibility has a value of 0, the tracking code is displayed on
  593. // all pages except those listed in $pages. When set to 1, it
  594. // is displayed only on those pages listed in $pages.
  595. $page_match = !($visibility xor $page_match);
  596. }
  597. elseif (module_exists('php')) {
  598. $page_match = php_eval($setting_pages);
  599. }
  600. else {
  601. $page_match = FALSE;
  602. }
  603. }
  604. else {
  605. $page_match = TRUE;
  606. }
  607. }
  608. return $page_match;
  609. }
  610. /**
  611. * Based on headers send by clients this function returns TRUE if GA code should
  612. * be added to the current page and otherwise FALSE.
  613. */
  614. function _googleanalytics_visibility_header($account) {
  615. if (($account->uid || variable_get('cache', 0) == 0) && variable_get('googleanalytics_privacy_donottrack', 1) && !empty($_SERVER['HTTP_DNT'])) {
  616. // Disable tracking if caching is disabled or a visitors is logged in and
  617. // have opted out from tracking via DNT (Do-Not-Track) header.
  618. return FALSE;
  619. }
  620. return TRUE;
  621. }