googleanalytics.admin.inc 44 KB

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