Add more blacklisted tokens
[project/google_analytics.git] / googleanalytics.admin.inc
1 <?php
2 // $Id$
3
4 /**
5 * @file
6 * Administrative page callbacks for the googleanalytics module.
7 */
8
9 /**
10 * Implements hook_admin_settings() for module settings configuration.
11 */
12 function googleanalytics_admin_settings_form($form_state) {
13 $form['account'] = array(
14 '#type' => 'fieldset',
15 '#title' => t('General settings'),
16 );
17
18 $form['account']['googleanalytics_account'] = array(
19 '#title' => t('Web Property ID'),
20 '#type' => 'textfield',
21 '#default_value' => variable_get('googleanalytics_account', 'UA-'),
22 '#size' => 15,
23 '#maxlength' => 20,
24 '#required' => TRUE,
25 '#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' => 'http://code.google.com/apis/analytics/docs/concepts/gaConceptsAccounts.html#webProperty')),
26 );
27
28 // Visibility settings.
29 $form['tracking_title'] = array(
30 '#type' => 'item',
31 '#title' => t('Tracking scope'),
32 );
33 $form['tracking'] = array(
34 '#type' => 'vertical_tabs',
35 '#attached' => array(
36 'js' => array(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.admin.js'),
37 ),
38 );
39
40 // Standard tracking configurations.
41 $form['tracking']['user_vis_settings'] = array(
42 '#type' => 'fieldset',
43 '#title' => t('Users'),
44 );
45 $t_permission = array('%permission' => t('opt-in or out of tracking'));
46 $form['tracking']['user_vis_settings']['googleanalytics_custom'] = array(
47 '#type' => 'radios',
48 '#title' => t('Allow users to customize tracking on their account page'),
49 '#options' => array(
50 t('No customization allowed'),
51 t('Tracking on by default, users with %permission permission can opt out', $t_permission),
52 t('Tracking off by default, users with %permission permission can opt in', $t_permission)
53 ),
54 '#default_value' => variable_get('googleanalytics_custom', 0),
55 );
56
57 // Render the role overview.
58 $form['tracking']['role_vis_settings'] = array(
59 '#type' => 'fieldset',
60 '#title' => t('Roles'),
61 );
62
63 $role_options = array_map('check_plain', user_roles());
64 $form['tracking']['role_vis_settings']['googleanalytics_roles'] = array(
65 '#type' => 'checkboxes',
66 '#title' => t('Add tracking for specific roles'),
67 '#default_value' => variable_get('googleanalytics_roles', array()),
68 '#options' => $role_options,
69 '#description' => t('If none are selected, all users will be tracked. If a user has any of the roles checked, that user will be tracked.'),
70 );
71
72 // Page specific visibility configurations.
73 $php_access = user_access('use PHP for tracking visibility');
74 $visibility = variable_get('googleanalytics_visibility', 0);
75 $pages = variable_get('googleanalytics_pages', '');
76
77 $form['tracking']['page_vis_settings'] = array(
78 '#type' => 'fieldset',
79 '#title' => t('Pages'),
80 '#collapsible' => TRUE,
81 '#collapsed' => TRUE,
82 );
83
84 if ($visibility == 2 && !$php_access) {
85 $form['tracking']['page_vis_settings'] = array();
86 $form['tracking']['page_vis_settings']['visibility'] = array('#type' => 'value', '#value' => 2);
87 $form['tracking']['page_vis_settings']['pages'] = array('#type' => 'value', '#value' => $pages);
88 }
89 else {
90 $options = array(
91 t('Every page except the listed pages'),
92 t('The listed pages only')
93 );
94 $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>'));
95
96 if (module_exists('php') && $php_access) {
97 $options[] = t('Pages on which this PHP code returns <code>TRUE</code> (experts only)');
98 $title = t('Pages or PHP code');
99 $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 ?>'));
100 }
101 else {
102 $title = t('Pages');
103 }
104 $form['tracking']['page_vis_settings']['googleanalytics_visibility'] = array(
105 '#type' => 'radios',
106 '#title' => t('Add tracking to specific pages'),
107 '#options' => $options,
108 '#default_value' => $visibility,
109 );
110 $form['tracking']['page_vis_settings']['googleanalytics_pages'] = array(
111 '#type' => 'textarea',
112 '#title' => '<span class="element-invisible">' . $title . '</span>',
113 '#default_value' => $pages,
114 '#description' => $description,
115 );
116 }
117
118 // Link specific configurations.
119 $form['tracking']['linktracking'] = array(
120 '#type' => 'fieldset',
121 '#title' => t('Links and downloads'),
122 );
123 $form['tracking']['linktracking']['googleanalytics_trackoutgoing'] = array(
124 '#type' => 'checkbox',
125 '#title' => t('Track clicks on outgoing links'),
126 '#default_value' => variable_get('googleanalytics_trackoutgoing', 1),
127 );
128 $form['tracking']['linktracking']['googleanalytics_trackmailto'] = array(
129 '#type' => 'checkbox',
130 '#title' => t('Track clicks on mailto links'),
131 '#default_value' => variable_get('googleanalytics_trackmailto', 1),
132 );
133 $form['tracking']['linktracking']['googleanalytics_trackfiles'] = array(
134 '#type' => 'checkbox',
135 '#title' => t('Track downloads (clicks on file links) for the following extensions'),
136 '#default_value' => variable_get('googleanalytics_trackfiles', 1),
137 );
138 $form['tracking']['linktracking']['googleanalytics_trackfiles_extensions'] = array(
139 '#type' => 'textfield',
140 '#default_value' => variable_get('googleanalytics_trackfiles_extensions', GA_TRACKFILES_EXTENSIONS),
141 '#description' => t('A file extension list separated by the | character that will be tracked when clicked. Regular expressions are supported. For example: !extensions', array('!extensions' => GA_TRACKFILES_EXTENSIONS)),
142 '#maxlength' => 255,
143 );
144
145 // Google already have many translations, if not - they display a note to change the language.
146 global $language;
147 $form['tracking']['search_and_adsense'] = array(
148 '#type' => 'fieldset',
149 '#title' => t('Search and AdSense'),
150 );
151
152 $site_search_dependencies = '<div class="admin-dependencies">';
153 $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')))));
154 $site_search_dependencies .= '</div>';
155
156 $form['tracking']['search_and_adsense']['googleanalytics_site_search'] = array(
157 '#type' => 'checkbox',
158 '#title' => t('Track internal search'),
159 '#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">How do I set up Site Search for my profile</a>.', array('@url' => 'http://www.google.com/support/analytics/bin/answer.py?hl=' . $language->language . '&answer=75817')) . $site_search_dependencies,
160 '#default_value' => variable_get('googleanalytics_site_search', FALSE),
161 '#disabled' => (module_exists('search') ? FALSE : TRUE),
162 );
163
164 $form['tracking']['search_and_adsense']['googleanalytics_trackadsense'] = array(
165 '#type' => 'checkbox',
166 '#title' => t('Track AdSense ads'),
167 '#default_value' => variable_get('googleanalytics_trackadsense', FALSE),
168 );
169
170 // Backward compatibility only.
171 // TODO: If currently not in use, hide the UI and later remove the code.
172 $segmentation = variable_get('googleanalytics_segmentation', array());
173
174 if (!empty($segmentation) || variable_get('googleanalytics_segmentation_DEPRECATED', FALSE)) {
175 $profile_enabled = module_exists('profile');
176 $form['segmentation'] = array(
177 '#type' => 'fieldset',
178 '#title' => t('Additional user information'),
179 '#collapsible' => TRUE,
180 );
181
182 // Compile a list of fields to show.
183 $fields = variable_get('googleanalytics_segmentation_default_fields', array('roles' => t('User roles')));
184 if ($profile_enabled) {
185 $result = db_query('SELECT name, title FROM {profile_field} ORDER BY weight');
186 foreach ($result as $record) {
187 $fields[$record->name] = $record->title;
188 }
189 }
190
191 $form['segmentation']['googleanalytics_segmentation'] = array(
192 '#type' => 'select',
193 '#title' => t('Segment users based on these selected properties') . ' <span class="admin-disabled">***DEPRECATED***</span>',
194 '#description' => t("You can supplement Google Analytics' basic IP address tracking of visitors by segmenting users based on these selected properties.") . ' <span class="admin-disabled">' . t('For most situations, Google recommend that you use Custom Variables to segment your visitors.') . '</span>' . (!$profile_enabled ? ' ' . t('<a href="@module_list">Enable the profile module</a> to be able to use profile fields for more granular tracking.', array('@module_list' => url('admin/build/modules'))) : '') . ' ' . t('Section 8.1 of the <a href="@ga_tos">Google Analytics terms of use</a> requires you to make sure you will not associate (or permit any third party to associate) any data gathered from your websites (or such third parties\' websites) with any personally identifying information from any source as part of your use (or such third parties\' use) of the Google Analytics\' service.', array('@ga_tos' => 'http://www.google.com/analytics/en-GB/tos.html')) . ' ' . t('You can select multiple values.'),
195 '#default_value' => $segmentation,
196 '#options' => $fields,
197 '#size' => count($fields)>3 ? 10 : 3,
198 '#multiple' => TRUE
199 );
200 }
201
202 $form['googleanalytics_custom_var'] = array(
203 '#collapsible' => TRUE,
204 '#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 64 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 values. Global and user tokens are always available; on node pages, node tokens are also available.', array('!custom_var_documentation' => 'http://code.google.com/intl/en/apis/analytics/docs/tracking/gaTrackingCustomVariables.html')),
205 '#theme' => 'googleanalytics_admin_custom_var_table',
206 '#title' => t('Custom variables'),
207 '#tree' => TRUE,
208 '#type' => 'fieldset',
209 );
210
211 $googleanalytics_custom_vars = variable_get('googleanalytics_custom_var', array());
212
213 // Google Analytics supports up to 5 custom variables.
214 for ($i = 1; $i < 6; $i++) {
215 $form['googleanalytics_custom_var']['slots'][$i]['slot'] = array(
216 '#default_value' => $i,
217 '#description' => t('Slot number'),
218 '#disabled' => TRUE,
219 '#size' => 1,
220 '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
221 '#title_display' => 'invisible',
222 '#type' => 'textfield',
223 );
224 $form['googleanalytics_custom_var']['slots'][$i]['name'] = array(
225 '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['name']) ? $googleanalytics_custom_vars['slots'][$i]['name'] : '',
226 '#description' => t('The custom variable name.'),
227 '#size' => 20,
228 '#title' => t('Custom variable name #@slot', array('@slot' => $i)),
229 '#title_display' => 'invisible',
230 '#type' => 'textfield',
231 );
232 $form['googleanalytics_custom_var']['slots'][$i]['value'] = array(
233 '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['value']) ? $googleanalytics_custom_vars['slots'][$i]['value'] : '',
234 '#description' => t('The custom variable value. You may use tokens in this field.'),
235 '#title' => t('Custom variable value #@slot', array('@slot' => $i)),
236 '#title_display' => 'invisible',
237 '#type' => 'textfield',
238 '#element_validate' => array('token_element_validate'),
239 '#token_types' => array('all'),
240 );
241 $form['googleanalytics_custom_var']['slots'][$i]['scope'] = array(
242 '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['scope']) ? $googleanalytics_custom_vars['slots'][$i]['scope'] : 3,
243 '#description' => t('The scope for the custom variable.'),
244 '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
245 '#title_display' => 'invisible',
246 '#type' => 'select',
247 '#options' => array(
248 1 => t('Visitor'),
249 2 => t('Session'),
250 3 => t('Page'),
251 ),
252 );
253 }
254
255 $form['googleanalytics_custom_var']['googleanalytics_custom_var_description'] = array(
256 '#type' => 'item',
257 '#description' => t('You can supplement Google Analytics\' basic IP address tracking of visitors by segmenting users based on custom variables. Section 8.1 of the <a href="@ga_tos">Google Analytics terms of use</a> requires you to make sure you will not associate (or permit any third party to associate) any data gathered from your websites (or such third parties\' websites) with any personally identifying information from any source as part of your use (or such third parties\' use) of the Google Analytics\' service.', array('@ga_tos' => 'http://www.google.com/analytics/en-GB/tos.html')),
258 );
259 $form['googleanalytics_custom_var']['googleanalytics_custom_var_token_tree'] = array(
260 '#theme' => 'token_tree',
261 '#token_types' => array('node'),
262 );
263
264
265 // Advanced feature configurations.
266 $form['advanced'] = array(
267 '#type' => 'fieldset',
268 '#title' => t('Advanced settings'),
269 '#collapsible' => TRUE,
270 '#collapsed' => TRUE,
271 );
272
273 $form['advanced']['googleanalytics_tracker_anonymizeip'] = array(
274 '#type' => 'checkbox',
275 '#title' => t('Anonymize visitors IP address'),
276 '#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.'),
277 '#default_value' => variable_get('googleanalytics_tracker_anonymizeip', 0),
278 );
279
280 $form['advanced']['googleanalytics_cache'] = array(
281 '#type' => 'checkbox',
282 '#title' => t('Locally cache tracking code file'),
283 '#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!"),
284 '#default_value' => variable_get('googleanalytics_cache', 0),
285 );
286
287 // Allow for tracking of the originating node when viewing translation sets.
288 if (module_exists('translation')) {
289 $form['advanced']['googleanalytics_translation_set'] = array(
290 '#type' => 'checkbox',
291 '#title' => t('Track translation sets as one unit'),
292 '#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.'),
293 '#default_value' => variable_get('googleanalytics_translation_set', 0),
294 );
295 }
296
297 $form['advanced']['codesnippet'] = array(
298 '#type' => 'fieldset',
299 '#title' => t('Custom JavaScript code'),
300 '#collapsible' => TRUE,
301 '#collapsed' => TRUE,
302 '#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' => 'http://code.google.com/apis/analytics/docs/gaConceptsOverview.html', '@ga_js_api' => 'http://code.google.com/apis/analytics/docs/gaJSApi.html'))
303 );
304 $form['advanced']['codesnippet']['googleanalytics_codesnippet_before'] = array(
305 '#type' => 'textarea',
306 '#title' => t('Code snippet (before)'),
307 '#default_value' => variable_get('googleanalytics_codesnippet_before', ''),
308 '#rows' => 5,
309 '#description' => t("Code in this textarea will be added <strong>before</strong> _gaq.push(['_trackPageview'])."),
310 );
311 $form['advanced']['codesnippet']['googleanalytics_codesnippet_after'] = array(
312 '#type' => 'textarea',
313 '#title' => t('Code snippet (after)'),
314 '#default_value' => variable_get('googleanalytics_codesnippet_after', ''),
315 '#rows' => 5,
316 '#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."),
317 );
318
319 $form['advanced']['googleanalytics_js_scope'] = array(
320 '#type' => 'select',
321 '#title' => t('JavaScript scope'),
322 '#description' => t('Google recommends adding the external JavaScript files to the header for performance reasons.'),
323 '#options' => array(
324 'footer' => t('Footer'),
325 'header' => t('Header'),
326 ),
327 '#default_value' => variable_get('googleanalytics_js_scope', 'header'),
328 );
329
330 return system_settings_form($form);
331 }
332
333 /**
334 * Implements _form_validate().
335 */
336 function googleanalytics_admin_settings_form_validate($form, &$form_state) {
337 // Custom variables validation.
338 foreach ($form_state['values']['googleanalytics_custom_var']['slots'] as $custom_var) {
339 // Validate empty names/values.
340 if (empty($custom_var['name']) && !empty($custom_var['value'])) {
341 form_set_error("googleanalytics_custom_var][slots][" . $custom_var['slot'] . "][name", t('Custom variable #@slot: <em>Name</em> is required, if <em>value</em> has been provided.', array('@slot' => $custom_var['slot'])));
342 }
343 elseif (!empty($custom_var['name']) && empty($custom_var['value'])) {
344 form_set_error("googleanalytics_custom_var][slots][" . $custom_var['slot'] . "][value", t('Custom variable #@slot: <em>Value</em> is required, if <em>name</em> has been provided.', array('@slot' => $custom_var['slot'])));
345 }
346
347 // Block tokens with personally identifying information.
348 if (_googleanalytics_contains_forbidden_token($custom_var['value'])) {
349 form_set_error("googleanalytics_custom_var][slots][" . $custom_var['slot'] . "][value", t('Custom variable #@slot: Forbidden token has been found in custom variable named %name. Never use tokens with personally identifying information!', array('%name' => $custom_var['name'], '@slot' => $custom_var['slot'])));
350 }
351 }
352
353 // Trim some text values.
354 $form_state['values']['googleanalytics_account'] = trim($form_state['values']['googleanalytics_account']);
355 $form_state['values']['googleanalytics_pages'] = trim($form_state['values']['googleanalytics_pages']);
356 $form_state['values']['googleanalytics_codesnippet_before'] = trim($form_state['values']['googleanalytics_codesnippet_before']);
357 $form_state['values']['googleanalytics_codesnippet_after'] = trim($form_state['values']['googleanalytics_codesnippet_after']);
358
359 if (!preg_match('/^UA-\d{4,}-\d+$/', $form_state['values']['googleanalytics_account'])) {
360 form_set_error('googleanalytics_account', t('A valid Google Analytics Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy.'));
361 }
362
363 // Clear obsolete local cache if cache has been disabled.
364 if (empty($form_state['values']['googleanalytics_cache']) && $form['advanced']['googleanalytics_cache']['#default_value']) {
365 googleanalytics_clear_js_cache();
366 }
367
368 // This is for the Newbie's who cannot read a text area description.
369 if (stristr($form_state['values']['googleanalytics_codesnippet_before'], 'google-analytics.com/ga.js')) {
370 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.'));
371 }
372 if (stristr($form_state['values']['googleanalytics_codesnippet_after'], 'google-analytics.com/ga.js')) {
373 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.'));
374 }
375 if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['googleanalytics_codesnippet_before'])) {
376 form_set_error('googleanalytics_codesnippet_before', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
377 }
378 if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['googleanalytics_codesnippet_after'])) {
379 form_set_error('googleanalytics_codesnippet_after', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
380 }
381 }
382
383 /**
384 * Layout for the custom variables table in the admin settings form.
385 */
386 function theme_googleanalytics_admin_custom_var_table($variables) {
387 $form = $variables['form'];
388
389 $header = array(
390 array('data' => t('Slot')),
391 array('data' => t('Name')),
392 array('data' => t('Value')),
393 array('data' => t('Scope')),
394 );
395
396 $rows = array();
397 foreach (element_children($form['slots']) as $key => $id) {
398 $rows[] = array(
399 'data' => array(
400 drupal_render($form['slots'][$id]['slot']),
401 drupal_render($form['slots'][$id]['name']),
402 drupal_render($form['slots'][$id]['value']),
403 drupal_render($form['slots'][$id]['scope']),
404 ),
405 );
406 }
407
408 $output = theme('table', array('header' => $header, 'rows' => $rows));
409 $output .= drupal_render($form['googleanalytics_custom_var_description']);
410 $output .= drupal_render($form['googleanalytics_custom_var_token_tree']);
411
412 return $output;
413 }
414
415 /**
416 * Validate if a string contains forbidden tokens not allowed by privacy rules.
417 *
418 * @param $token_string
419 * A string with one or more tokens to be validated.
420 * @return boolean
421 * TRUE if blacklisted token has been found, otherwise FALSE.
422 */
423 function _googleanalytics_contains_forbidden_token($token_string) {
424 // List of strings in tokens with personal identifying information not allowed
425 // for privacy reasons. See section 8.1 of the Google Analytics terms of use
426 // for more detailed information.
427 //
428 // This list can never ever be complete. For this reason it tries to use a
429 // regex and may kill a few other valid tokens, but it's the only way to
430 // protect users as much as possible from admins with illegal ideas.
431 //
432 // User tokens are not prefixed with colon to catch 'current-user' and 'user'.
433 //
434 // TODO: If someone have better ideas, share them, please!
435 $token_blacklist = array(
436 ':author]',
437 ':author:edit-url]',
438 ':author:url]',
439 ':author:path]',
440 ':fid]',
441 ':mail]',
442 ':name]',
443 ':uid]',
444 ':one-time-login-url]',
445 ':owner]',
446 ':owner:cancel-url]',
447 ':owner:edit-url]',
448 ':owner:url]',
449 ':owner:path]',
450 'user:cancel-url]',
451 'user:edit-url]',
452 'user:url]',
453 'user:path]',
454 );
455
456 return preg_match('/' . implode('|', array_map('preg_quote', $token_blacklist)) . '/i', $token_string);
457 }