Projet

Général

Profil

Paste
Télécharger (25,1 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / piwik / piwik.admin.inc @ e9f59589

1
<?php
2

    
3
/**
4
 * @file
5
 * Administrative page callbacks for the piwik module.
6
 */
7

    
8
/**
9
 * Implements hook_admin_settings() for configuring the module.
10
 */
11
function piwik_admin_settings_form($form_state) {
12
  $form['account'] = array(
13
    '#type' => 'fieldset',
14
    '#title' => t('General settings'),
15
  );
16

    
17
  $form['account']['piwik_site_id'] = array(
18
    '#type' => 'textfield',
19
    '#title' => t('Piwik site ID'),
20
    '#default_value' => variable_get('piwik_site_id', ''),
21
    '#size' => 15,
22
    '#maxlength' => 20,
23
    '#required' => TRUE,
24
    '#description' => t('The user account number is unique to the websites domain. Click the <strong>Settings</strong> link in your Piwik account, then the <strong>Websites</strong> tab and enter the appropriate site <strong>ID</strong> into this field.'),
25
  );
26
  $form['account']['piwik_url_http'] = array(
27
    '#type' => 'textfield',
28
    '#title' => t('Piwik HTTP URL'),
29
    '#default_value' => variable_get('piwik_url_http', ''),
30
    '#size' => 80,
31
    '#maxlength' => 255,
32
    '#required' => TRUE,
33
    '#description' => t('The URL to your Piwik base directory. Example: "http://www.example.com/piwik/".'),
34
  );
35
  $form['account']['piwik_url_https'] = array(
36
    '#type' => 'textfield',
37
    '#title' => t('Piwik HTTPS URL'),
38
    '#default_value' => variable_get('piwik_url_https', ''),
39
    '#size' => 80,
40
    '#maxlength' => 255,
41
    '#description' => t('The URL to your Piwik base directory with SSL certificate installed. Required if you track a SSL enabled website. Example: "https://www.example.com/piwik/".'),
42
  );
43

    
44
  // Visibility settings.
45
  $form['tracking_title'] = array(
46
    '#type' => 'item',
47
    '#title' => t('Tracking scope'),
48
  );
49
  $form['tracking'] = array(
50
    '#type' => 'vertical_tabs',
51
    '#attached' => array(
52
      'js' => array(drupal_get_path('module', 'piwik') . '/piwik.admin.js'),
53
    ),
54
  );
55

    
56
  $form['tracking']['domain_tracking'] = array(
57
    '#type' => 'fieldset',
58
    '#title' => t('Domains'),
59
  );
60

    
61
  global $cookie_domain;
62
  $multiple_sub_domains = array();
63
  foreach (array('www', 'app', 'shop') as $subdomain) {
64
    if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
65
      $multiple_sub_domains[] = $subdomain . $cookie_domain;
66
    }
67
    // IP addresses or localhost.
68
    else {
69
      $multiple_sub_domains[] = $subdomain . '.example.com';
70
    }
71
  }
72

    
73
  $form['tracking']['domain_tracking']['piwik_domain_mode'] = array(
74
    '#type' => 'radios',
75
    '#title' => t('What are you tracking?'),
76
    '#options' => array(
77
      0 => t('A single domain (default)') . '<div class="description">' . t('Domain: @domain', array('@domain' => $_SERVER['HTTP_HOST'])) . '</div>',
78
      1 => t('One domain with multiple subdomains') . '<div class="description">' . t('Examples: @domains', array('@domains' => implode(', ', $multiple_sub_domains))) . '</div>',
79
    ),
80
    '#default_value' => variable_get('piwik_domain_mode', 0),
81
  );
82

    
83
  // Page specific visibility configurations.
84
  $php_access = user_access('use PHP for tracking visibility');
85
  $visibility = variable_get('piwik_visibility_pages', 0);
86
  $pages = variable_get('piwik_pages', PIWIK_PAGES);
87

    
88
  $form['tracking']['page_vis_settings'] = array(
89
    '#type' => 'fieldset',
90
    '#title' => t('Pages'),
91
    '#collapsible' => TRUE,
92
    '#collapsed' => TRUE,
93
  );
94

    
95
  if ($visibility == 2 && !$php_access) {
96
    $form['tracking']['page_vis_settings'] = array();
97
    $form['tracking']['page_vis_settings']['visibility'] = array('#type' => 'value', '#value' => 2);
98
    $form['tracking']['page_vis_settings']['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

    
107
    if (module_exists('php') && $php_access) {
108
      $options[] = t('Pages on which this PHP code returns <code>TRUE</code> (experts only)');
109
      $title = t('Pages or PHP code');
110
      $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 ?>'));
111
    }
112
    else {
113
      $title = t('Pages');
114
    }
115
    $form['tracking']['page_vis_settings']['piwik_visibility_pages'] = array(
116
      '#type' => 'radios',
117
      '#title' => t('Add tracking to specific pages'),
118
      '#options' => $options,
119
      '#default_value' => $visibility,
120
    );
121
    $form['tracking']['page_vis_settings']['piwik_pages'] = array(
122
      '#type' => 'textarea',
123
      '#title' => $title,
124
      '#title_display' => 'invisible',
125
      '#default_value' => $pages,
126
      '#description' => $description,
127
      '#rows' => 10,
128
    );
129
  }
130

    
131
  // Render the role overview.
132
  $form['tracking']['role_vis_settings'] = array(
133
    '#type' => 'fieldset',
134
    '#title' => t('Roles'),
135
  );
136

    
137
  $form['tracking']['role_vis_settings']['piwik_visibility_roles'] = array(
138
    '#type' => 'radios',
139
    '#title' => t('Add tracking for specific roles'),
140
    '#options' => array(
141
      t('Add to the selected roles only'),
142
      t('Add to every role except the selected ones'),
143
    ),
144
    '#default_value' => variable_get('piwik_visibility_roles', 0),
145
  );
146

    
147
  $role_options = array_map('check_plain', user_roles());
148
  $form['tracking']['role_vis_settings']['piwik_roles'] = array(
149
    '#type' => 'checkboxes',
150
    '#title' => t('Roles'),
151
    '#default_value' => variable_get('piwik_roles', array()),
152
    '#options' => $role_options,
153
    '#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).'),
154
  );
155

    
156
  // Standard tracking configurations.
157
  $form['tracking']['user_vis_settings'] = array(
158
    '#type' => 'fieldset',
159
    '#title' => t('Users'),
160
  );
161
  $t_permission = array('%permission' => t('opt-in or out of tracking'));
162
  $form['tracking']['user_vis_settings']['piwik_custom'] = array(
163
    '#type' => 'radios',
164
    '#title' => t('Allow users to customize tracking on their account page'),
165
    '#options' => array(
166
      t('No customization allowed'),
167
      t('Tracking on by default, users with %permission permission can opt out', $t_permission),
168
      t('Tracking off by default, users with %permission permission can opt in', $t_permission)
169
    ),
170
    '#default_value' => variable_get('piwik_custom', 0),
171
  );
172

    
173
  // Link specific configurations.
174
  $form['tracking']['linktracking'] = array(
175
    '#type' => 'fieldset',
176
    '#title' => t('Links and downloads'),
177
  );
178
  $form['tracking']['linktracking']['piwik_trackmailto'] = array(
179
    '#type' => 'checkbox',
180
    '#title' => t('Track clicks on mailto links'),
181
    '#default_value' => variable_get('piwik_trackmailto', 1),
182
  );
183
  $form['tracking']['linktracking']['piwik_track'] = array(
184
    '#type' => 'checkbox',
185
    '#title' => t('Track clicks on outbound links and downloads (clicks on file links) for the following extensions'),
186
    '#default_value' => variable_get('piwik_track', 1),
187
  );
188
  $form['tracking']['linktracking']['piwik_trackfiles_extensions'] = array(
189
    '#title' => t('List of download file extensions'),
190
    '#title_display' => 'invisible',
191
    '#type' => 'textfield',
192
    '#default_value' => variable_get('piwik_trackfiles_extensions', PIWIK_TRACKFILES_EXTENSIONS),
193
    '#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' => PIWIK_TRACKFILES_EXTENSIONS)),
