You are here

function piwik_form_user_form_alter in Piwik Web Analytics 8

Implements hook_form_FORM_ID_alter().

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

File

./piwik.module, line 373
Drupal Module: Piwik.

Code

function piwik_form_user_form_alter(&$form, FormStateInterface $form_state) {
  $config = \Drupal::config('piwik.settings');
  $account = $form_state
    ->getFormObject()
    ->getEntity();
  if ($account
    ->hasPermission('opt-in or out of piwik tracking') && ($visibility_users = $config
    ->get('visibility.user_account_mode')) != 0 && _piwik_visibility_roles($account)) {
    $account_data_piwik = \Drupal::service('user.data')
      ->get('piwik', $account
      ->id());
    $form['piwik'] = [
      '#type' => 'details',
      '#title' => t('Piwik 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_piwik['users'] = FALSE;
      $description .= '<span class="admin-missing">';
      $description .= ' ' . t('You have opted out from tracking via browser privacy settings.');
      $description .= '</span>';
    }
    $form['piwik']['user_account_users'] = [
      '#type' => 'checkbox',
      '#title' => t('Enable user tracking'),
      '#description' => $description,
      '#default_value' => isset($account_data_piwik['user_account_users']) ? $account_data_piwik['user_account_users'] : $visibility_users == 1,
      '#disabled' => $disabled,
    ];

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