Projet

Général

Profil

Paste
Télécharger (27,8 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / matomo / matomo.admin.inc @ cd5c298a

1 60283730 Assos Assos
<?php
2
3
/**
4
 * @file
5
 * Administrative page callbacks for the matomo module.
6
 */
7
8
/**
9
 * Implements hook_admin_settings() for configuring the module.
10
 */
11
function matomo_admin_settings_form($form_state) {
12
  $form['account'] = array(
13
    '#type' => 'fieldset',
14
    '#title' => t('General settings'),
15
  );
16
17
  $form['account']['matomo_site_id'] = array(
18
    '#type' => 'textfield',
19
    '#title' => t('Matomo site ID'),
20
    '#default_value' => variable_get('matomo_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 Matomo account, then the <strong>Websites</strong> tab and enter the appropriate site <strong>ID</strong> into this field.'),
25
  );
26
  $form['account']['matomo_url_http'] = array(
27
    '#type' => 'textfield',
28
    '#title' => t('Matomo HTTP URL'),
29
    '#default_value' => variable_get('matomo_url_http', ''),
30
    '#size' => 80,
31
    '#maxlength' => 255,
32
    '#required' => TRUE,
33
    '#description' => t('The URL to your Matomo base directory. Example: "http://www.example.com/matomo/".'),
34
  );
35
  $form['account']['matomo_url_https'] = array(
36
    '#type' => 'textfield',
37
    '#title' => t('Matomo HTTPS URL'),
38
    '#default_value' => variable_get('matomo_url_https', ''),
39
    '#size' => 80,
40
    '#maxlength' => 255,
41
    '#description' => t('The URL to your Matomo base directory with SSL certificate installed. Required if you track a SSL enabled website. Example: "https://www.example.com/matomo/".'),
42
  );
43
  // Required for automated form save testing only.
44
  $form['account']['matomo_url_skiperror'] = array(
45
    '#type' => 'hidden',
46
    '#default_value' => FALSE,
47
  );
48
49
  // Visibility settings.
50
  $form['tracking_title'] = array(
51
    '#type' => 'item',
52
    '#title' => t('Tracking scope'),
53
  );
54
  $form['tracking'] = array(
55
    '#type' => 'vertical_tabs',
56
    '#attached' => array(
57
      'js' => array(drupal_get_path('module', 'matomo') . '/matomo.admin.js'),
58
    ),
59
  );
60
61
  $form['tracking']['domain_tracking'] = array(
62
    '#type' => 'fieldset',
63
    '#title' => t('Domains'),
64
  );
65
66
  global $cookie_domain;
67
  $multiple_sub_domains = array();
68
  foreach (array('www', 'app', 'shop') as $subdomain) {
69
    if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
70
      $multiple_sub_domains[] = $subdomain . $cookie_domain;
71
    }
72
    // IP addresses or localhost.
73
    else {
74
      $multiple_sub_domains[] = $subdomain . '.example.com';
75
    }
76
  }
77
78
  $form['tracking']['domain_tracking']['matomo_domain_mode'] = array(
79
    '#type' => 'radios',
80
    '#title' => t('What are you tracking?'),
81
    '#options' => array(
82
      0 => t('A single domain (default)') . '<div class="description">' . t('Domain: @domain', array('@domain' => $_SERVER['HTTP_HOST'])) . '</div>',
83
      1 => t('One domain with multiple subdomains') . '<div class="description">' . t('Examples: @domains', array('@domains' => implode(', ', $multiple_sub_domains))) . '</div>',
84
    ),
85
    '#default_value' => variable_get('matomo_domain_mode', 0),
86
  );
87
88
  // Page specific visibility configurations.
89
  $php_access = user_access('use php for matomo tracking visibility');
90
  $visibility = variable_get('matomo_visibility_pages', 0);
91
  $pages = variable_get('matomo_pages', MATOMO_PAGES);
92
93
  $form['tracking']['page_vis_settings'] = array(
94
    '#type' => 'fieldset',
95
    '#title' => t('Pages'),
96
    '#collapsible' => TRUE,
97
    '#collapsed' => TRUE,
98
  );
99
100
  if ($visibility == 2 && !$php_access) {
101
    $form['tracking']['page_vis_settings'] = array();
102
    $form['tracking']['page_vis_settings']['matomo_visibility_pages'] = array('#type' => 'value', '#value' => 2);
103
    $form['tracking']['page_vis_settings']['matomo_pages'] = array('#type' => 'value', '#value' => $pages);
104
  }
105
  else {
106
    $options = array(
107
      t('Every page except the listed pages'),
108
      t('The listed pages only')
109
    );
110
    $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>'));
111
112
    if (module_exists('php') && $php_access) {
113
      $options[] = t('Pages on which this PHP code returns <code>TRUE</code> (experts only)');
114
      $title = t('Pages or PHP code');
115
      $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 ?>'));
116
    }
117
    else {
118
      $title = t('Pages');
119
    }
120
    $form['tracking']['page_vis_settings']['matomo_visibility_pages'] = array(
121
      '#type' => 'radios',
122
      '#title' => t('Add tracking to specific pages'),
123
      '#options' => $options,
124
      '#default_value' => $visibility,
125
    );
126
    $form['tracking']['page_vis_settings']['matomo_pages'] = array(
127
      '#type' => 'textarea',
128
      '#title' => $title,
129
      '#title_display' => 'invisible',
130
      '#default_value' => $pages,
131
      '#description' => $description,
132
      '#rows' => 10,
133
    );
134
  }
135
136
  // Render the role overview.
137
  $form['tracking']['role_vis_settings'] = array(
138
    '#type' => 'fieldset',
139
    '#title' => t('Roles'),
140
  );
141
142
  $form['tracking']['role_vis_settings']['matomo_visibility_roles'] = array(
143
    '#type' => 'radios',
144
    '#title' => t('Add tracking for specific roles'),
145
    '#options' => array(
146
      t('Add to the selected roles only'),
147
      t('Add to every role except the selected ones'),
148
    ),
149
    '#default_value' => variable_get('matomo_visibility_roles', 0),
150
  );
151
152
  $role_options = array_map('check_plain', user_roles());
153
  $form['tracking']['role_vis_settings']['matomo_roles'] = array(
154
    '#type' => 'checkboxes',
155
    '#title' => t('Roles'),
156
    '#default_value' => variable_get('matomo_roles', array()),
157
    '#options' => $role_options,
158
    '#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).'),
159
  );