194
    '#maxlength' => 255,
195
    '#states' => array(
196
      'enabled' => array(
197
        ':input[name="piwik_track"]' => array('checked' => TRUE),
198
      ),
199
      # Note: Form required marker is not visible as title is invisible.
200
      'required' => array(
201
        ':input[name="piwik_track"]' => array('checked' => TRUE),
202
      ),
203
    ),
204
  );
205

    
206
  // Message specific configurations.
207
  $form['tracking']['messagetracking'] = array(
208
    '#type' => 'fieldset',
209
    '#title' => t('Messages'),
210
  );
211
  $form['tracking']['messagetracking']['piwik_trackmessages'] = array(
212
    '#type' => 'checkboxes',
213
    '#title' => t('Track messages of type'),
214
    '#default_value' => variable_get('piwik_trackmessages', array()),
215
    '#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. Every message is tracked as one individual event. Messages from excluded pages cannot tracked.'),
216
    '#options' => array(
217
      'status' => t('Status message'),
218
      'warning' => t('Warning message'),
219
      'error' => t('Error message'),
220
    ),
221
  );
222

    
223
  $form['tracking']['search'] = array(
224
    '#type' => 'fieldset',
225
    '#title' => t('Search'),
226
  );
227

    
228
  $site_search_dependencies = '<div class="admin-requirements">';
