Coverage index

src/Form/SettingsForm.php

Lines: 92.67%

LineHitsSource
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Drupal\visitors\Form;
6
7
use Drupal\Core\Condition\ConditionManager;
8
use Drupal\Core\Config\Entity\ConfigEntityType;
9
use Drupal\Core\Entity\EntityTypeManagerInterface;
10
use Drupal\Core\Form\ConfigFormBase;
11
use Drupal\Core\Form\FormStateInterface;
12
use Drupal\Core\Form\SubformState;
13
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
14
use Drupal\Core\Url;
15
use Drupal\visitors\VisitorsLocationPluginManager;
16
use Drupal\visitors\VisitorsVisibilityInterface;
17
use Symfony\Component\DependencyInjection\ContainerInterface;
18
19
/**
20
 * Visitors Settings Form.
21
 */
22
final class SettingsForm extends ConfigFormBase {
23
24
  /**
25
   * Visitors settings.
26
   *
27
   * @var string
28
   */
29
  const SETTINGS = 'visitors.settings';
30
31
  /**
32
   * Condition plugins that are not offered for tracking visibility.
33
   *
34
   * The theme condition has no empty option, so saving settings would
35
   * always store a theme and stop tracking on every other theme.
36
   */
37
  private const UNSUPPORTED_VISIBILITY_CONDITIONS = [
38
    'current_theme',
39
  ];
40
41
  /**
42
   * An extension discovery instance.
43
   *
44
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
45
   */
46
  protected EntityTypeManagerInterface $entityTypeManager;
47
48
  /**
49
   * The condition plugin manager.
50
   *
51
   * @var \Drupal\Core\Condition\ConditionManager
52
   */
53
  protected ConditionManager $conditionManager;
54
55
  /**
56
   * The context repository service.
57
   *
58
   * @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
59
   */
60
  protected ContextRepositoryInterface $contextRepository;
61
62
  /**
63
   * The location plugin manager.
64
   *
65
   * @var \Drupal\visitors\VisitorsLocationPluginManager
66
   */
67
  protected VisitorsLocationPluginManager $locationPluginManager;
68
69
  /**
70
   * Constructs a Settings form.
71
   *
72
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
73
   *   The entity type manager.
74
   * @param \Drupal\Core\Condition\ConditionManager $condition_manager
75
   *   The condition plugin manager.
76
   * @param \Drupal\Core\Plugin\Context\ContextRepositoryInterface $context_repository
77
   *   The context repository.
78
   * @param \Drupal\visitors\VisitorsLocationPluginManager $location_plugin_manager
79
   *   The location plugin manager.
80
   */
81
  public function __construct(
82
    EntityTypeManagerInterface $entity_type_manager,
83
    ConditionManager $condition_manager,
84
    ContextRepositoryInterface $context_repository,
85
    VisitorsLocationPluginManager $location_plugin_manager,
86
  ) {
879
    $this->entityTypeManager     = $entity_type_manager;
889
    $this->conditionManager      = $condition_manager;
899
    $this->contextRepository     = $context_repository;
909
    $this->locationPluginManager = $location_plugin_manager;
91
  }
92
93
  /**
94
   * {@inheritdoc}
95
   */
96
  public static function create(ContainerInterface $container) {
979
    return new self(
989
      $container->get('entity_type.manager'),
999
      $container->get('plugin.manager.condition'),
1009
      $container->get('context.repository'),
1019
      $container->get('visitors.location_plugin_manager'),
1029
    );
103
  }
104
105
  /**
106
   * {@inheritdoc}
107
   */
108
  public function getFormId() {
1091
    return 'visitors_admin_settings';
110
  }
111
112
  /**
113
   * {@inheritdoc}
114
   */
115
  protected function getEditableConfigNames() {
1165
    return [
1175
      static::SETTINGS,
1185
    ];
119
  }
120
121
  /**
122
   * {@inheritdoc}
123
   */
124
  public function buildForm(array $form, FormStateInterface $form_state) {
1253
    $settings = $this->config(self::SETTINGS);
1263
    $form = parent::buildForm($form, $form_state);
127
1283
    $form['#attached']['library'][] = 'visitors/visitors.admin';
129
1303
    $form['visitors_disable_tracking'] = [
1313
      '#type' => 'radios',
1323
      '#title' => $this->t('Track visitors'),
1333
      '#options' => [
1343
        $this->t('Enabled'),
1353
        $this->t('Disabled'),
1363
      ],
1373
      '#description' => $this->t('Enable or disable tracking of visitors.'),
1383
      '#default_value' => (int) $settings->get('disable_tracking'),
1393
    ];
140
1413
    $script_type = $settings->get('script_type');
1423
    $form['script_type'] = [
1433
      '#type' => 'radios',
1443
      '#title' => $this->t('Script type'),
1453
      '#options' => [
1463
        'minified' => $this->t('Minified'),
1473
        'full' => $this->t('Full'),
1483
      ],
1493
      '#default_value' => $script_type == 'full' ? 'full' : 'minified',
1503
      '#description' => $this->t('Full script is for debugging purposes. Minified script is for production.'),
1513
    ];
1523
    $form['client_debug'] = [
1533
      '#type' => 'checkbox',
1543
      '#title' => $this->t('Client debug'),
1553
      '#default_value' => $settings->get('client_debug'),
1563
      '#description' => $this->t('Log tracker commands in the browser console. Open the browser developer tools and look at the Console tab.'),
1573
    ];
1583
    $form['scroll_depth'] = [
1593
      '#type' => 'checkbox',
1603
      '#title' => $this->t('Record scroll depth'),
1613
      '#default_value' => (bool) $settings->get('scroll_depth'),
1623
      '#description' => $this->t('Record when a visitor reaches 25%, 50%, 75%, and 100% of the page.'),
1633
    ];
1643
    $form['javascript_errors'] = [
1653
      '#type' => 'radios',
1663
      '#title' => $this->t('JavaScript errors'),
1673
      '#options' => [
1683
        'off' => $this->t('Do not record'),
1693
        'activity' => $this->t('Activity log'),
1703
        'drupal' => $this->t('Drupal log'),
1713
      ],
1723
      '#default_value' => $this->javascriptErrorsMode(
1733
        $settings->get('javascript_errors')
1743
      ),
1753
      '#description' => $this->t('Record uncaught browser errors. Activity log stores them with other events. Drupal log writes them to the Visitors log and does not store them.'),
1763
    ];
1773
    $form['track_downloads'] = [
1783
      '#type' => 'checkbox',
1793
      '#title' => $this->t('Track file downloads'),
1803
      '#default_value' => (bool) ($settings->get('track_downloads') ?? TRUE),
1813
      '#description' => $this->t('Record clicks on file links, such as PDF and ZIP files.'),
1823
    ];
1833
    $form['track_outlinks'] = [
1843
      '#type' => 'checkbox',
1853
      '#title' => $this->t('Track outbound links'),
1863
      '#default_value' => (bool) ($settings->get('track_outlinks') ?? TRUE),
1873
      '#description' => $this->t('Record clicks that leave this site.'),
1883
    ];
1893
    $form['track_media'] = [
1903
      '#type' => 'checkbox',
1913
      '#title' => $this->t('Track audio and video'),
1923
      '#default_value' => (bool) ($settings->get('track_media') ?? TRUE),
1933
      '#description' => $this->t('Record HTML5 audio and video plays, pauses, and how much was heard or watched.'),
1943
    ];
1953
    $form['heartbeat_interval'] = [
1963
      '#type' => 'number',
1973
      '#title' => $this->t('Heartbeat interval'),
1983
      '#field_suffix' => $this->t('seconds'),
1993
      '#description' => $this->t('How often to record that a page is still open. Use 0 to turn this off. Values from 1 to 4 are saved as 5.'),
2003
      '#default_value' => $this->heartbeatIntervalValue($settings->get('heartbeat_interval')),
2013
      '#min' => 0,
2023
      '#step' => 1,
2033
    ];
2043
    $form['site_search'] = [
2053
      '#type' => 'details',
2063
      '#title' => $this->t('Site search'),
2073
      '#open' => FALSE,
2083
    ];
2093
    $form['site_search']['site_search_views'] = [
2103
      '#type' => 'textarea',
2113
      '#title' => $this->t('Views to track as search'),
2123
      '#description' => $this->t('One view per line: view id, display id, and the exposed filter that holds the keyword, separated by |. Core Search and Search API are tracked without a line here. A listed display is a search. An empty keyword is not recorded.'),
2133
      '#default_value' => $this->siteSearchViewsText($settings->get('site_search_views')),
2143
    ];
2153
    $location_options = $this->locationPluginOptions();
2163
    $location_plugin = $settings->get('location_plugin');
2173
    $known_plugin = is_string($location_plugin)
2183
      && isset($location_options[$location_plugin]);
2193
    if (!$known_plugin) {
2203
      $location_plugin = isset($location_options['browser_language'])
2213
        ? 'browser_language'
2220
        : (string) array_key_first($location_options);
223
    }
2243
    $form['location_plugin'] = [
2253
      '#type' => 'radios',
2263
      '#title' => $this->t('Location'),
2273
      '#options' => $location_options,
2283
      '#default_value' => $location_plugin,
2293
      '#description' => $this->t('How to set the visitor country and city. None stores no location. Browser language uses the region in the first Accept-Language value.'),
2303
    ];
231
2323
    $form['user_visibility_settings'] = [
2333
      '#type' => 'markup  ',
2343
      '#markup' => '<h2>' . $this->t('User Settings') . '</h2>',
2353
    ];
236
2373
    $visibility_user_account_mode = $settings->get('visibility.user_account_mode');
238
2393
    $t_permission = ['%permission' => $this->t('opt-out of visitors tracking')];
2403
    $form['user_visibility_settings']['visitors_visibility_user_account_mode'] = [
2413
      '#type' => 'radios',
2423
      '#title' => $this->t('Allow users to customize tracking on their account page'),
2433
      '#options' => [
2443
        VisitorsVisibilityInterface::USER_NO_PERSONALIZATION => $this->t('No customization allowed'),
2453
        VisitorsVisibilityInterface::USER_OPT_OUT => $this->t('Tracking on by default, users with %permission permission can opt out', $t_permission),
2463
        VisitorsVisibilityInterface::USER_OPT_IN => $this->t('Tracking off by default, users with %permission permission can opt in', $t_permission),
2473
      ],
2483
      '#default_value' => !empty($visibility_user_account_mode) ? $visibility_user_account_mode : 0,
2493
    ];
2503
    $form['user_visibility_settings']['visitors_trackuserid'] = [
2513
      '#type' => 'checkbox',
2523
      '#title' => $this->t('Track User ID'),
2533
      '#default_value' => $settings->get('track.userid'),
2543
      '#description' => $this->t('User ID enables the analysis of groups of sessions, across devices, using a unique, persistent, and representing a user. <a href=":url">Learn more about the benefits of using User ID</a>.', [':url' => 'https://matomo.org/docs/user-id/']),
2553
    ];
2563
    $form['user_visibility_settings']['visitors_userid_anonymize'] = [
2573
      '#type' => 'checkbox',
2583
      '#title' => $this->t('Pseudo-anonymize User ID'),
2593
      '#default_value' => $settings->get('track.userid_anonymize') ?? FALSE,
2603
      '#description' => $this->t('Store a stable pseudonym instead of the Drupal user id. The same person keeps the same value. Existing visits are left unchanged.'),
2613
      '#states' => [
2623
        'visible' => [
2633
          ':input[name="visitors_trackuserid"]' => ['checked' => TRUE],
2643
        ],
2653
      ],
2663
    ];
267
2683
    $form['user_visibility_settings']['visibility_exclude_user1'] = [
2693
      '#type' => 'checkbox',
2703
      '#title' => $this->t('Exclude user1 from statistics'),
2713
      '#default_value' => $settings->get('visibility.exclude_user1'),
2723
      '#description' => $this->t('Exclude hits of user1 from statistics.'),
2733
    ];
274
2753
    $form['retention'] = [
2763
      '#type' => 'markup',
2773
      '#markup' => '<h2>' . $this->t('Log Retention') . '</h2>',
2783
    ];
279
2803
    $form['retention']['flush_log_timer'] = [
2813
      '#type' => 'select',
2823
      '#title' => $this->t('Discard visitors logs older than'),
2833
      '#default_value'   => $settings->get('flush_log_timer'),
2843
      '#options' => [
2853
        0 => $this->t('Never'),
2863
        3600 => $this->t('1 hour'),
2873
        10800 => $this->t('3 hours'),
2883
        21600 => $this->t('6 hours'),
2893
        32400 => $this->t('9 hours'),
2903
        43200 => $this->t('12 hours'),
2913
        86400 => $this->t('1 day'),
2923
        172800 => $this->t('2 days'),
2933
        259200 => $this->t('3 days'),
2943
        604800 => $this->t('1 week'),
2953
        1209600 => $this->t('2 weeks'),
2963
        4838400 => $this->t('1 month 3 weeks'),
2973
        9676800 => $this->t('3 months 3 weeks'),
2983
        31536000 => $this->t('1 year'),
2993
        34214400 => $this->t('13 months'),
3003
      ],
3013
      '#description' =>
3023
      $this->t('Older visitors log entries (including referrer statistics) will be automatically discarded. (Requires a correctly configured <a href="@cron">cron maintenance task</a>.)',
3033
          ['@cron' => Url::fromRoute('system.status')->toString()]
3043
      ),
3053
    ];
306
3073
    $form['retention']['bot_retention_log'] = [
3083
      '#type' => 'select',
3093
      '#title' => $this->t('Discard bot logs older than'),
3103
      '#default_value'   => $settings->get('bot_retention_log'),
3113
      '#options' => [
3123
        -1 => $this->t('Do not log'),
3133
        0 => $this->t('Never'),
3143
        3600 => $this->t('1 hour'),
3153
        10800 => $this->t('3 hours'),
3163
        21600 => $this->t('6 hours'),
3173
        32400 => $this->t('9 hours'),
3183
        43200 => $this->t('12 hours'),
3193
        86400 => $this->t('1 day'),
3203
        172800 => $this->t('2 days'),
3213
        259200 => $this->t('3 days'),
3223
        604800 => $this->t('1 week'),
3233
        1209600 => $this->t('2 weeks'),
3243
        4838400 => $this->t('1 month 3 weeks'),
3253
        9676800 => $this->t('3 months 3 weeks'),
3263
        31536000 => $this->t('1 year'),
3273
        34214400 => $this->t('13 months'),
3283
      ],
3293
      '#description' =>
3303
      $this->t('Control how long or if visits by bots are logged.'),
3313
    ];
332
3333
    $form['privacy'] = [
3343
      '#type' => 'markup',
3353
      '#markup' => '<h2>' . $this->t('Privacy') . '</h2>',
3363
    ];
337
3383
    $form['privacy']['ip_anonymize'] = [
3393
      '#type' => 'checkbox',
3403
      '#title' => $this->t('Anonymize visitor IP addresses'),
3413
      '#default_value' => $settings->get('ip_anonymize') ?? FALSE,
3423
      '#description' => $this->t('Store a masked IP address instead of the full address. Existing visits are left unchanged.'),
3433
    ];
344
3453
    $form['privacy']['ip_mask_length'] = [
3463
      '#type' => 'radios',
3473
      '#title' => $this->t('How much of the IP address to remove'),
3483
      '#options' => [
3493
        1 => $this->t('1 octet — 192.168.100.0 (IPv6 /64)'),
3503
        2 => $this->t('2 octets — 192.168.0.0 (IPv6 /48)'),
3513
        3 => $this->t('3 octets — 192.0.0.0 (IPv6 /32)'),
3523
      ],
3533
      '#default_value' => (int) ($settings->get('ip_mask_length') ?? 1),
3543
      '#description' => $this->t('Location is looked up from the stored address, so city precision drops as more of the address is removed.'),
3553
      '#states' => [
3563
        'visible' => [
3573
          ':input[name="ip_anonymize"]' => ['checked' => TRUE],
3583
        ],
3593
      ],
3603
    ];
3613
    $form['privacy']['honor_do_not_track'] = [
3623
      '#type' => 'checkbox',
3633
      '#title' => $this->t('Honor Do Not Track'),
3643
      '#default_value' => $settings->get('honor_do_not_track') ?? FALSE,
3653
      '#description' => $this->t('Ignore a tracking hit when the browser sends DNT or X-Do-Not-Track.'),
3663
    ];
3673
    $form['privacy']['cookies'] = [
3683
      '#type' => 'checkbox',
3693
      '#title' => $this->t('Use analytics cookies'),
3703
      '#default_value' => $settings->get('cookies') ?? FALSE,
3713
      '#description' => $this->t('Off by default. Without cookies, an open visit is matched by browser fingerprint and IP, so people who share a browser and network can be counted as one visitor. IP anonymization makes that fingerprint weaker.'),
3723
    ];
373
3743
    $form['entity'] = [
3753
      '#type' => 'markup',
3763
      '#markup' => '<h2>' . $this->t('Entity Views Counter') . '</h2>',
3773
    ];
378
3793
    $form['entity']['counter_enabled'] = [
3803
      '#type' => 'checkbox',
3813
      '#title' => $this->t('Count entity views'),
3823
      '#default_value' => $settings->get('counter.enabled'),
3833
      '#description' => $this->t('Count the number of times entities are viewed.'),
3843
    ];
3853
    $form['entity']['entity_types'] = [
3863
      '#type' => 'checkboxes',
3873
      '#title' => $this->t('Entity Types'),
3883
      '#options' => $this->entityTypes(),
3893
      '#default_value' => $settings->get('counter.entity_types') ?? [],
3903
      '#description' => $this->t('Which entity types should be tracked.'),
3913
    ];
392
393
    // Build condition-based visibility UI.
3943
    $this->buildVisibilityConditions($form, $form_state, $settings);
395
3963
    return $form;
397
  }
398
399
  /**
400
   * {@inheritdoc}
401
   */
402
  public function validateForm(array &$form, FormStateInterface $form_state): void {
4031
    parent::validateForm($form, $form_state);
404
4051
    $mask_length = (int) $form_state->getValue('ip_mask_length');
4061
    if (!in_array($mask_length, [1, 2, 3], TRUE)) {
4070
      $form_state->setErrorByName('ip_mask_length', $this->t('Choose 1, 2, or 3 octets to remove.'));
408
    }
409
4101
    $interval = (int) $form_state->getValue('heartbeat_interval');
4111
    if ($interval < 0) {
4120
      $form_state->setErrorByName('heartbeat_interval', $this->t('The heartbeat interval cannot be negative.'));
413
    }
4141
    elseif ($interval > 0 && $interval < 5) {
4150
      $form_state->setValue('heartbeat_interval', 5);
416
    }
417
4181
    $location_plugin = (string) $form_state->getValue('location_plugin');
4191
    if (!array_key_exists($location_plugin, $this->locationPluginOptions())) {
4200
      $form_state->setErrorByName('location_plugin', $this->t('Choose a location plugin.'));
421
    }
422
4231
    $site_search = (string) $form_state->getValue('site_search_views');
4241
    foreach ($this->siteSearchViewLines($site_search) as $line) {
4250
      $parts = array_map('trim', explode('|', $line));
4260
      $complete = count($parts) === 3 && !in_array('', $parts, TRUE);
4270
      if (!$complete) {
4280
        $form_state->setErrorByName('site_search_views', $this->t('Each line needs a view id, a display id, and a keyword parameter, separated by |.'));
429
        break;
430
      }
431
    }
432
433
    // Validate visibility condition settings.
4341
    foreach ($form_state->getValue('visibility') as $condition_id => $condition_values) {
4351
      if ($this->isUnsupportedVisibilityCondition($condition_id)) {
436
        continue;
437
      }
438
      // Get the condition plugin instance.
4391
      $condition = $form_state->get(['conditions', $condition_id]);
440
      // Validate the condition configuration.
4411
      $condition->validateConfigurationForm(
4421
        $form['visibility'][$condition_id],
4431
        SubformState::createForSubform($form['visibility'][$condition_id], $form, $form_state)
4441
      );
445
    }
446
  }
447
448
  /**
449
   * {@inheritdoc}
450
   */
451
  public function submitForm(array &$form, FormStateInterface $form_state): void {
4522
    $settings = $this->config(self::SETTINGS);
4532
    $values = $form_state->getValues();
454
455
    // Process tracking conditions.
4562
    $tracking_conditions = [];
4572
    foreach ($form_state->getValue('visibility') as $condition_id => $condition_values) {
4581
      if ($this->isUnsupportedVisibilityCondition($condition_id)) {
459
        continue;
460
      }
461
      // Get the condition plugin instance.
4621
      $condition = $form_state->get(['conditions', $condition_id]);
463
      // Submit the condition configuration.
4641
      $condition->submitConfigurationForm(
4651
        $form['visibility'][$condition_id],
4661
        SubformState::createForSubform($form['visibility'][$condition_id], $form, $form_state)
4671
      );
468
      // Store the configuration.
4691
      $tracking_conditions[$condition_id] = $condition->getConfiguration();
470
    }
471
4722
    $settings
4732
      ->set('flush_log_timer', $values['flush_log_timer'])
4742
      ->set('bot_retention_log', $values['bot_retention_log'])
4752
      ->set('track.userid', (bool) ($values['visitors_trackuserid'] ?? FALSE))
4762
      ->set('track.userid_anonymize', (bool) ($values['visitors_userid_anonymize'] ?? FALSE))
4772
      ->set('counter.enabled', $values['counter_enabled'])
4782
      ->set('counter.entity_types', array_filter($values['entity_types'] ?? []))
4792
      ->set('disable_tracking', $values['visitors_disable_tracking'])
4802
      ->set('visibility.user_account_mode', $values['visitors_visibility_user_account_mode'])
4812
      ->set('visibility.exclude_user1', (bool) ($values['visibility_exclude_user1'] ?? FALSE))
4822
      ->set('script_type', $values['script_type'] ?? 'minified')
4832
      ->set('client_debug', (bool) ($values['client_debug'] ?? FALSE))
4842
      ->set('scroll_depth', (bool) ($values['scroll_depth'] ?? FALSE))
4852
      ->set('javascript_errors', $this->javascriptErrorsMode($values['javascript_errors'] ?? 'off'))
4862
      ->set('track_downloads', (bool) ($values['track_downloads'] ?? FALSE))
4872
      ->set('track_outlinks', (bool) ($values['track_outlinks'] ?? FALSE))
4882
      ->set('track_media', (bool) ($values['track_media'] ?? FALSE))
4892
      ->set('heartbeat_interval', $this->heartbeatIntervalValue($values['heartbeat_interval'] ?? NULL))
4902
      ->set('ip_anonymize', (bool) ($values['ip_anonymize'] ?? FALSE))
4912
      ->set('ip_mask_length', (int) ($values['ip_mask_length'] ?? 1))
4922
      ->set('honor_do_not_track', (bool) ($values['honor_do_not_track'] ?? FALSE))
4932
      ->set('cookies', (bool) ($values['cookies'] ?? FALSE))
4942
      ->set('site_search_views', $this->siteSearchViewsConfig((string) ($values['site_search_views'] ?? '')))
4952
      ->set('location_plugin', (string) ($values['location_plugin'] ?? 'browser_language'))
4962
      ->set('tracking_conditions', $tracking_conditions)
4972
      ->save();
498
4992
    parent::submitForm($form, $form_state);
500
  }
501
502
  /**
503
   * Location plugins, ordered by weight.
504
   *
505
   * @return array
506
   *   Plugin labels keyed by plugin id.
507
   */
508
  protected function locationPluginOptions(): array {
5094
    $definitions = $this->locationPluginManager->getDefinitions();
5104
    uasort($definitions, static function (array $left, array $right): int {
5114
      return ($left['weight'] ?? 0) <=> ($right['weight'] ?? 0);
5124
    });
5134
    $options = [];
5144
    foreach ($definitions as $id => $definition) {
5154
      $options[$id] = $definition['label'] ?? $id;
516
    }
5174
    return $options;
518
  }
519
520
  /**
521
   * Helper function for building the visibility UI form.
522
   *
523
   * @param array $form
524
   *   An associative array containing the structure of the form.
525
   * @param \Drupal\Core\Form\FormStateInterface $form_state
526
   *   The current state of the form.
527
   * @param \Drupal\Core\Config\ImmutableConfig $settings
528
   *   The configuration object.
529
   *
530
   * @return array
531
   *   The form array with the visibility UI added in.
532
   */
533
  protected function buildVisibilityConditions(array &$form, FormStateInterface $form_state, $settings): array {
5343
    $form['visibility_tabs'] = [
5353
      '#type' => 'vertical_tabs',
5363
      '#title' => $this->t('Visibility'),
5373
      '#title_display' => 'invisible',
5383
      '#parents' => ['visibility_tabs'],
5393
      '#group' => 'visibility_tabs',
5403
    ];
541
542
    // Get current tracking conditions.
5433
    $tracking_conditions = $settings->get('tracking_conditions') ?: [];
544
545
    // Get available contexts for condition plugins.
5463
    $contexts = $this->contextRepository->getAvailableContexts();
5473
    $form_state->setTemporaryValue('gathered_contexts', $contexts);
548
549
    // Initialize visibility container.
5503
    $form['visibility'] = [
5513
      '#type' => 'container',
5523
      '#tree' => TRUE,
5533
    ];
554
5553
    $excluded_conditions = $settings->get('excluded_conditions') ?: [];
5563
    $excluded_conditions = array_merge(
5573
      $excluded_conditions,
5583
      self::UNSUPPORTED_VISIBILITY_CONDITIONS,
5593
    );
560
    // Get all available condition plugin definitions.
5613
    $all_definitions = $this->conditionManager->getDefinitions();
5623
    $definitions = array_diff_key($all_definitions, array_flip($excluded_conditions));
5633
    foreach ($definitions as $condition_id => $definition) {
564
      // Get existing condition configuration or create new instance.
5651
      $condition_config = $tracking_conditions[$condition_id] ?? ['id' => $condition_id];
5661
      $condition = $this->conditionManager->createInstance(
5671
        $condition_id,
5681
        $condition_config
5691
      );
570
571
      // Store condition for validation and submission.
5721
      $form_state->set(['conditions', $condition_id], $condition);
573
574
      // Build condition form.
5751
      $condition_form = $condition->buildConfigurationForm([], $form_state);
5761
      $condition_form['#type'] = 'details';
5771
      $condition_form['#title'] = $definition['label'];
5781
      $condition_form['#group'] = 'visibility_tabs';
579
5801
      $form['visibility'][$condition_id] = $condition_form;
581
    }
582
5833
    return $form;
584
  }
585
586
  /**
587
   * Returns a list of entity types.
588
   */
589
  protected function entityTypes() {
5903
    $entity_types_list = [];
5913
    $entity_definitions = $this->entityTypeManager->getDefinitions();
5923
    foreach ($entity_definitions as $entity_name => $entity_definition) {
5933
      if ($entity_definition instanceof ConfigEntityType) {
594
        continue;
595
      }
5963
      $entity_types_list[$entity_name] = (string) $entity_definition->getLabel();
597
    }
5983
    asort($entity_types_list);
599
6003
    return $entity_types_list;
601
  }
602
603
  /**
604
   * Normalizes the JavaScript errors setting.
605
   *
606
   * A missing or unknown value does not record errors.
607
   *
608
   * @param mixed $value
609
   *   The stored or submitted value.
610
   *
611
   * @return string
612
   *   off, activity, or drupal.
613
   */
614
  protected function javascriptErrorsMode(mixed $value): string {
6155
    if (in_array($value, ['off', 'activity', 'drupal'], TRUE)) {
6162
      return $value;
617
    }
6183
    return 'off';
619
  }
620
621
  /**
622
   * Normalizes the heartbeat interval.
623
   *
624
   * A missing value is 15 seconds. Zero turns the heartbeat off.
625
   * The tracker will not use a delay below 5 seconds.
626
   *
627
   * @param mixed $value
628
   *   The stored or submitted value.
629
   *
630
   * @return int
631
   *   The interval in seconds.
632
   */
633
  protected function heartbeatIntervalValue(mixed $value): int {
6345
    if ($value === NULL || $value === '') {
6355
      return 15;
636
    }
6370
    $interval = (int) $value;
6380
    if ($interval <= 0) {
6390
      return 0;
640
    }
6410
    return max(5, $interval);
642
  }
643
644
  /**
645
   * Whether a condition plugin is not used for tracking visibility.
646
   *
647
   * @param string $condition_id
648
   *   The condition plugin id.
649
   *
650
   * @return bool
651
   *   TRUE when the condition must be ignored.
652
   */
653
  private function isUnsupportedVisibilityCondition(string $condition_id): bool {
6542
    return in_array(
6552
      $condition_id,
6562
      self::UNSUPPORTED_VISIBILITY_CONDITIONS,
6572
      TRUE,
6582
    );
659
  }
660
661
  /**
662
   * Textarea value for the opted-in view displays.
663
   *
664
   * @param mixed $views
665
   *   The stored site_search_views value.
666
   *
667
   * @return string
668
   *   One view|display|keyword line per display.
669
   */
670
  private function siteSearchViewsText(mixed $views): string {
6713
    if (!is_array($views)) {
6723
      return '';
673
    }
6740
    $lines = [];
6750
    foreach ($views as $view) {
6760
      if (!is_array($view)) {
677
        continue;
678
      }
6790
      $id = trim((string) ($view['view'] ?? ''));
6800
      $display = trim((string) ($view['display'] ?? ''));
6810
      $keyword = trim((string) ($view['keyword'] ?? ''));
6820
      if ($id === '' || $display === '' || $keyword === '') {
683
        continue;
684
      }
6850
      $lines[] = $id . '|' . $display . '|' . $keyword;
686
    }
6870
    return implode("\n", $lines);
688
  }
689
690
  /**
691
   * Non-empty lines from the site search textarea.
692
   *
693
   * @param string $text
694
   *   The submitted textarea.
695
   *
696
   * @return string[]
697
   *   The trimmed lines.
698
   */
699
  private function siteSearchViewLines(string $text): array {
7003
    $lines = preg_split('/\r\n|\r|\n/', $text);
7013
    if ($lines === FALSE) {
7020
      return [];
703
    }
7043
    $kept = [];
7053
    foreach ($lines as $line) {
7063
      $line = trim($line);
7073
      if ($line !== '') {
7080
        $kept[] = $line;
709
      }
710
    }
7113
    return $kept;
712
  }
713
714
  /**
715
   * Config value for the opted-in view displays.
716
   *
717
   * @param string $text
718
   *   The submitted textarea.
719
   *
720
   * @return array<int, array<string, string>>
721
   *   View, display, and keyword rows.
722
   */
723
  private function siteSearchViewsConfig(string $text): array {
7242
    $views = [];
7252
    foreach ($this->siteSearchViewLines($text) as $line) {
7260
      $parts = array_map('trim', explode('|', $line));
7270
      if (count($parts) !== 3 || in_array('', $parts, TRUE)) {
728
        continue;
729
      }
7300
      $views[] = [
7310
        'view' => $parts[0],
7320
        'display' => $parts[1],
7330
        'keyword' => $parts[2],
7340
      ];
735
    }
7362
    return $views;
737
  }
738
739
}