160
161
  // Standard tracking configurations.
162
  $form['tracking']['user_vis_settings'] = array(
163
    '#type' => 'fieldset',
164
    '#title' => t('Users'),
165
  );
166
  $t_permission = array('%permission' => t('Opt-in or out of tracking'));
167
  $form['tracking']['user_vis_settings']['matomo_custom'] = array(
168
    '#type' => 'radios',
169
    '#title' => t('Allow users to customize tracking on their account page'),
170
    '#options' => array(
171
      0 => t('No customization allowed'),
172
      1 => t('Tracking on by default, users with %permission permission can opt out', $t_permission),
173
      2 => t('Tracking off by default, users with %permission permission can opt in', $t_permission)
174
    ),
175
    '#default_value' => variable_get('matomo_custom', 1),
176
  );
177
  $form['tracking']['user_vis_settings']['matomo_trackuserid'] = array(
178
    '#type' => 'checkbox',
179
    '#title' => t('Track User ID'),
180
    '#default_value' => variable_get('matomo_trackuserid', 0),
181 cd5c298a Geoffroy Desvernay
    '#description' => t('User ID enables the analysis of groups of sessions, across devices, using a unique, persistent, and non-personally identifiable ID string representing a user. <a href="@url">Learn more about the benefits of using User ID</a>.', array('@url' => 'https://matomo.org/docs/user-id/')),
182 60283730 Assos Assos
  );
183
184
  // Link specific configurations.
185
  $form['tracking']['linktracking'] = array(
186
    '#type' => 'fieldset',
187
    '#title' => t('Links and downloads'),
188
  );
189
  $form['tracking']['linktracking']['matomo_trackmailto'] = array(
190
    '#type' => 'checkbox',
191
    '#title' => t('Track clicks on mailto links'),
192
    '#default_value' => variable_get('matomo_trackmailto', 1),
193
  );