229
  $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')))));
230
  $site_search_dependencies .= '</div>';
231

    
232
  $form['tracking']['search']['piwik_site_search'] = array(
233
    '#type' => 'checkbox',
234
    '#title' => t('Track internal search'),
235
    '#description' => t('If checked, internal search keywords are tracked.') . $site_search_dependencies,
236
    '#default_value' => variable_get('piwik_site_search', FALSE),
237
    '#disabled' => (module_exists('search') ? FALSE : TRUE),
238
  );
239

    
240
  // Privacy specific configurations.
241
  $form['tracking']['privacy'] = array(
242
    '#type' => 'fieldset',
243
    '#title' => t('Privacy'),
244
  );
245
  $form['tracking']['privacy']['piwik_privacy_donottrack'] = array(
246
    '#type' => 'checkbox',
247
    '#title' => t('Universal web tracking opt-out'),
248
    '#description' => t('If enabled and your Piwik server receives the <a href="http://donottrack.us/">Do-Not-Track</a> header from the client browser, the Piwik server will not track the user. 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.'),
249
    '#default_value' => variable_get('piwik_privacy_donottrack', 1),
250
  );
251

    
252
  // Piwik page title tree view settings.
253
  $form['page_title_hierarchy'] = array(
254
    '#type' => 'fieldset',
255
    '#title' => t('Page titles hierarchy'),
256
    '#description' => t('This functionality enables a dynamically expandable tree view of your site page titles in your Piwik statistics. See in Piwik statistics under <em>Actions</em> > <em>Page titles</em>.'),
257
    '#collapsible' => TRUE,
258
    '#collapsed' => FALSE,
259
  );
260
  $form['page_title_hierarchy']['piwik_page_title_hierarchy'] = array(
261
    '#type' => 'checkbox',
262
    '#title' => t("Show page titles as hierarchy like breadcrumbs"),
263
    '#description' => t('By default Piwik tracks the current page title and shows you a flat list of the most popular titles. This enables a breadcrumbs like tree view.'),
264
    '#default_value' => variable_get('piwik_page_title_hierarchy', FALSE),
265
  );
266
  $form['page_title_hierarchy']['piwik_page_title_hierarchy_exclude_home'] = array(
267
    '#type' => 'checkbox',
268
    '#title' => t('Hide home page from hierarchy'),
269
    '#description' => t('If enabled, the "Home" item will be removed from the hierarchy to flatten the structure in the Piwik statistics. Hits to the home page will still be counted, but for other pages the hierarchy will start at level Home+1.'),
270
    '#default_value' => variable_get('piwik_page_title_hierarchy_exclude_home', TRUE),
271
  );
272

    
273
  $form['piwik_custom_var'] = array(
274
    '#collapsible' => TRUE,
275
  	'#collapsed' => TRUE,
276
    '#description' => t('You can add Piwiks <a href="!custom_var_documentation">Custom Variables</a> here. These will be added to every page that Piwik tracking code appears on. Custom variable names and values are limited to 200 characters in length. Keep the names and values 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' => 'http://piwik.org/docs/custom-variables/')),
277
    '#theme' => 'piwik_admin_custom_var_table',
278
    '#title' => t('Custom variables'),
279
    '#tree' => TRUE,
280
    '#type' => 'fieldset',
281
  );
282

    
283
  $piwik_custom_vars = variable_get('piwik_custom_var', array());
284

    
285
  // Piwik supports up to 5 custom variables.
