You are here

function matomo_form_user_form_alter in Matomo Analytics 8

Implements hook_form_FORM_ID_alter().

Allow users to decide if tracking code will be added to pages or not.

File

./matomo.module, line 367
Drupal Module: Matomo.

Code

function matomo_form_user_form_alter(&$form, FormStateInterface $form_state) {
  $config = \Drupal::config('matomo.settings');
  $account = $form_state
    ->getFormObject()
    ->getEntity();
  if ($account
    ->hasPermission('opt-in or out of matomo tracking') && ($visibility_users = $config
    ->get('visibility.user_account_mode')) != 0 && _matomo_visibility_roles($account)) {
    $account_data_matomo = \Drupal::service('user.data')
      ->get('matomo', $account
      ->id());
    $form['matomo'] = [
      '#type' => 'details',
      '#title' => t('Matomo settings'),
      '#weight' => 3,
      '#open' => TRUE,
    ];
    switch ($visibility_users) {
      case 1:
        $description = t('Users are tracked by default, but you are able to opt out.');
        break;
      case 2:
        $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
        break;
    }

    // Disable tracking for visitors who have opted out from tracking via DNT
    // (Do-Not-Track) header.
    $disabled = FALSE;
    if ($config
      ->get('privacy.donottrack') && !empty($_SERVER['HTTP_DNT'])) {
      $disabled = TRUE;

      // Override settings value.
      $account_data_matomo['users'] = FALSE;
      $description .= '<span class="admin-missing">';
      $description .= ' ' . t('You have opted out from tracking via browser privacy settings.');
      $description .= '</span>';
    }

    // Migrate old piwik settings to matomo.
    $account_data_piwik = \Drupal::service('user.data')
      ->get('piwik', $account
      ->id());
    if (isset($account_data_piwik['user_account_users'])) {
      $account_data_matomo['user_account_users'] = $account_data_piwik['user_account_users'];
    }
    $form['matomo']['user_account_users'] = [
      '#type' => 'checkbox',
      '#title' => t('Enable user tracking'),
      '#description' => $description,
      '#default_value' => isset($account_data_matomo['user_account_users']) ? $account_data_matomo['user_account_users'] : $visibility_users == 1,
      '#disabled' => $disabled,
    ];

    // hook_user_update() is missing in D8, add custom submit handler.
    $form['actions']['submit']['#submit'][] = 'matomo_user_profile_form_submit';
  }
}