194
  $form['tracking']['linktracking']['matomo_track'] = array(
195
    '#type' => 'checkbox',
196
    '#title' => t('Track clicks on outbound links and downloads (clicks on file links) for the following extensions'),
197
    '#default_value' => variable_get('matomo_track', 1),
198
  );
199
  $form['tracking']['linktracking']['matomo_trackfiles_extensions'] = array(
200
    '#title' => t('List of download file extensions'),
201
    '#title_display' => 'invisible',
202
    '#type' => 'textfield',
203
    '#default_value' => variable_get('matomo_trackfiles_extensions', MATOMO_TRACKFILES_EXTENSIONS),
204
    '#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' => MATOMO_TRACKFILES_EXTENSIONS)),
205
    '#maxlength' => 500,
206
    '#states' => array(
207
      'enabled' => array(
208
        ':input[name="matomo_track"]' => array('checked' => TRUE),
209
      ),
210
      # Note: Form required marker is not visible as title is invisible.
211
      'required' => array(
212
        ':input[name="matomo_track"]' => array('checked' => TRUE),
213
      ),
214
    ),
215
  );
216
217
  $colorbox_dependencies = '<div class="admin-requirements">';
218
  $colorbox_dependencies .= t('Requires: !module-list', array('!module-list' => (module_exists('colorbox') ? t('@module (<span class="admin-enabled">enabled</span>)', array('@module' => 'Colorbox')) : t('@module (<span class="admin-disabled">disabled</span>)', array('@module' => 'Colorbox')))));
219
  $colorbox_dependencies .= '</div>';
220
221
  $form['tracking']['linktracking']['matomo_trackcolorbox'] = array(
222
    '#type' => 'checkbox',
223
    '#title' => t('Track content in colorbox modal dialogs'),
224
    '#default_value' => variable_get('matomo_trackcolorbox', 1),
225
    '#description' => t('Enable to track the content shown in colorbox modal windows.') . $colorbox_dependencies,
226
    '#disabled' => (module_exists('colorbox') ? FALSE : TRUE),
227
  );
228
229
  // Message specific configurations.
230
  $form['tracking']['messagetracking'] = array(
231
    '#type' => 'fieldset',
232
    '#title' => t('Messages'),
233
  );
234
  $form['tracking']['messagetracking']['matomo_trackmessages'] = array(
235
    '#type' => 'checkboxes',
236
    '#title' => t('Track messages of type'),
237
    '#default_value' => variable_get('matomo_trackmessages', array()),
238
    '#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 be tracked.'),
239
    '#options' => array(
240
      'status' => t('Status message'),
241
      'warning' => t('Warning message'),
242
      'error' => t('Error message'),
243
    ),
244
  );
245
246
  $form['tracking']['search'] = array(
247
    '#type' => 'fieldset',
248
    '#title' => t('Search'),
249
  );
250
251
  $site_search_dependencies = '<div class="admin-requirements">';
252
  $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')))));
253
  $site_search_dependencies .= '</div>';
254
255
  $form['tracking']['search']['matomo_site_search'] = array(
256
    '#type' => 'checkbox',
257
    '#title' => t('Track internal search'),
258
    '#description' => t('If checked, internal search keywords are tracked.') . $site_search_dependencies,
259
    '#default_value' => variable_get('matomo_site_search', FALSE),
260
    '#disabled' => (module_exists('search') ? FALSE : TRUE),
261
  );
262
263
  // Privacy specific configurations.
264
  $form['tracking']['privacy'] = array(
265
    '#type' => 'fieldset',
266
    '#title' => t('Privacy'),
267
  );
268
  $form['tracking']['privacy']['matomo_privacy_donottrack'] = array(
269
    '#type' => 'checkbox',
270
    '#title' => t('Universal web tracking opt-out'),
271 cd5c298a Geoffroy Desvernay
    '#description' => t('If enabled and your Matomo server receives the <a href="@donottrack">Do-Not-Track</a> header from the client browser, the Matomo 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.', array('@donottrack' => 'https://www.eff.org/issues/do-not-track')),
272 60283730 Assos Assos
    '#default_value' => variable_get('matomo_privacy_donottrack', 1),
273
  );