286
  for ($i = 1; $i < 6; $i++) {
287
    $form['piwik_custom_var']['slots'][$i]['slot'] = array(
288
      '#default_value' => $i,
289
      '#description' => t('Slot number'),
290
      '#disabled' => TRUE,
291
      '#size' => 1,
292
      '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
293
      '#title_display' => 'invisible',
294
      '#type' => 'textfield',
295
    );
296
    $form['piwik_custom_var']['slots'][$i]['name'] = array(
297
      '#default_value' => !empty($piwik_custom_vars['slots'][$i]['name']) ? $piwik_custom_vars['slots'][$i]['name'] : '',
298
      '#description' => t('The custom variable name.'),
299
      '#maxlength' => 100,
300
    	'#size' => 20,
301
      '#title' => t('Custom variable name #@slot', array('@slot' => $i)),
302
      '#title_display' => 'invisible',
303
      '#type' => 'textfield',
304
    );
305
    $form['piwik_custom_var']['slots'][$i]['value'] = array(
306
      '#default_value' => !empty($piwik_custom_vars['slots'][$i]['value']) ? $piwik_custom_vars['slots'][$i]['value'] : '',
307
      '#description' => t('The custom variable value.'),
308
      '#maxlength' => 255,
309
      '#title' => t('Custom variable value #@slot', array('@slot' => $i)),
310
      '#title_display' => 'invisible',
311
      '#type' => 'textfield',
312
      '#element_validate' => array('piwik_token_element_validate'),
313
      '#token_types' => array('node'),
314
    );
315
    if (module_exists('token')) {
316
      $form['piwik_custom_var']['slots'][$i]['value']['#element_validate'][] = 'token_element_validate';
317
    }
318
    $form['piwik_custom_var']['slots'][$i]['scope'] = array(
319
      '#default_value' => !empty($piwik_custom_vars['slots'][$i]['scope']) ? $piwik_custom_vars['slots'][$i]['scope'] : 'visit',
320
      '#description' => t('The scope for the custom variable.'),
321
      '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
322
      '#title_display' => 'invisible',
323
      '#type' => 'select',
324
      '#options' => array(
325
        'visit' => t('Visit'),
326
        'page' => t('Page'),
327
      ),
328
    );
329
  }
330

    
331
  $form['piwik_custom_var']['piwik_custom_var_description'] = array(
332
    '#type' => 'item',
333
    '#description' => t('You can supplement Piwiks\' basic IP address tracking of visitors by segmenting users based on custom variables. 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 Piwik\' service.'),
334
  );
335
  $form['piwik_custom_var']['piwik_custom_var_token_tree'] = array(
336
    '#theme' => 'token_tree',
337
    '#token_types' => array('node'),
338
    '#dialog' => TRUE,
339
  );
340

    
341
  // Advanced feature configurations.
342
  $form['advanced'] = array(
343
    '#type' => 'fieldset',
344
    '#title' => t('Advanced settings'),
345
    '#collapsible' => TRUE,
346
    '#collapsed' => TRUE,
347
  );
348

    
349
  $form['advanced']['piwik_cache'] = array(
350
    '#type' => 'checkbox',
351
    '#title' => t('Locally cache tracking code file'),
352
    '#description' => t('If checked, the tracking code file is retrieved from your Piwik site and cached locally. It is updated daily to ensure updates to tracking code are reflected in the local copy.'),
353
    '#default_value' => variable_get('piwik_cache', 0),
354
  );
355

    
356
  // Allow for tracking of the originating node when viewing translation sets.
357
  if (module_exists('translation')) {
358
    $form['advanced']['piwik_translation_set'] = array(
359
      '#type' => 'checkbox',
360
      '#title' => t('Track translation sets as one unit'),
361
      '#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.'),
362
      '#default_value' => variable_get('piwik_translation_set', 0),
363
    );
364
  }
365

    
366
  // Code snippet settings.
367
  $form['advanced']['codesnippet'] = array(
368
    '#type' => 'fieldset',
369
    '#title' => t('Custom JavaScript code'),
370
    '#collapsible' => TRUE,
371
    '#collapsed' => TRUE,
372
    '#description' => t('You can add custom Piwik <a href="@snippets">code snippets</a> here. These will be added to every page that Piwik appears on. <strong>Do not include the &lt;script&gt; tags</strong>, and always end your code with a semicolon (;).', array('@snippets' => 'http://piwik.org/docs/javascript-tracking/'))
373
  );
