googleanalytics.admin.inc 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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' => url('http://support.google.com/analytics/bin/answer.py', array('query' => array('answer' => '1034342'))))),
  76. );
  77. // Page specific visibility configurations.
  78. $php_access = user_access('use PHP for tracking visibility');
  79. $visibility = variable_get('googleanalytics_visibility_pages', 0);
  80. $pages = variable_get('googleanalytics_pages', GOOGLEANALYTICS_PAGES);
  81. $form['tracking']['page_vis_settings'] = array(
  82. '#type' => 'fieldset',
  83. '#title' => t('Pages'),
  84. '#collapsible' => TRUE,
  85. '#collapsed' => TRUE,
  86. );
  87. if ($visibility == 2 && !$php_access) {
  88. $form['tracking']['page_vis_settings'] = array();
  89. $form['tracking']['page_vis_settings']['visibility'] = array('#type' => 'value', '#value' => 2);
  90. $form['tracking']['page_vis_settings']['pages'] = array('#type' => 'value', '#value' => $pages);
  91. }
  92. else {
  93. $options = array(
  94. t('Every page except the listed pages'),
  95. t('The listed pages only'),
  96. );
  97. $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>'));
  98. if (module_exists('php') && $php_access) {
  99. $options[] = t('Pages on which this PHP code returns <code>TRUE</code> (experts only)');
  100. $title = t('Pages or PHP code');
  101. $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 ?>'));
  102. }
  103. else {
  104. $title = t('Pages');
  105. }
  106. $form['tracking']['page_vis_settings']['googleanalytics_visibility_pages'] = array(
  107. '#type' => 'radios',
  108. '#title' => t('Add tracking to specific pages'),
  109. '#options' => $options,
  110. '#default_value' => $visibility,
  111. );
  112. $form['tracking']['page_vis_settings']['googleanalytics_pages'] = array(
  113. '#type' => 'textarea',
  114. '#title' => $title,
  115. '#title_display' => 'invisible',
  116. '#default_value' => $pages,
  117. '#description' => $description,
  118. '#rows' => 10,
  119. );
  120. }
  121. // Render the role overview.
  122. $form['tracking']['role_vis_settings'] = array(
  123. '#type' => 'fieldset',
  124. '#title' => t('Roles'),
  125. );
  126. $form['tracking']['role_vis_settings']['googleanalytics_visibility_roles'] = array(
  127. '#type' => 'radios',
  128. '#title' => t('Add tracking for specific roles'),
  129. '#options' => array(
  130. t('Add to the selected roles only'),
  131. t('Add to every role except the selected ones'),
  132. ),
  133. '#default_value' => variable_get('googleanalytics_visibility_roles', 0),
  134. );
  135. $role_options = array_map('check_plain', user_roles());
  136. $form['tracking']['role_vis_settings']['googleanalytics_roles'] = array(
  137. '#type' => 'checkboxes',
  138. '#title' => t('Roles'),
  139. '#default_value' => variable_get('googleanalytics_roles', array()),
  140. '#options' => $role_options,
  141. '#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).'),
  142. );
  143. // Standard tracking configurations.
  144. $form['tracking']['user_vis_settings'] = array(
  145. '#type' => 'fieldset',
  146. '#title' => t('Users'),
  147. );
  148. $t_permission = array('%permission' => t('opt-in or out of tracking'));
  149. $form['tracking']['user_vis_settings']['googleanalytics_custom'] = array(
  150. '#type' => 'radios',
  151. '#title' => t('Allow users to customize tracking on their account page'),
  152. '#options' => array(
  153. t('No customization allowed'),
  154. t('Tracking on by default, users with %permission permission can opt out', $t_permission),
  155. t('Tracking off by default, users with %permission permission can opt in', $t_permission),
  156. ),
  157. '#default_value' => variable_get('googleanalytics_custom', 0),
  158. );
  159. // Link specific configurations.
  160. $form['tracking']['linktracking'] = array(
  161. '#type' => 'fieldset',
  162. '#title' => t('Links and downloads'),
  163. );
  164. $form['tracking']['linktracking']['googleanalytics_trackoutbound'] = array(
  165. '#type' => 'checkbox',
  166. '#title' => t('Track clicks on outbound links'),
  167. '#default_value' => variable_get('googleanalytics_trackoutbound', 1),
  168. );
  169. $form['tracking']['linktracking']['googleanalytics_trackmailto'] = array(
  170. '#type' => 'checkbox',
  171. '#title' => t('Track clicks on mailto links'),
  172. '#default_value' => variable_get('googleanalytics_trackmailto', 1),
  173. );
  174. $form['tracking']['linktracking']['googleanalytics_trackfiles'] = array(
  175. '#type' => 'checkbox',
  176. '#title' => t('Track downloads (clicks on file links) for the following extensions'),
  177. '#default_value' => variable_get('googleanalytics_trackfiles', 1),
  178. );
  179. $form['tracking']['linktracking']['googleanalytics_trackfiles_extensions'] = array(
  180. '#title' => t('List of download file extensions'),
  181. '#title_display' => 'invisible',
  182. '#type' => 'textfield',
  183. '#default_value' => variable_get('googleanalytics_trackfiles_extensions', GOOGLEANALYTICS_TRACKFILES_EXTENSIONS),
  184. '#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)),
  185. '#maxlength' => 255,
  186. );
  187. // Message specific configurations.
  188. $form['tracking']['messagetracking'] = array(
  189. '#type' => 'fieldset',
  190. '#title' => t('Messages'),
  191. );
  192. $form['tracking']['messagetracking']['googleanalytics_trackmessages'] = array(
  193. '#type' => 'checkboxes',
  194. '#title' => t('Track messages of type'),
  195. '#default_value' => variable_get('googleanalytics_trackmessages', array()),
  196. '#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. Keep in mind that Google allows a maximum of 500 events per session only and every message is tracked as one individual event. If the limit has been exceeded no further events are tracked, but normal page tracking is not effected. Messages from excluded pages cannot tracked.'),
  197. '#options' => array(
  198. 'status' => t('Status message'),
  199. 'warning' => t('Warning message'),
  200. 'error' => t('Error message'),
  201. ),
  202. );
  203. // Google already have many translations, if not - they display a note to change the language.
  204. global $language;
  205. $form['tracking']['search_and_advertising'] = array(
  206. '#type' => 'fieldset',
  207. '#title' => t('Search and Advertising'),
  208. );
  209. $site_search_dependencies = '<div class="admin-dependencies">';
  210. $site_search_dependencies .= t('Depends on: !dependencies', array('!dependencies' => (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')))));
  211. $site_search_dependencies .= '</div>';
  212. $form['tracking']['search_and_advertising']['googleanalytics_site_search'] = array(
  213. '#type' => 'checkbox',
  214. '#title' => t('Track internal search'),
  215. '#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' => url('http://support.google.com/analytics/bin/answer.py', array('query' => array('answer' => '1012264'))))) . $site_search_dependencies,
  216. '#default_value' => variable_get('googleanalytics_site_search', FALSE),
  217. '#disabled' => (module_exists('search') ? FALSE : TRUE),
  218. );
  219. $form['tracking']['search_and_advertising']['googleanalytics_trackadsense'] = array(
  220. '#type' => 'checkbox',
  221. '#title' => t('Track AdSense ads'),
  222. '#description' => t('If checked, your AdSense ads will be tracked in your Google Analytics account.'),
  223. '#default_value' => variable_get('googleanalytics_trackadsense', FALSE),
  224. );
  225. $form['tracking']['search_and_advertising']['googleanalytics_trackdoubleclick'] = array(
  226. '#type' => 'checkbox',
  227. '#title' => t('Track DoubleClick data'),
  228. '#description' => t('If checked, the alternative Google <a href="@doubleclick">DoubleClick data tracking</a> is used to enable AdWords remarketing features. If you choose this option you will need to <a href="@privacy">update your privacy policy</a>.', array('@doubleclick' => url('http://support.google.com/analytics/bin/answer.py', array('query' => array('answer' => '2444872'))), '@privacy' => url('http://support.google.com/analytics/bin/answer.py', array('query' => array('answer' => '2636405'))))),
  229. '#default_value' => variable_get('googleanalytics_trackdoubleclick', FALSE),
  230. );
  231. // Privacy specific configurations.
  232. $form['tracking']['privacy'] = array(
  233. '#type' => 'fieldset',
  234. '#title' => t('Privacy'),
  235. );
  236. $form['tracking']['privacy']['googleanalytics_tracker_anonymizeip'] = array(
  237. '#type' => 'checkbox',
  238. '#title' => t('Anonymize visitors IP address'),
  239. '#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.'),
  240. '#default_value' => variable_get('googleanalytics_tracker_anonymizeip', 0),
  241. );
  242. $form['tracking']['privacy']['googleanalytics_privacy_donottrack'] = array(
  243. '#type' => 'checkbox',
  244. '#title' => t('Universal web tracking opt-out'),
  245. '#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/')),
  246. '#default_value' => variable_get('googleanalytics_privacy_donottrack', 1),
  247. );
  248. // Custom variables.
  249. $form['googleanalytics_custom_var'] = array(
  250. '#collapsed' => TRUE,
  251. '#collapsible' => TRUE,
  252. '#description' => t('You can add Google Analytics <a href="@custom_var_documentation">Custom Variables</a> here. These will be added to every page that Google Analytics tracking code appears on. Google Analytics will only accept custom variables if the <em>name</em> and <em>value</em> combined are less than 128 bytes after URL encoding. Keep the names as short as possible and expect long values to get trimmed. You may use tokens in custom variable names and values. 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/gajs/gaTrackingCustomVariables')),
  253. '#theme' => 'googleanalytics_admin_custom_var_table',
  254. '#title' => t('Custom variables'),
  255. '#tree' => TRUE,
  256. '#type' => 'fieldset',
  257. );
  258. $googleanalytics_custom_vars = variable_get('googleanalytics_custom_var', array());
  259. // Google Analytics supports up to 5 custom variables.
  260. for ($i = 1; $i < 6; $i++) {
  261. $form['googleanalytics_custom_var']['slots'][$i]['slot'] = array(
  262. '#default_value' => $i,
  263. '#description' => t('Slot number'),
  264. '#disabled' => TRUE,
  265. '#size' => 1,
  266. '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
  267. '#title_display' => 'invisible',
  268. '#type' => 'textfield',
  269. );
  270. $form['googleanalytics_custom_var']['slots'][$i]['name'] = array(
  271. '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['name']) ? $googleanalytics_custom_vars['slots'][$i]['name'] : '',
  272. '#description' => t('The custom variable name.'),
  273. '#maxlength' => 255,
  274. '#size' => 20,
  275. '#title' => t('Custom variable name #@slot', array('@slot' => $i)),
  276. '#title_display' => 'invisible',
  277. '#type' => 'textfield',
  278. '#element_validate' => array('googleanalytics_token_element_validate'),
  279. '#token_types' => array('node'),
  280. );
  281. $form['googleanalytics_custom_var']['slots'][$i]['value'] = array(
  282. '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['value']) ? $googleanalytics_custom_vars['slots'][$i]['value'] : '',
  283. '#description' => t('The custom variable value.'),
  284. '#maxlength' => 255,
  285. '#title' => t('Custom variable value #@slot', array('@slot' => $i)),
  286. '#title_display' => 'invisible',
  287. '#type' => 'textfield',
  288. '#element_validate' => array('googleanalytics_token_element_validate'),
  289. '#token_types' => array('node'),
  290. );
  291. if (module_exists('token')) {
  292. $form['googleanalytics_custom_var']['slots'][$i]['name']['#element_validate'][] = 'token_element_validate';
  293. $form['googleanalytics_custom_var']['slots'][$i]['value']['#element_validate'][] = 'token_element_validate';
  294. }
  295. $form['googleanalytics_custom_var']['slots'][$i]['scope'] = array(
  296. '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['scope']) ? $googleanalytics_custom_vars['slots'][$i]['scope'] : 3,
  297. '#description' => t('The scope for the custom variable.'),
  298. '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
  299. '#title_display' => 'invisible',
  300. '#type' => 'select',
  301. '#options' => array(
  302. 1 => t('Visitor'),
  303. 2 => t('Session'),
  304. 3 => t('Page'),
  305. ),
  306. );
  307. }
  308. $form['googleanalytics_custom_var']['googleanalytics_custom_var_description'] = array(
  309. '#type' => 'item',
  310. '#description' => t('You can supplement Google Analytics\' basic IP address tracking of visitors by segmenting users based on custom variables. 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, 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')),
  311. );
  312. $form['googleanalytics_custom_var']['googleanalytics_custom_var_token_tree'] = array(
  313. '#theme' => 'token_tree',
  314. '#token_types' => array('node'),
  315. '#dialog' => TRUE,
  316. );
  317. // Advanced feature configurations.
  318. $form['advanced'] = array(
  319. '#type' => 'fieldset',
  320. '#title' => t('Advanced settings'),
  321. '#collapsible' => TRUE,
  322. '#collapsed' => TRUE,
  323. );
  324. $form['advanced']['googleanalytics_cache'] = array(
  325. '#type' => 'checkbox',
  326. '#title' => t('Locally cache tracking code file'),
  327. '#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!"),
  328. '#default_value' => variable_get('googleanalytics_cache', 0),
  329. );
  330. // Allow for tracking of the originating node when viewing translation sets.
  331. if (module_exists('translation')) {
  332. $form['advanced']['googleanalytics_translation_set'] = array(
  333. '#type' => 'checkbox',
  334. '#title' => t('Track translation sets as one unit'),
  335. '#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.'),
  336. '#default_value' => variable_get('googleanalytics_translation_set', 0),
  337. );
  338. }
  339. $form['advanced']['codesnippet'] = array(
  340. '#type' => 'fieldset',
  341. '#title' => t('Custom JavaScript code'),
  342. '#collapsible' => TRUE,
  343. '#collapsed' => TRUE,
  344. '#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/gajs/methods/')),
  345. );
  346. $form['advanced']['codesnippet']['googleanalytics_codesnippet_before'] = array(
  347. '#type' => 'textarea',
  348. '#title' => t('Code snippet (before)'),
  349. '#default_value' => variable_get('googleanalytics_codesnippet_before', ''),
  350. '#rows' => 5,
  351. '#description' => t("Code in this textarea will be added <strong>before</strong> _gaq.push(['_trackPageview'])."),
  352. );
  353. $form['advanced']['codesnippet']['googleanalytics_codesnippet_after'] = array(
  354. '#type' => 'textarea',
  355. '#title' => t('Code snippet (after)'),
  356. '#default_value' => variable_get('googleanalytics_codesnippet_after', ''),
  357. '#rows' => 5,
  358. '#description' => t("Code in this textarea will be added <strong>after</strong> _gaq.push(['_trackPageview']). This is useful if you'd like to track a site in two accounts."),
  359. );
  360. $form['advanced']['googleanalytics_js_scope'] = array(
  361. '#type' => 'select',
  362. '#title' => t('JavaScript scope'),
  363. '#description' => t('Google recommends adding the external JavaScript files to the header for performance reasons. If <em>Multiple top-level domains</em> has been selected, this setting will be forced to header.'),
  364. '#options' => array(
  365. 'footer' => t('Footer'),
  366. 'header' => t('Header'),
  367. ),
  368. '#default_value' => variable_get('googleanalytics_js_scope', 'header'),
  369. '#disabled' => (variable_get('googleanalytics_domain_mode', 0) == 2) ? TRUE : FALSE,
  370. );
  371. return system_settings_form($form);
  372. }
  373. /**
  374. * Implements _form_validate().
  375. */
  376. function googleanalytics_admin_settings_form_validate($form, &$form_state) {
  377. // Custom variables validation.
  378. foreach ($form_state['values']['googleanalytics_custom_var']['slots'] as $custom_var) {
  379. $form_state['values']['googleanalytics_custom_var']['slots'][$custom_var['slot']]['name'] = trim($custom_var['name']);
  380. $form_state['values']['googleanalytics_custom_var']['slots'][$custom_var['slot']]['value'] = trim($custom_var['value']);
  381. // Validate empty names/values.
  382. if (empty($custom_var['name']) && !empty($custom_var['value'])) {
  383. form_set_error("googleanalytics_custom_var][slots][" . $custom_var['slot'] . "][name", t('The custom variable @slot-number requires a <em>Name</em> if a <em>Value</em> has been provided.', array('@slot-number' => $custom_var['slot'])));
  384. }
  385. elseif (!empty($custom_var['name']) && empty($custom_var['value'])) {
  386. form_set_error("googleanalytics_custom_var][slots][" . $custom_var['slot'] . "][value", t('The custom variable @slot-number requires a <em>Value</em> if a <em>Name</em> has been provided.', array('@slot-number' => $custom_var['slot'])));
  387. }
  388. }
  389. // Trim some text values.
  390. $form_state['values']['googleanalytics_account'] = trim($form_state['values']['googleanalytics_account']);
  391. $form_state['values']['googleanalytics_pages'] = trim($form_state['values']['googleanalytics_pages']);
  392. $form_state['values']['googleanalytics_cross_domains'] = trim($form_state['values']['googleanalytics_cross_domains']);
  393. $form_state['values']['googleanalytics_codesnippet_before'] = trim($form_state['values']['googleanalytics_codesnippet_before']);
  394. $form_state['values']['googleanalytics_codesnippet_after'] = trim($form_state['values']['googleanalytics_codesnippet_after']);
  395. // Replace all type of dashes (n-dash, m-dash, minus) with the normal dashes.
  396. $form_state['values']['googleanalytics_account'] = str_replace(array('–', '—', '−'), '-', $form_state['values']['googleanalytics_account']);
  397. if (!preg_match('/^UA-\d{4,}-\d+$/', $form_state['values']['googleanalytics_account'])) {
  398. form_set_error('googleanalytics_account', t('A valid Google Analytics Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy.'));
  399. }
  400. // If multiple top-level domains has been selected, a domain names list is required.
  401. if ($form_state['values']['googleanalytics_domain_mode'] == 2 && empty($form_state['values']['googleanalytics_cross_domains'])) {
  402. 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.'));
  403. }
  404. // Clear obsolete local cache if cache has been disabled.
  405. if (empty($form_state['values']['googleanalytics_cache']) && $form['advanced']['googleanalytics_cache']['#default_value']) {
  406. googleanalytics_clear_js_cache();
  407. }
  408. // This is for the Newbie's who cannot read a text area description.
  409. if (stristr($form_state['values']['googleanalytics_codesnippet_before'], 'google-analytics.com/ga.js')) {
  410. 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.'));
  411. }
  412. if (stristr($form_state['values']['googleanalytics_codesnippet_after'], 'google-analytics.com/ga.js')) {
  413. 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.'));
  414. }
  415. if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['googleanalytics_codesnippet_before'])) {
  416. form_set_error('googleanalytics_codesnippet_before', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
  417. }
  418. if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['googleanalytics_codesnippet_after'])) {
  419. form_set_error('googleanalytics_codesnippet_after', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
  420. }
  421. // Header section must be forced for multiple top-level domains.
  422. if ($form_state['values']['googleanalytics_domain_mode'] == 2) {
  423. $form_state['values']['googleanalytics_js_scope'] = 'header';
  424. }
  425. }
  426. /**
  427. * Layout for the custom variables table in the admin settings form.
  428. */
  429. function theme_googleanalytics_admin_custom_var_table($variables) {
  430. $form = $variables['form'];
  431. $header = array(
  432. array('data' => t('Slot')),
  433. array('data' => t('Name')),
  434. array('data' => t('Value')),
  435. array('data' => t('Scope')),
  436. );
  437. $rows = array();
  438. foreach (element_children($form['slots']) as $key => $id) {
  439. $rows[] = array(
  440. 'data' => array(
  441. drupal_render($form['slots'][$id]['slot']),
  442. drupal_render($form['slots'][$id]['name']),
  443. drupal_render($form['slots'][$id]['value']),
  444. drupal_render($form['slots'][$id]['scope']),
  445. ),
  446. );
  447. }
  448. $output = theme('table', array('header' => $header, 'rows' => $rows));
  449. $output .= drupal_render($form['googleanalytics_custom_var_description']);
  450. $output .= drupal_render($form['googleanalytics_custom_var_token_tree']);
  451. return $output;
  452. }
  453. /**
  454. * Validate a form element that should have tokens in it.
  455. *
  456. * For example:
  457. * @code
  458. * $form['my_node_text_element'] = array(
  459. * '#type' => 'textfield',
  460. * '#title' => t('Some text to token-ize that has a node context.'),
  461. * '#default_value' => 'The title of this node is [node:title].',
  462. * '#element_validate' => array('googleanalytics_token_element_validate'),
  463. * );
  464. * @endcode
  465. */
  466. function googleanalytics_token_element_validate(&$element, &$form_state) {
  467. $value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];
  468. if (!drupal_strlen($value)) {
  469. // Empty value needs no further validation since the element should depend
  470. // on using the '#required' FAPI property.
  471. return $element;
  472. }
  473. $tokens = token_scan($value);
  474. $invalid_tokens = _googleanalytics_get_forbidden_tokens($tokens);
  475. if ($invalid_tokens) {
  476. 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))));
  477. }
  478. return $element;
  479. }
  480. function _googleanalytics_get_forbidden_tokens($value) {
  481. $invalid_tokens = array();
  482. $value_tokens = is_string($value) ? token_scan($value) : $value;
  483. foreach ($value_tokens as $type => $tokens) {
  484. if (array_filter($tokens, '_googleanalytics_contains_forbidden_token')) {
  485. $invalid_tokens = array_merge($invalid_tokens, array_values($tokens));
  486. }
  487. }
  488. array_unique($invalid_tokens);
  489. return $invalid_tokens;
  490. }
  491. /**
  492. * Validate if a string contains forbidden tokens not allowed by privacy rules.
  493. *
  494. * @param $token_string
  495. * A string with one or more tokens to be validated.
  496. * @return boolean
  497. * TRUE if blacklisted token has been found, otherwise FALSE.
  498. */
  499. function _googleanalytics_contains_forbidden_token($token_string) {
  500. // List of strings in tokens with personal identifying information not allowed
  501. // for privacy reasons. See section 8.1 of the Google Analytics terms of use
  502. // for more detailed information.
  503. //
  504. // This list can never ever be complete. For this reason it tries to use a
  505. // regex and may kill a few other valid tokens, but it's the only way to
  506. // protect users as much as possible from admins with illegal ideas.
  507. //
  508. // User tokens are not prefixed with colon to catch 'current-user' and 'user'.
  509. //
  510. // TODO: If someone have better ideas, share them, please!
  511. $token_blacklist = array(
  512. ':author]',
  513. ':author:edit-url]',
  514. ':author:url]',
  515. ':author:path]',
  516. ':current-user]',
  517. ':current-user:original]',
  518. ':fid]',
  519. ':mail]',
  520. ':name]',
  521. ':uid]',
  522. ':one-time-login-url]',
  523. ':owner]',
  524. ':owner:cancel-url]',
  525. ':owner:edit-url]',
  526. ':owner:url]',
  527. ':owner:path]',
  528. 'user:cancel-url]',
  529. 'user:edit-url]',
  530. 'user:url]',
  531. 'user:path]',
  532. 'user:picture]',
  533. // addressfield_tokens.module
  534. ':first-name]',
  535. ':last-name]',
  536. ':name-line]',
  537. ':mc-address]',
  538. ':thoroughfare]',
  539. ':premise]',
  540. // realname.module
  541. ':name-raw]',
  542. // token.module
  543. ':ip-address]',
  544. );
  545. return preg_match('/' . implode('|', array_map('preg_quote', $token_blacklist)) . '/i', $token_string);
  546. }