274
275
  // Matomo page title tree view settings.
276
  $form['page_title_hierarchy'] = array(
277
    '#type' => 'fieldset',
278
    '#title' => t('Page titles hierarchy'),
279
    '#description' => t('This functionality enables a dynamically expandable tree view of your site page titles in your Matomo statistics. See in Matomo statistics under <em>Actions</em> > <em>Page titles</em>.'),
280
    '#collapsible' => TRUE,
281
    '#collapsed' => FALSE,
282
  );
283
  $form['page_title_hierarchy']['matomo_page_title_hierarchy'] = array(
284
    '#type' => 'checkbox',
285
    '#title' => t("Show page titles as hierarchy like breadcrumbs"),
286
    '#description' => t('By default Matomo tracks the current page title and shows you a flat list of the most popular titles. This enables a breadcrumbs like tree view.'),
287
    '#default_value' => variable_get('matomo_page_title_hierarchy', FALSE),
288
  );
289
  $form['page_title_hierarchy']['matomo_page_title_hierarchy_exclude_home'] = array(
290
    '#type' => 'checkbox',
291
    '#title' => t('Hide home page from hierarchy'),
292
    '#description' => t('If enabled, the "Home" item will be removed from the hierarchy to flatten the structure in the Matomo statistics. Hits to the home page will still be counted, but for other pages the hierarchy will start at level Home+1.'),
293
    '#default_value' => variable_get('matomo_page_title_hierarchy_exclude_home', TRUE),
294
  );
295
296
  $form['matomo_custom_var'] = array(
297
    '#collapsible' => TRUE,
298
  	'#collapsed' => TRUE,
299 cd5c298a Geoffroy Desvernay
    '#description' => t('You can add Matomos <a href="!custom_var_documentation">Custom Variables</a> here. These will be added to every page that Matomo 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' => 'https://matomo.org/docs/custom-variables/')),
300 60283730 Assos Assos
    '#theme' => 'matomo_admin_custom_var_table',
301
    '#title' => t('Custom variables'),
302
    '#tree' => TRUE,
303
    '#type' => 'fieldset',
304
  );
305
306
  $matomo_custom_vars = variable_get('matomo_custom_var', array());
307
308
  // Matomo supports up to 5 custom variables.
309
  for ($i = 1; $i < 6; $i++) {
310
    $form['matomo_custom_var']['slots'][$i]['slot'] = array(
311
      '#default_value' => $i,
312
      '#description' => t('Slot number'),
313
      '#disabled' => TRUE,
314
      '#size' => 1,
315
      '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
316
      '#title_display' => 'invisible',
317
      '#type' => 'textfield',
318
    );
319
    $form['matomo_custom_var']['slots'][$i]['name'] = array(
320
      '#default_value' => !empty($matomo_custom_vars['slots'][$i]['name']) ? $matomo_custom_vars['slots'][$i]['name'] : '',
321
      '#description' => t('The custom variable name.'),
322
      '#maxlength' => 100,
323
    	'#size' => 20,
324
      '#title' => t('Custom variable name #@slot', array('@slot' => $i)),
325
      '#title_display' => 'invisible',
326
      '#type' => 'textfield',
327
    );
328
    $form['matomo_custom_var']['slots'][$i]['value'] = array(
329
      '#default_value' => !empty($matomo_custom_vars['slots'][$i]['value']) ? $matomo_custom_vars['slots'][$i]['value'] : '',
330
      '#description' => t('The custom variable value.'),
331
      '#maxlength' => 255,
332
      '#title' => t('Custom variable value #@slot', array('@slot' => $i)),
333
      '#title_display' => 'invisible',
334
      '#type' => 'textfield',
335
      '#element_validate' => array('matomo_token_element_validate'),
336
      '#token_types' => array('node'),
337
    );
338
    if (module_exists('token')) {
339
      $form['matomo_custom_var']['slots'][$i]['value']['#element_validate'][] = 'token_element_validate';
340
    }
341
    $form['matomo_custom_var']['slots'][$i]['scope'] = array(
342
      '#default_value' => !empty($matomo_custom_vars['slots'][$i]['scope']) ? $matomo_custom_vars['slots'][$i]['scope'] : 'visit',
343
      '#description' => t('The scope for the custom variable.'),
344
      '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
345
      '#title_display' => 'invisible',
346
      '#type' => 'select',
347
      '#options' => array(
348
        'visit' => t('Visit'),
349
        'page' => t('Page'),
350
      ),
351
    );
352
  }