374
  $form['advanced']['codesnippet']['piwik_codesnippet_before'] = array(
375
    '#type' => 'textarea',
376
    '#title' => t('Code snippet (before)'),
377
    '#default_value' => variable_get('piwik_codesnippet_before', ''),
378
    '#rows' => 5,
379
    '#description' => t('Code in this textarea will be added <strong>before</strong> _paq.push(["trackPageView"]).')
380
  );
381
  $form['advanced']['codesnippet']['piwik_codesnippet_after'] = array(
382
    '#type' => 'textarea',
383
    '#title' => t('Code snippet (after)'),
384
    '#default_value' => variable_get('piwik_codesnippet_after', ''),
385
    '#rows' => 5,
386
    '#description' => t('Code in this textarea will be added <strong>after</strong> _paq.push(["trackPageView"]). This is useful if you\'d like to track a site in two accounts.')
387
  );
388

    
389
  $form['advanced']['piwik_js_scope'] = array(
390
    '#type' => 'select',
391
    '#title' => t('JavaScript scope'),
392
    '#description' => t("Piwik recommends adding the tracking code to the header for performance reasons."),
393
    '#options' => array(
394
      'footer' => t('Footer'),
395
      'header' => t('Header'),
396
    ),
397
    '#default_value' => variable_get('piwik_js_scope', 'header'),
398
  );
399

    
400
  return system_settings_form($form);
401
}
402

    
403
function piwik_admin_settings_form_validate($form, &$form_state) {
404
  // Custom variables validation.
405
  foreach ($form_state['values']['piwik_custom_var']['slots'] as $custom_var) {
406
    $form_state['values']['piwik_custom_var']['slots'][$custom_var['slot']]['name'] = trim($custom_var['name']);
407
    $form_state['values']['piwik_custom_var']['slots'][$custom_var['slot']]['value'] = trim($custom_var['value']);
408

    
409
    // Validate empty names/values.
410
    if (empty($custom_var['name']) && !empty($custom_var['value'])) {
411
      form_set_error("piwik_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'])));
412
    }
413
    elseif (!empty($custom_var['name']) && empty($custom_var['value'])) {
414
      form_set_error("piwik_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'])));
415
    }
416
  }
417

    
418
  // Trim some text area values.
419
  $form_state['values']['piwik_site_id'] = trim($form_state['values']['piwik_site_id']);
420
  $form_state['values']['piwik_pages'] = trim($form_state['values']['piwik_pages']);
421
  $form_state['values']['piwik_codesnippet_before'] = trim($form_state['values']['piwik_codesnippet_before']);
422
  $form_state['values']['piwik_codesnippet_after'] = trim($form_state['values']['piwik_codesnippet_after']);
423

    
424
  if (!preg_match('/^\d{1,}$/', $form_state['values']['piwik_site_id'])) {
425
    form_set_error('piwik_site_id', t('A valid Piwik site ID is an integer only.'));
426
  }
427

    
428
  $url = $form_state['values']['piwik_url_http'] . 'piwik.php';
429
  $result = drupal_http_request($url);
430
  if ($result->code != 200) {
431
    form_set_error('piwik_url_http', t('The validation of "@url" failed with error "@error" (HTTP code @code).', array('@url' => check_url($url), '@error' => $result->error, '@code' => $result->code)));
432
  }
433

    
434
  if (!empty($form_state['values']['piwik_url_https'])) {
435
    $url = $form_state['values']['piwik_url_https'] . 'piwik.php';
436
    $result = drupal_http_request($url);
437
    if ($result->code != 200) {
438
      form_set_error('piwik_url_https', t('The validation of "@url" failed with error "@error" (HTTP code @code).', array('@url' => check_url($url), '@error' => $result->error, '@code' => $result->code)));
439
    }
440
  }
441

    
442
  // Delete obsolete local cache file.
443
  if (empty($form_state['values']['piwik_cache']) && $form['advanced']['piwik_cache']['#default_value']) {
444
    piwik_clear_js_cache();
445
  }
446

    
447
  // This is for the Newbie's who cannot read a text area description.
448
  if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['piwik_codesnippet_before'])) {
449
    form_set_error('piwik_codesnippet_before', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
450
  }
451
  if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['piwik_codesnippet_after'])) {
452
    form_set_error('piwik_codesnippet_after', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
453
  }
454
}
455

    
456
/**
457
 * Layout for the custom variables table in the admin settings form.
458
 */
