#609892 by Dave Reid: Correct token broken code
[project/google_analytics.git] / googleanalytics.admin.inc
CommitLineData
5bcdd55b 1<?php
2// $Id$
60b6111f 3
5bcdd55b 4/**
5 * @file
6 * Administrative page callbacks for the googleanalytics module.
7 */
8
9/**
7c745c6a 10 * Implements hook_admin_settings() for module settings configuration.
5bcdd55b 11 */
84201561 12function googleanalytics_admin_settings_form($form_state) {
5bcdd55b 13 $form['account'] = array(
14 '#type' => 'fieldset',
60b6111f 15 '#title' => t('General settings'),
5bcdd55b 16 );
17
18 $form['account']['googleanalytics_account'] = array(
a8664f42 19 '#title' => t('Web Property ID'),
5bcdd55b 20 '#type' => 'textfield',
5bcdd55b 21 '#default_value' => variable_get('googleanalytics_account', 'UA-'),
22 '#size' => 15,
23 '#maxlength' => 20,
24 '#required' => TRUE,
a8664f42 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 ),
5bcdd55b 38 );
39
60b6111f 40 // Standard tracking configurations.
a8664f42 41 $form['tracking']['user_vis_settings'] = array(
60b6111f 42 '#type' => 'fieldset',
a8664f42 43 '#title' => t('Users'),
60b6111f 44 );
a8664f42 45 $t_permission = array('%permission' => t('opt-in or out of tracking'));
46 $form['tracking']['user_vis_settings']['googleanalytics_custom'] = array(
60b6111f 47 '#type' => 'radios',
a8664f42 48 '#title' => t('Allow users to customize tracking on their account page'),
60b6111f 49 '#options' => array(
a8664f42 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)
60b6111f 53 ),
60b6111f 54 '#default_value' => variable_get('googleanalytics_custom', 0),
55 );
5bcdd55b 56
60b6111f 57 // Render the role overview.
a8664f42 58 $form['tracking']['role_vis_settings'] = array(
5bcdd55b 59 '#type' => 'fieldset',
a8664f42 60 '#title' => t('Roles'),
5bcdd55b 61 );
62
a8664f42 63 $role_options = array_map('check_plain', user_roles());
64 $form['tracking']['role_vis_settings']['googleanalytics_roles'] = array(
60b6111f 65 '#type' => 'checkboxes',
66 '#title' => t('Add tracking for specific roles'),
67 '#default_value' => variable_get('googleanalytics_roles', array()),
68 '#options' => $role_options,
a8664f42 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.'),
60b6111f 70 );
5bcdd55b 71
60b6111f 72 // Page specific visibility configurations.
a8664f42 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(
5bcdd55b 78 '#type' => 'fieldset',
a8664f42 79 '#title' => t('Pages'),
5bcdd55b 80 '#collapsible' => TRUE,
60b6111f 81 '#collapsed' => TRUE,
5bcdd55b 82 );
83
a8664f42 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);
5bcdd55b 88 }
89 else {
a8664f42 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>'));
60b6111f 95
a8664f42 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');
60b6111f 103 }
a8664f42 104 $form['tracking']['page_vis_settings']['googleanalytics_visibility'] = array(
60b6111f 105 '#type' => 'radios',
106 '#title' => t('Add tracking to specific pages'),
107 '#options' => $options,
108 '#default_value' => $visibility,
5bcdd55b 109 );
a8664f42 110 $form['tracking']['page_vis_settings']['googleanalytics_pages'] = array(
60b6111f 111 '#type' => 'textarea',
a8664f42 112 '#title' => '<span class="element-invisible">' . $title . '</span>',
60b6111f 113 '#default_value' => $pages,
114 '#description' => $description,
115 );
116 }
117
a8664f42 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'),
7c745c6a 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,
a8664f42 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'),
6f7bc4b9 167 '#description' => t('If checked, your AdSense ads will be tracked in your Google Analytics account.'),
a8664f42 168 '#default_value' => variable_get('googleanalytics_trackadsense', FALSE),
169 );
170
26110623 171 // Backward compatibility only.
172 // TODO: If currently not in use, hide the UI and later remove the code.
173 $segmentation = variable_get('googleanalytics_segmentation', array());
174
ba1cd2fd 175 if (!empty($segmentation) || variable_get('googleanalytics_segmentation_DEPRECATED', FALSE)) {
26110623 176 $profile_enabled = module_exists('profile');
177 $form['segmentation'] = array(
178 '#type' => 'fieldset',
179 '#title' => t('Additional user information'),
180 '#collapsible' => TRUE,
181 );
182
183 // Compile a list of fields to show.
184 $fields = variable_get('googleanalytics_segmentation_default_fields', array('roles' => t('User roles')));
185 if ($profile_enabled) {
186 $result = db_query('SELECT name, title FROM {profile_field} ORDER BY weight');
187 foreach ($result as $record) {
188 $fields[$record->name] = $record->title;
189 }
190 }
191
192 $form['segmentation']['googleanalytics_segmentation'] = array(
193 '#type' => 'select',
194 '#title' => t('Segment users based on these selected properties') . ' <span class="admin-disabled">***DEPRECATED***</span>',
501e13d4 195 '#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.'),
8ac83edd 196 '#default_value' => $segmentation,
26110623 197 '#options' => $fields,
198 '#size' => count($fields)>3 ? 10 : 3,
199 '#multiple' => TRUE
200 );
201 }
202
26110623 203 $form['googleanalytics_custom_var'] = array(
60b6111f 204 '#collapsible' => TRUE,
26110623 205 '#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')),
206 '#theme' => 'googleanalytics_admin_custom_var_table',
207 '#title' => t('Custom variables'),
208 '#tree' => TRUE,
209 '#type' => 'fieldset',
60b6111f 210 );
211
26110623 212 $googleanalytics_custom_vars = variable_get('googleanalytics_custom_var', array());
213
214 // Google Analytics supports up to 5 custom variables.
215 for ($i = 1; $i < 6; $i++) {
216 $form['googleanalytics_custom_var']['slots'][$i]['slot'] = array(
217 '#default_value' => $i,
218 '#description' => t('Slot number'),
219 '#disabled' => TRUE,
220 '#size' => 1,
1c4f71d8 221 '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
222 '#title_display' => 'invisible',
26110623 223 '#type' => 'textfield',
224 );
225 $form['googleanalytics_custom_var']['slots'][$i]['name'] = array(
226 '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['name']) ? $googleanalytics_custom_vars['slots'][$i]['name'] : '',
227 '#description' => t('The custom variable name.'),
228 '#size' => 20,
1c4f71d8 229 '#title' => t('Custom variable name #@slot', array('@slot' => $i)),
230 '#title_display' => 'invisible',
26110623 231 '#type' => 'textfield',
232 );
233 $form['googleanalytics_custom_var']['slots'][$i]['value'] = array(
234 '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['value']) ? $googleanalytics_custom_vars['slots'][$i]['value'] : '',
baec3364 235 '#description' => t('The custom variable value. You may use tokens in this field.'),
1c4f71d8 236 '#title' => t('Custom variable value #@slot', array('@slot' => $i)),
237 '#title_display' => 'invisible',
26110623 238 '#type' => 'textfield',
91359d57 239 '#element_validate' => array('googleanalytics_token_element_validate'),
2d846b38 240 '#token_types' => array('node'),
26110623 241 );
242 $form['googleanalytics_custom_var']['slots'][$i]['scope'] = array(
243 '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['scope']) ? $googleanalytics_custom_vars['slots'][$i]['scope'] : 3,
244 '#description' => t('The scope for the custom variable.'),
1c4f71d8 245 '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
246 '#title_display' => 'invisible',
26110623 247 '#type' => 'select',
248 '#options' => array(
249 1 => t('Visitor'),
250 2 => t('Session'),
251 3 => t('Page'),
252 ),
253 );
5bcdd55b 254 }
255
26110623 256 $form['googleanalytics_custom_var']['googleanalytics_custom_var_description'] = array(
257 '#type' => 'item',
ad86b8b8 258 '#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')),
26110623 259 );
260 $form['googleanalytics_custom_var']['googleanalytics_custom_var_token_tree'] = array(
26110623 261 '#theme' => 'token_tree',
2d846b38 262 '#token_types' => array('node'),
60b6111f 263 );
264
26110623 265
60b6111f 266 // Advanced feature configurations.
5bcdd55b 267 $form['advanced'] = array(
268 '#type' => 'fieldset',
60b6111f 269 '#title' => t('Advanced settings'),
5bcdd55b 270 '#collapsible' => TRUE,
271 '#collapsed' => TRUE,
60b6111f 272 );
273
b44fb664 274 $form['advanced']['googleanalytics_tracker_anonymizeip'] = array(
275 '#type' => 'checkbox',
276 '#title' => t('Anonymize visitors IP address'),
b44fb664 277 '#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.'),
0753fcd1 278 '#default_value' => variable_get('googleanalytics_tracker_anonymizeip', 0),
b44fb664 279 );
280
5bcdd55b 281 $form['advanced']['googleanalytics_cache'] = array(
282 '#type' => 'checkbox',
a8664f42 283 '#title' => t('Locally cache tracking code file'),
284 '#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!"),
5bcdd55b 285 '#default_value' => variable_get('googleanalytics_cache', 0),
286 );
97110728 287
288 // Allow for tracking of the originating node when viewing translation sets.
289 if (module_exists('translation')) {
290 $form['advanced']['googleanalytics_translation_set'] = array(
291 '#type' => 'checkbox',
292 '#title' => t('Track translation sets as one unit'),
293 '#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.'),
294 '#default_value' => variable_get('googleanalytics_translation_set', 0),
295 );
5bcdd55b 296 }
297
97110728 298 $form['advanced']['codesnippet'] = array(
299 '#type' => 'fieldset',
60b6111f 300 '#title' => t('Custom JavaScript code'),
97110728 301 '#collapsible' => TRUE,
302 '#collapsed' => TRUE,
a8664f42 303 '#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'))
97110728 304 );
305 $form['advanced']['codesnippet']['googleanalytics_codesnippet_before'] = array(
306 '#type' => 'textarea',
307 '#title' => t('Code snippet (before)'),
308 '#default_value' => variable_get('googleanalytics_codesnippet_before', ''),
309 '#rows' => 5,
dbfe5398 310 '#description' => t("Code in this textarea will be added <strong>before</strong> _gaq.push(['_trackPageview'])."),
97110728 311 );
312 $form['advanced']['codesnippet']['googleanalytics_codesnippet_after'] = array(
313 '#type' => 'textarea',
314 '#title' => t('Code snippet (after)'),
315 '#default_value' => variable_get('googleanalytics_codesnippet_after', ''),
60b6111f 316 '#rows' => 5,
dbfe5398 317 '#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."),
60b6111f 318 );
319
320 $form['advanced']['googleanalytics_js_scope'] = array(
321 '#type' => 'select',
322 '#title' => t('JavaScript scope'),
01f3950e 323 '#description' => t('Google recommends adding the external JavaScript files to the header for performance reasons.'),
60b6111f 324 '#options' => array(
325 'footer' => t('Footer'),
326 'header' => t('Header'),
327 ),
01f3950e 328 '#default_value' => variable_get('googleanalytics_js_scope', 'header'),
5bcdd55b 329 );
330
331 return system_settings_form($form);
332}
60b6111f 333
7c745c6a 334/**
335 * Implements _form_validate().
336 */
60b6111f 337function googleanalytics_admin_settings_form_validate($form, &$form_state) {
26110623 338 // Custom variables validation.
339 foreach ($form_state['values']['googleanalytics_custom_var']['slots'] as $custom_var) {
340 // Validate empty names/values.
341 if (empty($custom_var['name']) && !empty($custom_var['value'])) {
342 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'])));
343 }
344 elseif (!empty($custom_var['name']) && empty($custom_var['value'])) {
345 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'])));
346 }
26110623 347 }
348
38901433 349 // Trim some text values.
350 $form_state['values']['googleanalytics_account'] = trim($form_state['values']['googleanalytics_account']);
351 $form_state['values']['googleanalytics_pages'] = trim($form_state['values']['googleanalytics_pages']);
352 $form_state['values']['googleanalytics_codesnippet_before'] = trim($form_state['values']['googleanalytics_codesnippet_before']);
353 $form_state['values']['googleanalytics_codesnippet_after'] = trim($form_state['values']['googleanalytics_codesnippet_after']);
354
60b6111f 355 if (!preg_match('/^UA-\d{4,}-\d+$/', $form_state['values']['googleanalytics_account'])) {
a8664f42 356 form_set_error('googleanalytics_account', t('A valid Google Analytics Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy.'));
60b6111f 357 }
358
8de0b902 359 // Clear obsolete local cache if cache has been disabled.
360 if (empty($form_state['values']['googleanalytics_cache']) && $form['advanced']['googleanalytics_cache']['#default_value']) {
35b6a781 361 googleanalytics_clear_js_cache();
362 }
363
60b6111f 364 // This is for the Newbie's who cannot read a text area description.
97110728 365 if (stristr($form_state['values']['googleanalytics_codesnippet_before'], 'google-analytics.com/ga.js')) {
366 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.'));
367 }
368 if (stristr($form_state['values']['googleanalytics_codesnippet_after'], 'google-analytics.com/ga.js')) {
369 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.'));
370 }
371 if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['googleanalytics_codesnippet_before'])) {
372 form_set_error('googleanalytics_codesnippet_before', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
373 }
374 if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['googleanalytics_codesnippet_after'])) {
375 form_set_error('googleanalytics_codesnippet_after', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
60b6111f 376 }
60b6111f 377}
26110623 378
379/**
380 * Layout for the custom variables table in the admin settings form.
381 */
382function theme_googleanalytics_admin_custom_var_table($variables) {
383 $form = $variables['form'];
384
385 $header = array(
386 array('data' => t('Slot')),
387 array('data' => t('Name')),
388 array('data' => t('Value')),
389 array('data' => t('Scope')),
390 );
391
392 $rows = array();
393 foreach (element_children($form['slots']) as $key => $id) {
394 $rows[] = array(
395 'data' => array(
396 drupal_render($form['slots'][$id]['slot']),
397 drupal_render($form['slots'][$id]['name']),
398 drupal_render($form['slots'][$id]['value']),
399 drupal_render($form['slots'][$id]['scope']),
400 ),
401 );
402 }
403
404 $output = theme('table', array('header' => $header, 'rows' => $rows));
405 $output .= drupal_render($form['googleanalytics_custom_var_description']);
3d84068b 406 $output .= drupal_render($form['googleanalytics_custom_var_token_tree']);
26110623 407
408 return $output;
409}
410
411/**
91359d57 412 * Validate a form element that should have tokens in it.
413 *
414 * For example:
415 * @code
416 * $form['my_node_text_element'] = array(
417 * '#type' => 'textfield',
418 * '#title' => t('Some text to token-ize that has a node context.'),
419 * '#default_value' => 'The title of this node is [node:title].',
420 * '#element_validate' => array('googleanalytics_token_element_validate'),
421 * );
422 * @endcode
423 */
424function googleanalytics_token_element_validate(&$element, &$form_state) {
425 $value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];
426
427 if (!drupal_strlen($value)) {
428 // Empty value needs no further validation since the element should depend
429 // on using the '#required' FAPI property.
430 return $element;
431 }
432
433 // If token module is installed, it is possible to check if the token is valid.
434 if (module_exists('token')) {
435 token_element_validate($element, $form_state);
436 }
437
438 $tokens = token_scan($value);
439 $title = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
440
441 $invalid_tokens = _googleanalytics_get_forbidden_tokens($tokens);
442 if ($invalid_tokens) {
443 form_error($element, t('The %element-title is using the following forbidden tokens with personal identifying information: @invalid-tokens.', array('%element-title' => $title, '@invalid-tokens' => implode(', ', $invalid_tokens))));
444 }
445
446 return $element;
447}
448
449function _googleanalytics_get_forbidden_tokens($value) {
450 $invalid_tokens = array();
451 $value_tokens = is_string($value) ? token_scan($value) : $value;
452
453 foreach ($value_tokens as $type => $tokens) {
454 if (array_filter($tokens, '_googleanalytics_contains_forbidden_token')) {
455 $invalid_tokens = array_merge($invalid_tokens, array_values($tokens));
456 }
457 }
458
459 array_unique($invalid_tokens);
460 return $invalid_tokens;
461}
462
463/**
26110623 464 * Validate if a string contains forbidden tokens not allowed by privacy rules.
465 *
466 * @param $token_string
467 * A string with one or more tokens to be validated.
468 * @return boolean
469 * TRUE if blacklisted token has been found, otherwise FALSE.
470 */
471function _googleanalytics_contains_forbidden_token($token_string) {
472 // List of strings in tokens with personal identifying information not allowed
473 // for privacy reasons. See section 8.1 of the Google Analytics terms of use
474 // for more detailed information.
475 //
476 // This list can never ever be complete. For this reason it tries to use a
477 // regex and may kill a few other valid tokens, but it's the only way to
478 // protect users as much as possible from admins with illegal ideas.
479 //
480 // User tokens are not prefixed with colon to catch 'current-user' and 'user'.
481 //
482 // TODO: If someone have better ideas, share them, please!
483 $token_blacklist = array(
484 ':author]',
485 ':author:edit-url]',
486 ':author:url]',
487 ':author:path]',
9cd6439b 488 ':fid]',
26110623 489 ':mail]',
490 ':name]',
491 ':uid]',
9cd6439b 492 ':one-time-login-url]',
493 ':owner]',
494 ':owner:cancel-url]',
495 ':owner:edit-url]',
496 ':owner:url]',
497 ':owner:path]',
498 'user:cancel-url]',
26110623 499 'user:edit-url]',
500 'user:url]',
501 'user:path]',
502 );
503
504 return preg_match('/' . implode('|', array_map('preg_quote', $token_blacklist)) . '/i', $token_string);
505}