353
354
  $form['matomo_custom_var']['matomo_custom_var_description'] = array(
355
    '#type' => 'item',
356
    '#description' => t('You can supplement Matomos\' 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 Matomo\' service.'),
357
  );
358
  $form['matomo_custom_var']['matomo_custom_var_token_tree'] = array(
359
    '#theme' => 'token_tree',
360
    '#token_types' => array('node'),
361
    '#dialog' => TRUE,
362
  );
363
364
  // Advanced feature configurations.
365
  $form['advanced'] = array(
366
    '#type' => 'fieldset',
367
    '#title' => t('Advanced settings'),
368
    '#collapsible' => TRUE,
369
    '#collapsed' => TRUE,
370
  );
371
372
  $form['advanced']['matomo_cache'] = array(
373
    '#type' => 'checkbox',
374
    '#title' => t('Locally cache tracking code file'),
375
    '#description' => t('If checked, the tracking code file is retrieved from your Matomo site and cached locally. It is updated daily to ensure updates to tracking code are reflected in the local copy.'),
376
    '#default_value' => variable_get('matomo_cache', 0),
377
  );
378
379
  // Allow for tracking of the originating node when viewing translation sets.
380
  if (module_exists('translation')) {
381
    $form['advanced']['matomo_translation_set'] = array(
382
      '#type' => 'checkbox',
383
      '#title' => t('Track translation sets as one unit'),
384
      '#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.'),
385
      '#default_value' => variable_get('matomo_translation_set', 0),
386
    );
387
  }
388
389
  // Code snippet settings.
390
  $user_access_add_js_snippets = !user_access('add js snippets for matomo');
391
  $user_access_add_js_snippets_permission_warning = $user_access_add_js_snippets ? ' <em>' . t('This field has been disabled because you do not have sufficient permissions to edit it.') . '</em>' : '';
392
  $form['advanced']['codesnippet'] = array(
393
    '#type' => 'fieldset',
394
    '#title' => t('Custom JavaScript code'),
395
    '#collapsible' => TRUE,
396
    '#collapsed' => TRUE,
397 cd5c298a Geoffroy Desvernay
    '#description' => t('You can add custom Matomo <a href="@snippets">code snippets</a> here. These will be added to every page that Matomo appears on. <strong>Do not include the &lt;script&gt; tags</strong>, and always end your code with a semicolon (;).', array('@snippets' => 'https://matomo.org/docs/javascript-tracking/'))
398 60283730 Assos Assos
  );
399
  $form['advanced']['codesnippet']['matomo_codesnippet_before'] = array(
400
    '#type' => 'textarea',
401
    '#title' => t('Code snippet (before)'),
402
    '#default_value' => variable_get('matomo_codesnippet_before', ''),
403
    '#disabled' => $user_access_add_js_snippets,
404
    '#rows' => 5,
405
    '#description' => t('Code in this textarea will be added <strong>before</strong> _paq.push(["trackPageView"]).')
406
  );
407
  $form['advanced']['codesnippet']['matomo_codesnippet_after'] = array(
408
    '#type' => 'textarea',
409
    '#title' => t('Code snippet (after)'),
410
    '#default_value' => variable_get('matomo_codesnippet_after', ''),
411
    '#disabled' => $user_access_add_js_snippets,
412
    '#rows' => 5,
413
    '#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.')
414
  );
415
416
  $form['advanced']['matomo_js_scope'] = array(
417
    '#type' => 'select',
418
    '#title' => t('JavaScript scope'),
419
    '#description' => t("Matomo recommends adding the tracking code to the header for performance reasons."),
420
    '#options' => array(
421
      'footer' => t('Footer'),
422
      'header' => t('Header'),
423
    ),
424
    '#default_value' => variable_get('matomo_js_scope', 'header'),
425
  );