459
function theme_piwik_admin_custom_var_table($variables) {
460
  $form = $variables['form'];
461

    
462
  $header = array(
463
    array('data' => t('Slot')),
464
    array('data' => t('Name')),
465
    array('data' => t('Value')),
466
    array('data' => t('Scope')),
467
  );
468

    
469
  $rows = array();
470
  foreach (element_children($form['slots']) as $key => $id) {
471
    $rows[] = array(
472
      'data' => array(
473
        drupal_render($form['slots'][$id]['slot']),
474
        drupal_render($form['slots'][$id]['name']),
475
        drupal_render($form['slots'][$id]['value']),
476
        drupal_render($form['slots'][$id]['scope']),
477
      ),
478
    );
479
  }
480

    
481
  $output = theme('table', array('header' => $header, 'rows' => $rows));
482
  $output .= drupal_render($form['piwik_custom_var_description']);
483
  $output .= drupal_render($form['piwik_custom_var_token_tree']);
484

    
485
  return $output;
486
}
487

    
488
/**
489
 * Validate a form element that should have tokens in it.
490
 *
491
 * For example:
492
 * @code
493
 * $form['my_node_text_element'] = array(
494
 *   '#type' => 'textfield',
495
 *   '#title' => t('Some text to token-ize that has a node context.'),
496
 *   '#default_value' => 'The title of this node is [node:title].',
497
 *   '#element_validate' => array('piwik_token_element_validate'),
498
 * );
499
 * @endcode
500
 */
501
function piwik_token_element_validate(&$element, &$form_state) {
502
  $value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];
503

    
504
  if (!drupal_strlen($value)) {
505
    // Empty value needs no further validation since the element should depend
506
    // on using the '#required' FAPI property.
507
    return $element;
508
  }
509

    
510
  $tokens = token_scan($value);
511
  $invalid_tokens = _piwik_get_forbidden_tokens($tokens);
512
  if ($invalid_tokens) {
513
    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))));
514
  }
515

    
516
  return $element;
517
}
518

    
519
function _piwik_get_forbidden_tokens($value) {
520
  $invalid_tokens = array();
521
  $value_tokens = is_string($value) ? token_scan($value) : $value;
522

    
523
  foreach ($value_tokens as $type => $tokens) {
524
    if (array_filter($tokens, '_piwik_contains_forbidden_token')) {
525
      $invalid_tokens = array_merge($invalid_tokens, array_values($tokens));
526
    }
527
  }
528

    
529
  array_unique($invalid_tokens);
530
  return $invalid_tokens;
531
}
532

    
533
/**
534
 * Validate if a string contains forbidden tokens not allowed by privacy rules.
535
 *
536
 * @param $token_string
537
 *   A string with one or more tokens to be validated.
538
 * @return boolean
539
 *   TRUE if blacklisted token has been found, otherwise FALSE.
540
 */
541
function _piwik_contains_forbidden_token($token_string) {
542
  // List of strings in tokens with personal identifying information not allowed
543
  // for privacy reasons. See section 8.1 of the Google Analytics terms of use
544
  // for more detailed information.
545
  //
546
  // This list can never ever be complete. For this reason it tries to use a
547
  // regex and may kill a few other valid tokens, but it's the only way to
548
  // protect users as much as possible from admins with illegal ideas.
549
  //
550
  // User tokens are not prefixed with colon to catch 'current-user' and 'user'.
551
  //
552
  // TODO: If someone have better ideas, share them, please!
553
  $token_blacklist = array(
554
    ':author]',
555
    ':author:edit-url]',
556
    ':author:url]',
557
    ':author:path]',
558
    ':current-user]',
559
    ':current-user:original]',
560
    ':fid]',
561
    ':mail]',
562
    ':name]',
563
    ':uid]',
564
    ':one-time-login-url]',
565
    ':owner]',
566
    ':owner:cancel-url]',
567
    ':owner:edit-url]',
568
    ':owner:url]',
569
    ':owner:path]',
570
    'user:cancel-url]',
571
    'user:edit-url]',
572
    'user:url]',
573
    'user:path]',
574
    'user:picture]',
575
    // addressfield_tokens.module
576
    ':first-name]',
577
    ':last-name]',
578
    ':name-line]',
579
    ':mc-address]',
580
    ':thoroughfare]',
581
    ':premise]',
582
    // realname.module
583
    ':name-raw]',
584
    // token.module
585
    ':ip-address]',
586
  );
587

    
588
  return preg_match('/' . implode('|', array_map('preg_quote', $token_blacklist)) . '/i', $token_string);
589
}