googleanalytics.admin.inc 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. <?php
  2. /**
  3. * @file
  4. * Administrative page callbacks for the googleanalytics module.
  5. */
  6. /**
  7. * Implements hook_admin_settings() for module settings configuration.
  8. */
  9. function googleanalytics_admin_settings_form($form_state) {
  10. $form['account'] = array(
  11. '#type' => 'fieldset',
  12. '#title' => t('General settings'),
  13. );
  14. $form['account']['googleanalytics_account'] = array(
  15. '#title' => t('Web Property ID'),
  16. '#type' => 'textfield',
  17. '#default_value' => variable_get('googleanalytics_account', 'UA-'),
  18. '#size' => 20,
  19. '#maxlength' => 20,
  20. '#required' => TRUE,
  21. '#description' => t('This ID is unique to each site you want to track separately, and is in the form of UA-xxxxxxx-yy. To get a Web Property ID, <a href="@analytics">register your site with Google Analytics</a>, or if you already have registered your site, go to your Google Analytics Settings page to see the ID next to every site profile. <a href="@webpropertyid">Find more information in the documentation</a>.', array('@analytics' => 'https://marketingplatform.google.com/about/analytics/', '@webpropertyid' => url('https://developers.google.com/analytics/resources/concepts/gaConceptsAccounts', array('fragment' => 'webProperty')))),
  22. );
  23. $form['account']['googleanalytics_premium'] = array(
  24. '#type' => 'checkbox',
  25. '#title' => t('Premium account'),
  26. '#description' => t('If you are a Google Analytics Premium customer, you can use up to 200 instead of 20 custom dimensions and metrics.'),
  27. '#default_value' => variable_get('googleanalytics_premium', FALSE),
  28. );
  29. // Visibility settings.
  30. $form['tracking_title'] = array(
  31. '#type' => 'item',
  32. '#title' => t('Tracking scope'),
  33. );
  34. $form['tracking'] = array(
  35. '#type' => 'vertical_tabs',
  36. '#attached' => array(
  37. 'js' => array(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.admin.js'),
  38. ),
  39. );
  40. $form['tracking']['domain_tracking'] = array(
  41. '#type' => 'fieldset',
  42. '#title' => t('Domains'),
  43. );
  44. global $cookie_domain;
  45. $multiple_sub_domains = array();
  46. foreach (array('www', 'app', 'shop') as $subdomain) {
  47. if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
  48. $multiple_sub_domains[] = $subdomain . $cookie_domain;
  49. }
  50. // IP addresses or localhost.
  51. else {
  52. $multiple_sub_domains[] = $subdomain . '.example.com';
  53. }
  54. }
  55. $multiple_toplevel_domains = array();
  56. foreach (array('.com', '.net', '.org') as $tldomain) {
  57. $host = $_SERVER['HTTP_HOST'];
  58. $domain = substr($host, 0, strrpos($host, '.'));
  59. if (count(explode('.', $host)) > 2 && !is_numeric(str_replace('.', '', $host))) {
  60. $multiple_toplevel_domains[] = $domain . $tldomain;
  61. }
  62. // IP addresses or localhost
  63. else {
  64. $multiple_toplevel_domains[] = 'www.example' . $tldomain;
  65. }
  66. }
  67. $form['tracking']['domain_tracking']['googleanalytics_domain_mode'] = array(
  68. '#type' => 'radios',
  69. '#title' => t('What are you tracking?'),
  70. '#options' => array(
  71. 0 => t('A single domain (default)') . '<div class="description">' . t('Domain: @domain', array('@domain' => $_SERVER['HTTP_HOST'])) . '</div>',
  72. 1 => t('One domain with multiple subdomains') . '<div class="description">' . t('Examples: @domains', array('@domains' => implode(', ', $multiple_sub_domains))) . '</div>',
  73. 2 => t('Multiple top-level domains') . '<div class="description">' . t('Examples: @domains', array('@domains' => implode(', ', $multiple_toplevel_domains))) . '</div>',
  74. ),
  75. '#default_value' => variable_get('googleanalytics_domain_mode', 0),
  76. );
  77. $form['tracking']['domain_tracking']['googleanalytics_cross_domains'] = array(
  78. '#title' => t('List of top-level domains'),
  79. '#type' => 'textarea',
  80. '#default_value' => variable_get('googleanalytics_cross_domains', ''),
  81. '#description' => t('If you selected "Multiple top-level domains" above, enter all related top-level domains. Add one domain per line. By default, the data in your reports only includes the path and name of the page, and not the domain name. For more information see section <em>Show separate domain names</em> in <a href="@url">Tracking Multiple Domains</a>.', array('@url' => 'https://support.google.com/analytics/answer/1034342')),
  82. '#states' => array(
  83. 'enabled' => array(
  84. ':input[name="googleanalytics_domain_mode"]' => array('value' => '2'),
  85. ),
  86. 'required' => array(
  87. ':input[name="googleanalytics_domain_mode"]' => array('value' => '2'),
  88. ),
  89. ),
  90. );
  91. // Page specific visibility configurations.
  92. $php_access = user_access('use PHP for tracking visibility');
  93. $visibility = variable_get('googleanalytics_visibility_pages', 0);
  94. $pages = variable_get('googleanalytics_pages', GOOGLEANALYTICS_PAGES);
  95. $form['tracking']['page_vis_settings'] = array(
  96. '#type' => 'fieldset',
  97. '#title' => t('Pages'),
  98. '#collapsible' => TRUE,
  99. '#collapsed' => TRUE,
  100. );
  101. if ($visibility == 2 && !$php_access) {
  102. $form['tracking']['page_vis_settings'] = array();
  103. $form['tracking']['page_vis_settings']['googleanalytics_visibility_pages'] = array('#type' => 'value', '#value' => 2);
  104. $form['tracking']['page_vis_settings']['googleanalytics_pages'] = array('#type' => 'value', '#value' => $pages);
  105. }
  106. else {
  107. $options = array(
  108. t('Every page except the listed pages'),
  109. t('The listed pages only'),
  110. );
  111. $description = t("Specify pages by using their paths. Enter one path per line. The '*' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page.", array('%blog' => 'blog', '%blog-wildcard' => 'blog/*', '%front' => '<front>'));
  112. if (module_exists('php') && $php_access) {
  113. $options[] = t('Pages on which this PHP code returns <code>TRUE</code> (experts only)');
  114. $title = t('Pages or PHP code');
  115. $description .= ' ' . t('If the PHP option is chosen, enter PHP code between %php. Note that executing incorrect PHP code can break your Drupal site.', array('%php' => '<?php ?>'));
  116. }
  117. else {
  118. $title = t('Pages');
  119. }
  120. $form['tracking']['page_vis_settings']['googleanalytics_visibility_pages'] = array(
  121. '#type' => 'radios',
  122. '#title' => t('Add tracking to specific pages'),
  123. '#options' => $options,
  124. '#default_value' => $visibility,
  125. );
  126. $form['tracking']['page_vis_settings']['googleanalytics_pages'] = array(
  127. '#type' => 'textarea',
  128. '#title' => $title,
  129. '#title_display' => 'invisible',
  130. '#default_value' => $pages,
  131. '#description' => $description,
  132. '#rows' => 10,
  133. );
  134. }
  135. // Render the role overview.
  136. $form['tracking']['role_vis_settings'] = array(
  137. '#type' => 'fieldset',
  138. '#title' => t('Roles'),
  139. );
  140. $form['tracking']['role_vis_settings']['googleanalytics_visibility_roles'] = array(
  141. '#type' => 'radios',
  142. '#title' => t('Add tracking for specific roles'),
  143. '#options' => array(
  144. t('Add to the selected roles only'),
  145. t('Add to every role except the selected ones'),
  146. ),
  147. '#default_value' => variable_get('googleanalytics_visibility_roles', 0),
  148. );
  149. $role_options = array_map('check_plain', user_roles());
  150. $form['tracking']['role_vis_settings']['googleanalytics_roles'] = array(
  151. '#type' => 'checkboxes',
  152. '#title' => t('Roles'),
  153. '#default_value' => variable_get('googleanalytics_roles', array()),
  154. '#options' => $role_options,
  155. '#description' => t('If none of the roles are selected, all users will be tracked. If a user has any of the roles checked, that user will be tracked (or excluded, depending on the setting above).'),
  156. );
  157. // Standard tracking configurations.
  158. $form['tracking']['user_vis_settings'] = array(
  159. '#type' => 'fieldset',
  160. '#title' => t('Users'),
  161. );
  162. $t_permission = array('%permission' => t('Opt-in or out of tracking'));
  163. $form['tracking']['user_vis_settings']['googleanalytics_custom'] = array(
  164. '#type' => 'radios',
  165. '#title' => t('Allow users to customize tracking on their account page'),
  166. '#options' => array(
  167. t('No customization allowed'),
  168. t('Tracking on by default, users with %permission permission can opt out', $t_permission),
  169. t('Tracking off by default, users with %permission permission can opt in', $t_permission),
  170. ),
  171. '#default_value' => variable_get('googleanalytics_custom', 0),
  172. );
  173. $form['tracking']['user_vis_settings']['googleanalytics_trackuserid'] = array(
  174. '#type' => 'checkbox',
  175. '#title' => t('Track User ID'),
  176. '#default_value' => variable_get('googleanalytics_trackuserid', 0),
  177. '#description' => t('User ID enables the analysis of groups of sessions, across devices, using a unique, persistent, and non-personally identifiable ID string representing a user. <a href="@url">Learn more about the benefits of using User ID</a>.', array('@url' => 'https://support.google.com/analytics/answer/3123663')),
  178. );
  179. // Link specific configurations.
  180. $form['tracking']['linktracking'] = array(
  181. '#type' => 'fieldset',
  182. '#title' => t('Links and downloads'),
  183. );
  184. $form['tracking']['linktracking']['googleanalytics_trackoutbound'] = array(
  185. '#type' => 'checkbox',
  186. '#title' => t('Track clicks on outbound links'),
  187. '#default_value' => variable_get('googleanalytics_trackoutbound', 1),
  188. );
  189. $form['tracking']['linktracking']['googleanalytics_trackmailto'] = array(
  190. '#type' => 'checkbox',
  191. '#title' => t('Track clicks on mailto links'),
  192. '#default_value' => variable_get('googleanalytics_trackmailto', 1),
  193. );
  194. $form['tracking']['linktracking']['googleanalytics_trackfiles'] = array(
  195. '#type' => 'checkbox',
  196. '#title' => t('Track downloads (clicks on file links) for the following extensions'),
  197. '#default_value' => variable_get('googleanalytics_trackfiles', 1),
  198. );
  199. $form['tracking']['linktracking']['googleanalytics_trackfiles_extensions'] = array(
  200. '#title' => t('List of download file extensions'),
  201. '#title_display' => 'invisible',
  202. '#type' => 'textfield',
  203. '#default_value' => variable_get('googleanalytics_trackfiles_extensions', GOOGLEANALYTICS_TRACKFILES_EXTENSIONS),
  204. '#description' => t('A file extension list separated by the | character that will be tracked as download when clicked. Regular expressions are supported. For example: !extensions', array('!extensions' => GOOGLEANALYTICS_TRACKFILES_EXTENSIONS)),
  205. '#maxlength' => 500,
  206. '#states' => array(
  207. 'enabled' => array(
  208. ':input[name="googleanalytics_trackfiles"]' => array('checked' => TRUE),
  209. ),
  210. // Note: Form required marker is not visible as title is invisible.
  211. 'required' => array(
  212. ':input[name="googleanalytics_trackfiles"]' => array('checked' => TRUE),
  213. ),
  214. ),
  215. );
  216. $colorbox_dependencies = '<div class="admin-requirements">';
  217. $colorbox_dependencies .= t('Requires: !module-list', array('!module-list' => (module_exists('colorbox') ? t('@module (<span class="admin-enabled">enabled</span>)', array('@module' => 'Colorbox')) : t('@module (<span class="admin-disabled">disabled</span>)', array('@module' => 'Colorbox')))));
  218. $colorbox_dependencies .= '</div>';
  219. $form['tracking']['linktracking']['googleanalytics_trackcolorbox'] = array(
  220. '#type' => 'checkbox',
  221. '#title' => t('Track content in colorbox modal dialogs'),
  222. '#default_value' => variable_get('googleanalytics_trackcolorbox', 1),
  223. '#description' => t('Enable to track the content shown in colorbox modal windows.') . $colorbox_dependencies,
  224. '#disabled' => (module_exists('colorbox') ? FALSE : TRUE),
  225. );
  226. $form['tracking']['linktracking']['googleanalytics_tracklinkid'] = array(
  227. '#type' => 'checkbox',
  228. '#title' => t('Track enhanced link attribution'),
  229. '#default_value' => variable_get('googleanalytics_tracklinkid', 0),
  230. '#description' => t('Enhanced Link Attribution improves the accuracy of your In-Page Analytics report by automatically differentiating between multiple links to the same URL on a single page by using link element IDs. <a href="@url">Enable enhanced link attribution</a> in the Admin UI of your Google Analytics account.', array('@url' => 'https://support.google.com/analytics/answer/2558867')),
  231. );
  232. $form['tracking']['linktracking']['googleanalytics_trackurlfragments'] = array(
  233. '#type' => 'checkbox',
  234. '#title' => t('Track changing URL fragments as pageviews'),
  235. '#default_value' => variable_get('googleanalytics_trackurlfragments', 0),
  236. '#description' => t('By default, the URL reported to Google Analytics will not include the "fragment identifier" (i.e. the portion of the URL beginning with a hash sign), and hash changes by themselves will not cause new pageviews to be reported. Checking this box will cause hash changes to be reported as pageviews (in modern browsers) and all pageview URLs to include the fragment where applicable.'),
  237. );
  238. // Message specific configurations.
  239. $form['tracking']['messagetracking'] = array(
  240. '#type' => 'fieldset',
  241. '#title' => t('Messages'),
  242. );
  243. $form['tracking']['messagetracking']['googleanalytics_trackmessages'] = array(
  244. '#type' => 'checkboxes',
  245. '#title' => t('Track messages of type'),
  246. '#default_value' => variable_get('googleanalytics_trackmessages', array()),
  247. '#description' => t('This will track the selected message types shown to users. Tracking of form validation errors may help you identifying usability issues in your site. For each visit (user session), a maximum of approximately 500 combined GATC requests (both events and page views) can be tracked. Every message is tracked as one individual event. Note that - as the number of events in a session approaches the limit - additional events might not be tracked. Messages from excluded pages cannot be tracked.'),
  248. '#options' => array(
  249. 'status' => t('Status message'),
  250. 'warning' => t('Warning message'),
  251. 'error' => t('Error message'),
  252. ),
  253. );
  254. $form['tracking']['search_and_advertising'] = array(
  255. '#type' => 'fieldset',
  256. '#title' => t('Search and Advertising'),
  257. );
  258. $site_search_dependencies = '<div class="admin-requirements">';
  259. $site_search_dependencies .= t('Requires: !module-list', array('!module-list' => (module_exists('search') ? t('@module (<span class="admin-enabled">enabled</span>)', array('@module' => 'Search')) : t('@module (<span class="admin-disabled">disabled</span>)', array('@module' => 'Search')))));
  260. $site_search_dependencies .= '</div>';
  261. $form['tracking']['search_and_advertising']['googleanalytics_site_search'] = array(
  262. '#type' => 'checkbox',
  263. '#title' => t('Track internal search'),
  264. '#description' => t('If checked, internal search keywords are tracked. You must configure your Google account to use the internal query parameter <strong>search</strong>. For more information see <a href="@url">Setting Up Site Search for a Profile</a>.', array('@url' => 'https://support.google.com/analytics/answer/1012264')) . $site_search_dependencies,
  265. '#default_value' => variable_get('googleanalytics_site_search', FALSE),
  266. '#disabled' => (module_exists('search') ? FALSE : TRUE),
  267. );
  268. $form['tracking']['search_and_advertising']['googleanalytics_trackadsense'] = array(
  269. '#type' => 'checkbox',
  270. '#title' => t('Track AdSense ads'),
  271. '#description' => t('If checked, your AdSense ads will be tracked in your Google Analytics account.'),
  272. '#default_value' => variable_get('googleanalytics_trackadsense', FALSE),
  273. );
  274. $form['tracking']['search_and_advertising']['googleanalytics_trackdoubleclick'] = array(
  275. '#type' => 'checkbox',
  276. '#title' => t('Track display features'),
  277. '#description' => t('The display features plugin can be used to enable Display Advertising Features in Google Analytics, such as Remarketing, Demographics and Interest Reporting, and more. <a href="@displayfeatures">Learn more about Display Advertising Features in Google Analytics</a>. If you choose this option you will need to <a href="@privacy">update your privacy policy</a>.', array('@displayfeatures' => 'https://support.google.com/analytics/answer/3450482', '@privacy' => 'https://support.google.com/analytics/answer/2700409')),
  278. '#default_value' => variable_get('googleanalytics_trackdoubleclick', FALSE),
  279. );
  280. // Privacy specific configurations.
  281. $form['tracking']['privacy'] = array(
  282. '#type' => 'fieldset',
  283. '#title' => t('Privacy'),
  284. );
  285. $form['tracking']['privacy']['googleanalytics_tracker_anonymizeip'] = array(
  286. '#type' => 'checkbox',
  287. '#title' => t('Anonymize visitors IP address'),
  288. '#description' => t('Tell Google Analytics to anonymize the information sent by the tracker objects by removing the last octet of the IP address prior to its storage. Note that this will slightly reduce the accuracy of geographic reporting. In some countries it is not allowed to collect personally identifying information for privacy reasons and this setting may help you to comply with the local laws.'),
  289. '#default_value' => variable_get('googleanalytics_tracker_anonymizeip', 1),
  290. );
  291. $form['tracking']['privacy']['googleanalytics_privacy_donottrack'] = array(
  292. '#type' => 'checkbox',
  293. '#title' => t('Universal web tracking opt-out'),
  294. '#description' => t('If enabled and your server receives the <a href="@donottrack">Do-Not-Track</a> header from the client browser, the Google Analytics module will not embed any tracking code into your site. Compliance with Do Not Track could be purely voluntary, enforced by industry self-regulation, or mandated by state or federal law. Please accept your visitors privacy. If they have opt-out from tracking and advertising, you should accept their personal decision. This feature is currently limited to logged in users and disabled page caching.', array('@donottrack' => 'https://www.eff.org/issues/do-not-track')),
  295. '#default_value' => variable_get('googleanalytics_privacy_donottrack', 1),
  296. );
  297. // Custom Dimensions.
  298. $form['googleanalytics_custom_dimension'] = array(
  299. '#collapsed' => TRUE,
  300. '#collapsible' => TRUE,
  301. '#description' => t('You can set values for Google Analytics <a href="@custom_var_documentation">Custom Dimensions</a> here. You must have already configured your custom dimensions in the <a href="@setup_documentation">Google Analytics Management Interface</a>. You may use tokens. Global and user tokens are always available; on node pages, node tokens are also available. A dimension <em>value</em> is allowed to have a maximum length of 150 bytes. Expect longer values to get trimmed.', array('@custom_var_documentation' => 'https://developers.google.com/analytics/devguides/collection/analyticsjs/custom-dims-mets', '@setup_documentation' => 'https://support.google.com/analytics/answer/2709829')),
  302. '#theme' => 'googleanalytics_admin_custom_var_table',
  303. '#title' => t('Custom dimensions'),
  304. '#tree' => TRUE,
  305. '#type' => 'fieldset',
  306. );
  307. $googleanalytics_custom_dimension = variable_get('googleanalytics_custom_dimension', array());
  308. // Standard Google Analytics accounts support up to 20 custom dimensions,
  309. // premium accounts support up to 200 custom dimensions.
  310. $limit = (variable_get('googleanalytics_premium', FALSE)) ? 200 : 20;
  311. for ($i = 1; $i <= $limit; $i++) {
  312. $form['googleanalytics_custom_dimension']['indexes'][$i]['index'] = array(
  313. '#default_value' => $i,
  314. '#description' => t('Index number'),
  315. '#disabled' => TRUE,
  316. '#size' => 1,
  317. '#title' => t('Custom dimension index #@index', array('@index' => $i)),
  318. '#title_display' => 'invisible',
  319. '#type' => 'textfield',
  320. );
  321. $form['googleanalytics_custom_dimension']['indexes'][$i]['value'] = array(
  322. '#default_value' => isset($googleanalytics_custom_dimension[$i]['value']) ? $googleanalytics_custom_dimension[$i]['value'] : '',
  323. '#description' => t('The custom dimension value.'),
  324. '#maxlength' => 255,
  325. '#title' => t('Custom dimension value #@index', array('@index' => $i)),
  326. '#title_display' => 'invisible',
  327. '#type' => 'textfield',
  328. '#element_validate' => array('googleanalytics_token_element_validate'),
  329. '#token_types' => array('node'),
  330. );
  331. if (module_exists('token')) {
  332. $form['googleanalytics_custom_dimension']['indexes'][$i]['value']['#element_validate'][] = 'token_element_validate';
  333. }
  334. }
  335. $form['googleanalytics_custom_dimension']['googleanalytics_description'] = array(
  336. '#type' => 'item',
  337. '#description' => t('You can supplement Google Analytics\' basic IP address tracking of visitors by segmenting users based on custom dimensions. Section 7 of the <a href="@ga_tos">Google Analytics terms of service</a> requires that You will not (and will not allow any third party to) use the Service to track, collect or upload any data that personally identifies an individual (such as a name, userid, email address or billing information), or other data which can be reasonably linked to such information by Google. You will have and abide by an appropriate Privacy Policy and will comply with all applicable laws and regulations relating to the collection of information from Visitors. You must post a Privacy Policy and that Privacy Policy must provide notice of Your use of cookies that are used to collect traffic data, and You must not circumvent any privacy features (e.g., an opt-out) that are part of the Service.', array('@ga_tos' => 'https://www.google.com/analytics/terms/gb.html')),
  338. );
  339. if (module_exists('token')) {
  340. $form['googleanalytics_custom_dimension']['googleanalytics_token_tree'] = array(
  341. '#theme' => 'token_tree',
  342. '#token_types' => array('node'),
  343. '#dialog' => TRUE,
  344. );
  345. }
  346. // Custom Metrics.
  347. $form['googleanalytics_custom_metric'] = array(
  348. '#collapsed' => TRUE,
  349. '#collapsible' => TRUE,
  350. '#description' => t('You can add Google Analytics <a href="@custom_var_documentation">Custom Metrics</a> here. You must have already configured your custom metrics in the <a href="@setup_documentation">Google Analytics Management Interface</a>. You may use tokens. Global and user tokens are always available; on node pages, node tokens are also available.', array('@custom_var_documentation' => 'https://developers.google.com/analytics/devguides/collection/analyticsjs/custom-dims-mets', '@setup_documentation' => 'https://support.google.com/analytics/answer/2709829')),
  351. '#theme' => 'googleanalytics_admin_custom_var_table',
  352. '#title' => t('Custom metrics'),
  353. '#tree' => TRUE,
  354. '#type' => 'fieldset',
  355. );
  356. $googleanalytics_custom_metric = variable_get('googleanalytics_custom_metric', array());
  357. // Standard Google Analytics accounts support up to 20 custom metrics,
  358. // premium accounts support up to 200 custom metrics.
  359. for ($i = 1; $i <= $limit; $i++) {
  360. $form['googleanalytics_custom_metric']['indexes'][$i]['index'] = array(
  361. '#default_value' => $i,
  362. '#description' => t('Index number'),
  363. '#disabled' => TRUE,
  364. '#size' => 1,
  365. '#title' => t('Custom metric index #@index', array('@index' => $i)),
  366. '#title_display' => 'invisible',
  367. '#type' => 'textfield',
  368. );
  369. $form['googleanalytics_custom_metric']['indexes'][$i]['value'] = array(
  370. '#default_value' => isset($googleanalytics_custom_metric[$i]['value']) ? $googleanalytics_custom_metric[$i]['value'] : '',
  371. '#description' => t('The custom metric value.'),
  372. '#maxlength' => 255,
  373. '#title' => t('Custom metric value #@index', array('@index' => $i)),
  374. '#title_display' => 'invisible',
  375. '#type' => 'textfield',
  376. '#element_validate' => array('googleanalytics_token_element_validate'),
  377. '#token_types' => array('node'),
  378. );
  379. if (module_exists('token')) {
  380. $form['googleanalytics_custom_metric']['indexes'][$i]['value']['#element_validate'][] = 'token_element_validate';
  381. }
  382. }
  383. $form['googleanalytics_custom_metric']['googleanalytics_description'] = array(
  384. '#type' => 'item',
  385. '#description' => t('You can supplement Google Analytics\' basic IP address tracking of visitors by segmenting users based on custom metrics. Section 7 of the <a href="@ga_tos">Google Analytics terms of service</a> requires that You will not (and will not allow any third party to) use the Service to track, collect or upload any data that personally identifies an individual (such as a name, userid, email address or billing information), or other data which can be reasonably linked to such information by Google. You will have and abide by an appropriate Privacy Policy and will comply with all applicable laws and regulations relating to the collection of information from Visitors. You must post a Privacy Policy and that Privacy Policy must provide notice of Your use of cookies that are used to collect traffic data, and You must not circumvent any privacy features (e.g., an opt-out) that are part of the Service.', array('@ga_tos' => 'https://www.google.com/analytics/terms/gb.html')),
  386. );
  387. if (module_exists('token')) {
  388. $form['googleanalytics_custom_metric']['googleanalytics_token_tree'] = array(
  389. '#theme' => 'token_tree',
  390. '#token_types' => array('node'),
  391. '#dialog' => TRUE,
  392. );
  393. }
  394. // Advanced feature configurations.
  395. $form['advanced'] = array(
  396. '#type' => 'fieldset',
  397. '#title' => t('Advanced settings'),
  398. '#collapsible' => TRUE,
  399. '#collapsed' => TRUE,
  400. );
  401. $form['advanced']['googleanalytics_cache'] = array(
  402. '#type' => 'checkbox',
  403. '#title' => t('Locally cache tracking code file'),
  404. '#description' => t("If checked, the tracking code file is retrieved from Google Analytics and cached locally. It is updated daily from Google's servers to ensure updates to tracking code are reflected in the local copy. Do not activate this until after Google Analytics has confirmed that site tracking is working!"),
  405. '#default_value' => variable_get('googleanalytics_cache', 0),
  406. );
  407. // Allow for tracking of the originating node when viewing translation sets.
  408. if (module_exists('translation')) {
  409. $form['advanced']['googleanalytics_translation_set'] = array(
  410. '#type' => 'checkbox',
  411. '#title' => t('Track translation sets as one unit'),
  412. '#description' => t('When a node is part of a translation set, record statistics for the originating node instead. This allows for a translation set to be treated as a single unit.'),
  413. '#default_value' => variable_get('googleanalytics_translation_set', 0),
  414. );
  415. }
  416. $user_access_add_js_snippets = !user_access('add JS snippets for google analytics');
  417. $user_access_add_js_snippets_permission_warning = $user_access_add_js_snippets ? ' <em>' . t('This field has been disabled because you do not have sufficient permissions to edit it.') . '</em>' : '';
  418. $form['advanced']['codesnippet'] = array(
  419. '#type' => 'fieldset',
  420. '#title' => t('Custom JavaScript code'),
  421. '#collapsible' => TRUE,
  422. '#collapsed' => TRUE,
  423. '#description' => t('You can add custom Google Analytics <a href="@snippets">code snippets</a> here. These will be added every time tracking is in effect. Before you add your custom code, you should read the <a href="@ga_concepts_overview">Google Analytics Tracking Code - Functional Overview</a> and the <a href="@ga_js_api">Google Analytics Tracking API</a> documentation. <strong>Do not include the &lt;script&gt; tags</strong>, and always end your code with a semicolon (;).', array('@snippets' => 'https://drupal.org/node/248699', '@ga_concepts_overview' => 'https://developers.google.com/analytics/resources/concepts/gaConceptsTrackingOverview', '@ga_js_api' => 'https://developers.google.com/analytics/devguides/collection/analyticsjs/method-reference')),
  424. );
  425. $form['advanced']['codesnippet']['googleanalytics_codesnippet_create'] = array(
  426. '#type' => 'textarea',
  427. '#title' => t('Create only fields'),
  428. '#default_value' => _googleanalytics_get_name_value_string(variable_get('googleanalytics_codesnippet_create', array())),
  429. '#rows' => 5,
  430. '#description' => t('Enter one value per line, in the format name|value. Settings in this textarea will be added to <code>ga("create", "UA-XXXX-Y", {"name":"value"});</code>. For more information, read <a href="@url">create only fields</a> documentation in the Analytics.js field reference.', array('@url' => 'https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#create')),
  431. '#element_validate' => array('googleanalytics_validate_create_field_values'),
  432. );
  433. $form['advanced']['codesnippet']['googleanalytics_codesnippet_before'] = array(
  434. '#type' => 'textarea',
  435. '#title' => t('Code snippet (before)'),
  436. '#default_value' => variable_get('googleanalytics_codesnippet_before', ''),
  437. '#disabled' => $user_access_add_js_snippets,
  438. '#rows' => 5,
  439. '#description' => t('Code in this textarea will be added <strong>before</strong> <code>ga("send", "pageview");</code>.') . $user_access_add_js_snippets_permission_warning,
  440. );
  441. $form['advanced']['codesnippet']['googleanalytics_codesnippet_after'] = array(
  442. '#type' => 'textarea',
  443. '#title' => t('Code snippet (after)'),
  444. '#default_value' => variable_get('googleanalytics_codesnippet_after', ''),
  445. '#disabled' => $user_access_add_js_snippets,
  446. '#rows' => 5,
  447. '#description' => t('Code in this textarea will be added <strong>after</strong> <code>ga("send", "pageview");</code>. This is useful if you\'d like to track a site in two accounts.') . $user_access_add_js_snippets_permission_warning,
  448. );
  449. $form['advanced']['googleanalytics_debug'] = array(
  450. '#type' => 'checkbox',
  451. '#title' => t('Enable debugging'),
  452. '#description' => t('If checked, the Google Universal Analytics debugging script will be loaded. You should not enable your production site to use this version of the JavaScript. The analytics_debug.js script is larger than the analytics.js tracking code and it is not typically cached. Using it in your production site will slow down your site for all of your users. Again, this is only for your own testing purposes. Debug messages are printed to the <code>window.console</code> object.'),
  453. '#default_value' => variable_get('googleanalytics_debug', 0),
  454. );
  455. return system_settings_form($form);
  456. }
  457. /**
  458. * Implements _form_validate().
  459. */
  460. function googleanalytics_admin_settings_form_validate($form, &$form_state) {
  461. // Trim custom dimensions and metrics.
  462. foreach ($form_state['values']['googleanalytics_custom_dimension']['indexes'] as $dimension) {
  463. $form_state['values']['googleanalytics_custom_dimension']['indexes'][$dimension['index']]['value'] = trim($dimension['value']);
  464. // Remove empty values from the array.
  465. if (!drupal_strlen($form_state['values']['googleanalytics_custom_dimension']['indexes'][$dimension['index']]['value'])) {
  466. unset($form_state['values']['googleanalytics_custom_dimension']['indexes'][$dimension['index']]);
  467. }
  468. }
  469. $form_state['values']['googleanalytics_custom_dimension'] = $form_state['values']['googleanalytics_custom_dimension']['indexes'];
  470. foreach ($form_state['values']['googleanalytics_custom_metric']['indexes'] as $metric) {
  471. $form_state['values']['googleanalytics_custom_metric']['indexes'][$metric['index']]['value'] = trim($metric['value']);
  472. // Remove empty values from the array.
  473. if (!drupal_strlen($form_state['values']['googleanalytics_custom_metric']['indexes'][$metric['index']]['value'])) {
  474. unset($form_state['values']['googleanalytics_custom_metric']['indexes'][$metric['index']]);
  475. }
  476. }
  477. $form_state['values']['googleanalytics_custom_metric'] = $form_state['values']['googleanalytics_custom_metric']['indexes'];
  478. // Trim some text values.
  479. $form_state['values']['googleanalytics_account'] = trim($form_state['values']['googleanalytics_account']);
  480. $form_state['values']['googleanalytics_pages'] = trim($form_state['values']['googleanalytics_pages']);
  481. $form_state['values']['googleanalytics_cross_domains'] = trim($form_state['values']['googleanalytics_cross_domains']);
  482. $form_state['values']['googleanalytics_codesnippet_create'] = _googleanalytics_extract_create_field_values($form_state['values']['googleanalytics_codesnippet_create']);
  483. $form_state['values']['googleanalytics_codesnippet_before'] = trim($form_state['values']['googleanalytics_codesnippet_before']);
  484. $form_state['values']['googleanalytics_codesnippet_after'] = trim($form_state['values']['googleanalytics_codesnippet_after']);
  485. // Replace all type of dashes (n-dash, m-dash, minus) with the normal dashes.
  486. $form_state['values']['googleanalytics_account'] = str_replace(array('–', '—', '−'), '-', $form_state['values']['googleanalytics_account']);
  487. if (!preg_match('/^UA-\d+-\d+$/', $form_state['values']['googleanalytics_account'])) {
  488. form_set_error('googleanalytics_account', t('A valid Google Analytics Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy.'));
  489. }
  490. // If multiple top-level domains has been selected, a domain names list is required.
  491. if ($form_state['values']['googleanalytics_domain_mode'] == 2 && empty($form_state['values']['googleanalytics_cross_domains'])) {
  492. form_set_error('googleanalytics_cross_domains', t('A list of top-level domains is required if <em>Multiple top-level domains</em> has been selected.'));
  493. }
  494. // Clear the domain list if cross domains are disabled.
  495. if ($form_state['values']['googleanalytics_domain_mode'] != 2) {
  496. $form_state['values']['googleanalytics_cross_domains'] = '';
  497. }
  498. // Disallow empty list of download file extensions.
  499. if ($form_state['values']['googleanalytics_trackfiles'] && empty($form_state['values']['googleanalytics_trackfiles_extensions'])) {
  500. form_set_error('googleanalytics_trackfiles_extensions', t('List of download file extensions cannot empty.'));
  501. }
  502. // Clear obsolete local cache if cache has been disabled.
  503. if (empty($form_state['values']['googleanalytics_cache']) && $form['advanced']['googleanalytics_cache']['#default_value']) {
  504. googleanalytics_clear_js_cache();
  505. }
  506. // This is for the Newbie's who cannot read a text area description.
  507. if (stristr($form_state['values']['googleanalytics_codesnippet_before'], 'google-analytics.com/analytics.js')) {
  508. form_set_error('googleanalytics_codesnippet_before', t('Do not add the tracker code provided by Google into the javascript code snippets! This module already builds the tracker code based on your Google Analytics account number and settings.'));
  509. }
  510. if (stristr($form_state['values']['googleanalytics_codesnippet_after'], 'google-analytics.com/analytics.js')) {
  511. form_set_error('googleanalytics_codesnippet_after', t('Do not add the tracker code provided by Google into the javascript code snippets! This module already builds the tracker code based on your Google Analytics account number and settings.'));
  512. }
  513. if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['googleanalytics_codesnippet_before'])) {
  514. form_set_error('googleanalytics_codesnippet_before', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
  515. }
  516. if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['googleanalytics_codesnippet_after'])) {
  517. form_set_error('googleanalytics_codesnippet_after', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
  518. }
  519. }
  520. /**
  521. * Layout for the custom variables table in the admin settings form.
  522. *
  523. * @param array $variables
  524. * An array contains the form elements.
  525. *
  526. * @return string
  527. * The rendered output.
  528. */
  529. function theme_googleanalytics_admin_custom_var_table($variables) {
  530. $form = $variables['form'];
  531. $header = array(
  532. array('data' => t('Index')),
  533. array('data' => t('Value')),
  534. );
  535. $rows = array();
  536. foreach (element_children($form['indexes']) as $id) {
  537. $rows[] = array(
  538. 'data' => array(
  539. drupal_render($form['indexes'][$id]['index']),
  540. drupal_render($form['indexes'][$id]['value']),
  541. ),
  542. );
  543. }
  544. $output = theme('table', array('header' => $header, 'rows' => $rows));
  545. $output .= drupal_render($form['googleanalytics_description']);
  546. if (isset($form['googleanalytics_token_tree'])) {
  547. $output .= drupal_render($form['googleanalytics_token_tree']);
  548. }
  549. return $output;
  550. }
  551. /**
  552. * Validate a form element that should have tokens in it.
  553. *
  554. * For example:
  555. * @code
  556. * $form['my_node_text_element'] = array(
  557. * '#type' => 'textfield',
  558. * '#title' => t('Some text to token-ize that has a node context.'),
  559. * '#default_value' => 'The title of this node is [node:title].',
  560. * '#element_validate' => array('googleanalytics_token_element_validate'),
  561. * );
  562. * @endcode
  563. */
  564. function googleanalytics_token_element_validate(&$element, &$form_state) {
  565. $value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];
  566. if (!drupal_strlen($value)) {
  567. // Empty value needs no further validation since the element should depend
  568. // on using the '#required' FAPI property.
  569. return $element;
  570. }
  571. $tokens = token_scan($value);
  572. $invalid_tokens = _googleanalytics_get_forbidden_tokens($tokens);
  573. if ($invalid_tokens) {
  574. form_error($element, t('The %element-title is using the following forbidden tokens with personal identifying information: @invalid-tokens.', array('%element-title' => $element['#title'], '@invalid-tokens' => implode(', ', $invalid_tokens))));
  575. }
  576. return $element;
  577. }
  578. /**
  579. * @param array $value
  580. * An array of token values.
  581. *
  582. * @return array
  583. * A unique array of invalid tokens.
  584. */
  585. function _googleanalytics_get_forbidden_tokens($value) {
  586. $invalid_tokens = array();
  587. $value_tokens = is_string($value) ? token_scan($value) : $value;
  588. foreach ($value_tokens as $tokens) {
  589. if (array_filter($tokens, '_googleanalytics_contains_forbidden_token')) {
  590. $invalid_tokens = array_merge($invalid_tokens, array_values($tokens));
  591. }
  592. }
  593. array_unique($invalid_tokens);
  594. return $invalid_tokens;
  595. }
  596. /**
  597. * Validate if a string contains forbidden tokens not allowed by privacy rules.
  598. *
  599. * @param string $token_string
  600. * A string with one or more tokens to be validated.
  601. *
  602. * @return boolean
  603. * TRUE if blacklisted token has been found, otherwise FALSE.
  604. */
  605. function _googleanalytics_contains_forbidden_token($token_string) {
  606. // List of strings in tokens with personal identifying information not allowed
  607. // for privacy reasons. See section 8.1 of the Google Analytics terms of use
  608. // for more detailed information.
  609. //
  610. // This list can never ever be complete. For this reason it tries to use a
  611. // regex and may kill a few other valid tokens, but it's the only way to
  612. // protect users as much as possible from admins with illegal ideas.
  613. //
  614. // User tokens are not prefixed with colon to catch 'current-user' and 'user'.
  615. //
  616. // TODO: If someone have better ideas, share them, please!
  617. $token_blacklist = array(
  618. ':author]',
  619. ':author:edit-url]',
  620. ':author:url]',
  621. ':author:path]',
  622. ':current-user]',
  623. ':current-user:original]',
  624. ':fid]',
  625. ':mail]',
  626. ':name]',
  627. ':uid]',
  628. ':one-time-login-url]',
  629. ':owner]',
  630. ':owner:cancel-url]',
  631. ':owner:edit-url]',
  632. ':owner:url]',
  633. ':owner:path]',
  634. 'user:cancel-url]',
  635. 'user:edit-url]',
  636. 'user:url]',
  637. 'user:path]',
  638. 'user:picture]',
  639. // addressfield_tokens.module
  640. ':first-name]',
  641. ':last-name]',
  642. ':name-line]',
  643. ':mc-address]',
  644. ':thoroughfare]',
  645. ':premise]',
  646. // realname.module
  647. ':name-raw]',
  648. // token.module
  649. ':ip-address]',
  650. );
  651. return preg_match('/' . implode('|', array_map('preg_quote', $token_blacklist)) . '/i', $token_string);
  652. }
  653. /**
  654. * #element_validate callback for create only fields.
  655. *
  656. * @param $element
  657. * An associative array containing the properties and children of the
  658. * generic form element.
  659. * @param $form_state
  660. * The $form_state array for the form this element belongs to.
  661. *
  662. * @see form_process_pattern()
  663. */
  664. function googleanalytics_validate_create_field_values(&$element, &$form_state) {
  665. $values = _googleanalytics_extract_create_field_values($element['#value']);
  666. if (!is_array($values)) {
  667. form_error($element, t('The %element-title field contains invalid input.', array('%element-title' => $element['#title'])));
  668. }
  669. else {
  670. // Check that name and value are valid for the field type.
  671. foreach ($values as $name => $value) {
  672. if ($error = _googleanalytics_validate_create_field_name($name)) {
  673. form_error($element, $error);
  674. break;
  675. }
  676. if ($error = _googleanalytics_validate_create_field_value($value)) {
  677. form_error($element, $error);
  678. break;
  679. }
  680. }
  681. return $element;
  682. }
  683. }
  684. /**
  685. * Extracts the values array from the element.
  686. *
  687. * @param string $string
  688. * The raw string to extract values from.
  689. *
  690. * @return array|null
  691. * The array of extracted key/value pairs, or NULL if the string is invalid.
  692. *
  693. * @see \Drupal\options\Plugin\Field\FieldType\ListTextItem::allowedValuesString()
  694. */
  695. function _googleanalytics_extract_create_field_values($string) {
  696. $values = array();
  697. $list = explode("\n", $string);
  698. $list = array_map('trim', $list);
  699. $list = array_filter($list, 'strlen');
  700. foreach ($list as $text) {
  701. // Check for an explicit key.
  702. $matches = array();
  703. if (preg_match('/(.*)\|(.*)/', $text, $matches)) {
  704. // Trim key and value to avoid unwanted spaces issues.
  705. $name = trim($matches[1]);
  706. $value = trim($matches[2]);
  707. }
  708. else {
  709. return;
  710. }
  711. $values[$name] = $value;
  712. }
  713. return _googleanalytics_convert_form_value_data_types($values);
  714. }
  715. /**
  716. * Checks whether a field name is valid.
  717. *
  718. * @param string $name
  719. * The option value entered by the user.
  720. *
  721. * @return string
  722. * The error message if the specified value is invalid, NULL otherwise.
  723. */
  724. function _googleanalytics_validate_create_field_name($name) {
  725. // List of supported field names:
  726. // https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#create
  727. $create_only_fields = array(
  728. 'allowAnchor',
  729. 'alwaysSendReferrer',
  730. 'clientId',
  731. 'cookieName',
  732. 'cookieDomain',
  733. 'cookieExpires',
  734. 'legacyCookieDomain',
  735. 'legacyHistoryImport',
  736. 'sampleRate',
  737. 'siteSpeedSampleRate',
  738. 'storage',
  739. 'useAmpClientId',
  740. );
  741. if ($name == 'name') {
  742. return t('Create only field name %name is a disallowed field name. Changing the <em>Tracker Name</em> is currently not supported.', array('%name' => $name));
  743. }
  744. if ($name == 'allowLinker') {
  745. return t('Create only field name %name is a disallowed field name. Please select <em>Multiple top-level domains</em> under <em>What are you tracking</em> to enable cross domain tracking.', array('%name' => $name));
  746. }
  747. if ($name == 'userId') {
  748. return t('Create only field name %name is a disallowed field name. Please enable <em>Track User ID</em> under <em>Tracking scope > Users</em>.', array('%name' => $name));
  749. }
  750. if (!in_array($name, $create_only_fields)) {
  751. return t('Create only field name %name is an unknown field name. Field names are case sensitive. Please see <a href="@url">create only fields</a> documentation for supported field names.', array('%name' => $name, '@url' => 'https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#create'));
  752. }
  753. }
  754. /**
  755. * Checks whether a field value is valid.
  756. *
  757. * @param string $value
  758. * The option value entered by the user.
  759. *
  760. * @return string
  761. * The error message if the specified value is invalid, NULL otherwise.
  762. */
  763. function _googleanalytics_validate_create_field_value($value) {
  764. if (!is_bool($value) && !drupal_strlen($value)) {
  765. return t('A create only field requires a value.');
  766. }
  767. if (drupal_strlen($value) > 255) {
  768. return t('The value of a create only field must be a string at most 255 characters long.');
  769. }
  770. }
  771. /**
  772. * Generates a string representation of an array.
  773. *
  774. * This string format is suitable for edition in a textarea.
  775. *
  776. * @param array $values
  777. * An array of values, where array keys are values and array values are
  778. * labels.
  779. *
  780. * @return string
  781. * The string representation of the $values array:
  782. * - Values are separated by a carriage return.
  783. * - Each value is in the format "name|value" or "value".
  784. */
  785. function _googleanalytics_get_name_value_string($values) {
  786. $lines = array();
  787. foreach ($values as $name => $value) {
  788. // Convert data types.
  789. // @todo: #2251377: Json utility class serializes boolean values to incorrect data type
  790. if (is_bool($value)) {
  791. $value = ($value) ? 'true' : 'false';
  792. }
  793. $lines[] = "$name|$value";
  794. }
  795. return implode("\n", $lines);
  796. }
  797. /**
  798. * Prepare form data types for Json conversion.
  799. *
  800. * @param array $values
  801. * Array of name/value pairs.
  802. *
  803. * @return array
  804. * Array of name/value pairs with casted data types.
  805. */
  806. function _googleanalytics_convert_form_value_data_types($values) {
  807. foreach ($values as $name => $value) {
  808. // Convert data types.
  809. // @todo: #2251377: Json utility class serializes boolean values to incorrect data type
  810. $match = drupal_strtolower($value);
  811. if ($match == 'true') {
  812. $value = TRUE;
  813. }
  814. elseif ($match == 'false') {
  815. $value = FALSE;
  816. }
  817. // Convert other known fields.
  818. // @todo: #2251343: Json utility class serializes numeric values to incorrect data type
  819. switch ($name) {
  820. case 'sampleRate':
  821. // Float
  822. settype($value, 'float');
  823. break;
  824. case 'siteSpeedSampleRate':
  825. case 'cookieExpires':
  826. // Integer
  827. settype($value, 'integer');
  828. break;
  829. }
  830. $values[$name] = $value;
  831. }
  832. return $values;
  833. }