426
427
  return system_settings_form($form);
428
}
429
430
function matomo_admin_settings_form_validate($form, &$form_state) {
431
  // Custom variables validation.
432
  foreach ($form_state['values']['matomo_custom_var']['slots'] as $custom_var) {
433
    $form_state['values']['matomo_custom_var']['slots'][$custom_var['slot']]['name'] = trim($custom_var['name']);
434
    $form_state['values']['matomo_custom_var']['slots'][$custom_var['slot']]['value'] = trim($custom_var['value']);
435
436
    // Validate empty names/values.
437
    if (empty($custom_var['name']) && !empty($custom_var['value'])) {
438
      form_set_error("matomo_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'])));
439
    }
440
    elseif (!empty($custom_var['name']) && empty($custom_var['value'])) {
441
      form_set_error("matomo_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'])));
442
    }
443
  }
444
445
  // Trim some text area values.
446
  $form_state['values']['matomo_site_id'] = trim($form_state['values']['matomo_site_id']);
447
  $form_state['values']['matomo_pages'] = trim($form_state['values']['matomo_pages']);
448
  $form_state['values']['matomo_codesnippet_before'] = trim($form_state['values']['matomo_codesnippet_before']);
449
  $form_state['values']['matomo_codesnippet_after'] = trim($form_state['values']['matomo_codesnippet_after']);
450
451
  if (!preg_match('/^\d{1,}$/', $form_state['values']['matomo_site_id'])) {
452
    form_set_error('matomo_site_id', t('A valid Matomo site ID is an integer only.'));
453
  }
454
455
  $matomo_url = $form_state['values']['matomo_url_http'];
456
  if ('/' != drupal_substr($matomo_url, -1, 1)) {
457
    $matomo_url = $matomo_url . '/';
458
    $form_state['values']['matomo_url_http'] = $matomo_url;
459
  }
460
  $url = $matomo_url . 'piwik.php';
461
  $result = drupal_http_request($url);
462
  if ($result->code != 200 && $form_state['values']['matomo_url_skiperror'] == FALSE) {
463
    form_set_error('matomo_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)));
464
  }
465
466
  if (!empty($form_state['values']['matomo_url_https'])) {
467
    $matomo_url = $form_state['values']['matomo_url_https'];
468
    if ('/' != drupal_substr($matomo_url, -1, 1)) {
469
      $matomo_url = $matomo_url . '/';
470
      $form_state['values']['matomo_url_https'] = $matomo_url;
471
    }
472
    $url = $matomo_url . 'piwik.php';
473
    $result = drupal_http_request($url);
474
    if ($result->code != 200 && $form_state['values']['matomo_url_skiperror'] == FALSE) {
475
      form_set_error('matomo_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)));
476
    }
477
  }
478
479
  // Delete obsolete local cache file.
480
  if (empty($form_state['values']['matomo_cache']) && $form['advanced']['matomo_cache']['#default_value']) {
481
    matomo_clear_js_cache();
482
  }
483
484
  // This is for the Newbie's who cannot read a text area description.
485
  if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['matomo_codesnippet_before'])) {
486
    form_set_error('matomo_codesnippet_before', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
487
  }
488
  if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['matomo_codesnippet_after'])) {
489
    form_set_error('matomo_codesnippet_after', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
490
  }
491
}
492
493
/**
494
 * Layout for the custom variables table in the admin settings form.
495
 *
496
 * @param array $variables
497
 *   An array contains the form elements.
498
 *
499
 * @return string
500
 *   The rendered output.
501
 */
502
function theme_matomo_admin_custom_var_table($variables) {
503
  $form = $variables['form'];
504
505
  $header = array(
506
    array('data' => t('Slot')),
507
    array('data' => t('Name')),
508
    array('data' => t('Value')),
509
    array('data' => t('Scope')),
510
  );
511
512
  $rows = array();
513
  foreach (element_children($form['slots']) as $key => $id) {
514
    $rows[] = array(
515
      'data' => array(
516
        drupal_render($form['slots'][$id]['slot']),
517
        drupal_render($form['slots'][$id]['name']),
518
        drupal_render($form['slots'][$id]['value']),
519
        drupal_render($form['slots'][$id]['scope']),
520
      ),
521
    );
522
  }
523
524
  $output = theme('table', array('header' => $header, 'rows' => $rows));
525
  $output .= drupal_render($form['matomo_custom_var_description']);
526
  $output .= drupal_render($form['matomo_custom_var_token_tree']);
527
528
  return $output;
529
}
530
531
/**
532
 * Validate a form element that should have tokens in it.
533
 *
534
 * For example:
535
 * @code
536
 * $form['my_node_text_element'] = array(
537
 *   '#type' => 'textfield',
538
 *   '#title' => t('Some text to token-ize that has a node context.'),
539
 *   '#default_value' => 'The title of this node is [node:title].',
540
 *   '#element_validate' => array('matomo_token_element_validate'),
541
 * );
542
 * @endcode
543
 */
544
function matomo_token_element_validate(&$element, &$form_state) {
545
  $value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];
546
547
  if (!drupal_strlen($value)) {
548
    // Empty value needs no further validation since the element should depend
549
    // on using the '#required' FAPI property.
550
    return $element;
551
  }
552
553
  $tokens = token_scan($value);
554
  $invalid_tokens = _matomo_get_forbidden_tokens($tokens);
555
  if ($invalid_tokens) {
556
    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))));
557
  }
558
559
  return $element;
560
}
561
562
/**
563
 * @param array $value
564
 *   An array of token values.
565
 *
566
 * @return array
567
 *   A unique array of invalid tokens.
568
 */
569
function _matomo_get_forbidden_tokens($value) {
570
  $invalid_tokens = array();
571
  $value_tokens = is_string($value) ? token_scan($value) : $value;
572
573
  foreach ($value_tokens as $type => $tokens) {
574
    if (array_filter($tokens, '_matomo_contains_forbidden_token')) {
575
      $invalid_tokens = array_merge($invalid_tokens, array_values($tokens));
576
    }
577
  }
578
579
  array_unique($invalid_tokens);
580
  return $invalid_tokens;
581
}
582
583
/**
584
 * Validate if a string contains forbidden tokens not allowed by privacy rules.
585
 *
586
 * @param string $token_string
587
 *   A string with one or more tokens to be validated.
588
 *
589
 * @return boolean
590
 *   TRUE if blacklisted token has been found, otherwise FALSE.
591
 */
592
function _matomo_contains_forbidden_token($token_string) {
593
  // List of strings in tokens with personal identifying information not allowed
594
  // for privacy reasons. See section 8.1 of the Google Analytics terms of use
595
  // for more detailed information.
596
  //
597
  // This list can never ever be complete. For this reason it tries to use a
598
  // regex and may kill a few other valid tokens, but it's the only way to
599
  // protect users as much as possible from admins with illegal ideas.
600
  //
601
  // User tokens are not prefixed with colon to catch 'current-user' and 'user'.
602
  //
603
  // TODO: If someone have better ideas, share them, please!
604
  $token_blacklist = array(
605
    ':author]',
606
    ':author:edit-url]',
607
    ':author:url]',
608
    ':author:path]',
609
    ':current-user]',
610
    ':current-user:original]',
611
    ':fid]',
612
    ':mail]',
613
    ':name]',
614
    ':uid]',
615
    ':one-time-login-url]',
616
    ':owner]',
617
    ':owner:cancel-url]',
618
    ':owner:edit-url]',
619
    ':owner:url]',
620
    ':owner:path]',
621
    'user:cancel-url]',
622
    'user:edit-url]',
623
    'user:url]',
624
    'user:path]',
625
    'user:picture]',
626
    // addressfield_tokens.module
627
    ':first-name]',
628
    ':last-name]',
629
    ':name-line]',
630
    ':mc-address]',
631
    ':thoroughfare]',
632
    ':premise]',
633
    // realname.module
634
    ':name-raw]',
635
    // token.module
636
    ':ip-address]',
637
  );
638
639
  return preg_match('/' . implode('|', array_map('preg_quote', $token_blacklist)) . '/i', $token_string);
640
}