etracker-8.x-3.x-dev/src/Form/EtrackerAdminSettingsForm.php

src/Form/EtrackerAdminSettingsForm.php
<?php

namespace Drupal\etracker\Form;

use Drupal\Component\Utility\Html;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\etracker\Helper\Constants;
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;

/**
 * Configure eTracker settings for this site.
 */
class EtrackerAdminSettingsForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'etracker_admin_settings';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      Constants::ETRACKER_SETTINGS_CONFIG_NAME,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config(Constants::ETRACKER_SETTINGS_CONFIG_NAME);

    $form['general'] = [
      '#type' => 'details',
      '#title' => $this->t('General settings'),
      '#open' => TRUE,
    ];

    $form['general']['account_key'] = [
      '#type' => 'textfield',
      '#required' => TRUE,
      '#title' => $this->t('eTracker Account Key'),
      '#description' => $this->t('You can find your unique eTracker account key on etracker.com &gt; Settings &gt; Account &gt; <a href="https://newapp.etracker.com/#/report/accountSettings/accountKey">Account-Key</a>.<br/><strong>Please note:</strong> This is <em>NOT</em> your Account-ID, but an alphanumeric mixed-case string used as <code>data-secure-code</code> in your tracking snippet.'),
      '#default_value' => $config->get('account_key'),
    ];

    // Scope.
    $form['general']['etracker_scope_script'] = [
      '#type' => 'radios',
      '#title' => $this->t('Script position'),
      '#options' => [
        Constants::ETRACKER_SCOPE_SCRIPT_HEADER => $this->t('Header') . ' (' . $this->t('recommended') . ')',
        Constants::ETRACKER_SCOPE_SCRIPT_FOOTER => $this->t('Footer'),
      ],
      '#default_value' => $config->get('etracker_scope_script'),
      '#description' => $this->t('The JavaScript is built in a way that it does <strong>not</strong> block or delay the loading of the page.<br/>To support all functionality of eTracker analytics it is required to have the tracking code in the <code>&lt;head&gt;</code> element of the page. Only change this if really needed.'),
    ];

    // Visibility settings.
    $form['tracking_scope'] = [
      '#type' => 'vertical_tabs',
      '#title' => $this->t('Tracking scope'),
      '#attached' => [
        'library' => [
          'etracker/etracker.admin',
        ],
      ],
    ];

    // Pages specific configurations.
    $form['tracking']['pages'] = [
      '#type' => 'details',
      '#title' => $this->t('Pages'),
      '#group' => 'tracking_scope',
    ];

    $form['tracking']['pages']['etracker_track_path_mode'] = [
      '#type' => 'radios',
      '#title' => $this->t('Add tracking to specific pages'),
      '#options' => [
        Constants::ETRACKER_TRACK_PATHS_MODE_ALL => $this->t('Every page except the listed pages'),
        Constants::ETRACKER_TRACK_PATHS_MODE_LISTED => $this->t('The listed pages only'),
      ],
      '#default_value' => $config->get('etracker_track_path_mode'),
    ];
    $form['tracking']['pages']['etracker_track_paths'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Pages'),
      '#title_display' => 'invisible',
      '#default_value' => $config->get('etracker_track_paths'),
      '#description' => $this->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.",
        [
          '%blog' => '/blog',
          '%blog-wildcard' => '/blog/*',
          '%front' => '<front>',
        ]),
      '#rows' => 10,
    ];

    // Roles specific configurations.
    $form['tracking']['roles'] = [
      '#type' => 'details',
      '#title' => $this->t('Roles'),
      '#group' => 'tracking_scope',
    ];

    $form['tracking']['roles']['etracker_track_roles_mode'] = [
      '#type' => 'radios',
      '#title' => $this->t('Add tracking for specific roles'),
      '#options' => [
        Constants::ETRACKER_TRACK_ROLES_MODE_ALL => $this->t('Add to every role except the selected ones'),
        Constants::ETRACKER_TRACK_ROLES_MODE_LISTED => $this->t('Add to the selected roles only'),
      ],
      '#default_value' => $config->get('etracker_track_roles_mode'),
    ];

    $form['tracking']['roles']['etracker_track_roles'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Roles'),
      '#options' => array_map(function (RoleInterface $role) {
        return Html::escape($role->label());
      }, Role::loadMultiple()),
      '#default_value' => $config->get('etracker_track_roles'),
      '#description' => $this->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).'),
    ];

    // Users specific configurations.
    $form['tracking']['users'] = [
      '#type' => 'details',
      '#title' => $this->t('Users'),
      '#group' => 'tracking_scope',
    ];

    $t_permission = ['%permission' => $this->t('opt-in or out of etracker tracking')];
    $form['tracking']['users']['etracker_track_user'] = [
      '#type' => 'radios',
      '#title' => $this->t('Allow users to customize tracking on their account page'),
      '#options' => [
        Constants::ETRACKER_TRACK_USER_NO_CUSTOMIZATION => $this->t('No customization allowed'),
        Constants::ETRACKER_TRACK_USER_TRACKING_ON => $this->t('Tracking on by default, users with %permission permission can opt out',
          $t_permission),
        Constants::ETRACKER_TRACK_USER_TRACKING_OFF => $this->t('Tracking off by default, users with %permission permission can opt in',
          $t_permission),
      ],
      '#default_value' => $config->get('etracker_track_user'),
    ];

    // Breadcrumb specific configurations.
    $form['tracking']['breadcrumb'] = [
      '#type' => 'details',
      '#title' => $this->t('Breadcrumb'),
      '#group' => 'tracking_scope',
    ];

    $form['tracking']['breadcrumb']['etracker_mode_breadcrumb_as_area'] = [
      '#type' => 'radios',
      '#title' => $this->t('Breadcrumb as area'),
      '#default_value' => $config->get('etracker_mode_breadcrumb_as_area'),
      '#description' => $this->t('Select if and how you want to utilize your breadcrumb as an hierarchical area for tracking.<br/>If turned on you can select whether the root of your site will be used as the most top area of the hierarchy or not.'),
      '#options' => [
        Constants::ETRACKER_MODE_BREADCRUMB_OFF => $this->t('Off'),
        Constants::ETRACKER_MODE_BREADCRUMB_ON => $this->t('On'),
        Constants::ETRACKER_MODE_BREADCRUMB_ON_EXCLUDE_HOME => $this->t('On, hide home page from hierarchy'),
      ],
    ];

    // Link specific configurations.
    $form['tracking']['linktracking'] = [
      '#type' => 'details',
      '#title' => $this->t('Links and downloads'),
      '#group' => 'tracking_scope',
    ];

    $event_types = $config->get('event_tracking');
    $form['tracking']['linktracking']['track_mailto'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Track clicks on mailto links'),
      '#default_value' => $event_types['track_mailto'],
    ];

    $form['tracking']['linktracking']['track_external'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Track clicks on outbound links'),
      '#default_value' => $event_types['track_external'],
    ];

    $form['tracking']['linktracking']['track_download'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Track clicks on downloads (clicks on file links) for the following extensions'),
      '#default_value' => $event_types['track_download'],
    ];

    $form['tracking']['linktracking']['track_download_extensions'] = [
      '#type' => 'textfield',
      '#title' => $this->t('List of download file extensions'),
      '#title_display' => 'invisible',
      '#description' => $this->t('A file extension list separated by the whitespace character that will be tracked as download when clicked. For example: @extensions', ['@extensions' => 'pdf doc docx']),
      '#default_value' => $event_types['track_download_extensions'],
      '#states' => [
        'disabled' => [
          'input[name="track_download"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];

    // Message specific configurations.
    $form['tracking']['messagetracking'] = [
      '#type' => 'details',
      '#title' => $this->t('Messages'),
      '#group' => 'tracking_scope',
    ];

    $form['tracking']['messagetracking']['track_system_messages'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Track messages of type'),
      '#description' => $this->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.'),
      '#default_value' => $event_types['track_system_messages'],
      '#options' => [
        'status' => $this->t('Status message'),
        'warning' => $this->t('Warning message'),
        'error' => $this->t('Error message'),
      ],
    ];

    // Privacy specific configurations.
    $form['tracking']['privacy'] = [
      '#type' => 'details',
      '#title' => $this->t('Privacy'),
      '#group' => 'tracking_scope',
    ];

    $script_settings = $config->get('etracker_script_settings');
    $form['tracking']['privacy']['data_respect_dnt'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Universal web tracking opt-out'),
      '#description' => $this->t('If enabled the <a href=":donottrack">Do-Not-Track</a> header is sent by the client browser and the eTracker 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 visitor\'s privacy. If they have opt-out from tracking and advertising, you should accept their personal decision.', [':donottrack' => 'https://www.eff.org/issues/do-not-track']),
      '#default_value' => $script_settings['data_respect_dnt'],
    ];

    $form['tracking']['privacy']['data_block_cookies'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Disable cookies'),
      '#description' => $this->t('eTracker uses <a href=":cookie">cookies</a> to store some information about visitors between visits. Enable to disable all eTracker tracking cookies. When cookies are disabled, some data in eTracker will be <a href=":disablecookies">less accurate</a>.<br />Enable the <em>cookies_etracker</em> submodule for further cookie consent options.', [
        ':cookie' => Url::fromUri('https://en.wikipedia.org/wiki/HTTP_cookie')->toString(),
        ':disablecookies' => Url::fromUri('https://www.etracker.com/cookie-less-etracking/')->toString(),
      ]),

      '#default_value' => $script_settings['data_block_cookies'],
    ];

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);

    // Trim some text area values.
    $form_state->setValue('account_key', trim($form_state->getValue('account_key')));
    $form_state->setValue('etracker_track_paths', trim($form_state->getValue('etracker_track_paths')));
    $form_state->setValue('etracker_track_roles', array_filter($form_state->getValue('etracker_track_roles')));
    $form_state->setValue('track_system_messages', array_filter($form_state->getValue('track_system_messages')));

    if (!preg_match('/^\w{6,}$/', $form_state->getValue('account_key'))) {
      $form_state->setErrorByName('account_key', $this->t('A valid eTracker account key is a six character string.'));
    }

    // Verify that every path is prefixed with a slash,
    // but don't check for slashes if no paths configured.
    if (!empty($form_state->getValue('etracker_track_paths'))) {
      $pages = preg_split('/(\r\n?|\n)/', $form_state->getValue('etracker_track_paths'));
      foreach ($pages as $page) {
        if (strpos($page, '/') !== 0 && $page !== '<front>') {
          $form_state->setErrorByName('etracker_track_paths', $this->t('Path "@page" not prefixed with slash.', ['@page' => $page]));
          // Drupal forms show one error only.
          break;
        }
      }
    }

  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $privacy_settings = [
      'data_block_cookies' => $form_state->getValue('data_block_cookies'),
      'data_respect_dnt' => $form_state->getValue('data_respect_dnt'),
    ];
    $event_tracking = [
      'track_mailto' => $form_state->getValue('track_mailto'),
      'track_download' => $form_state->getValue('track_download'),
      'track_download_extensions' => $form_state->getValue('track_download_extensions'),
      'track_external' => $form_state->getValue('track_external'),
      'track_system_messages' => array_values(array_filter($form_state->getValue('track_system_messages'))),
    ];

    $config = $this->config(Constants::ETRACKER_SETTINGS_CONFIG_NAME);
    $config
      ->set('account_key', $form_state->getValue('account_key'))
      ->set('etracker_scope_script', $form_state->getValue('etracker_scope_script'))
      // Pages.
      ->set('etracker_track_path_mode', $form_state->getValue('etracker_track_path_mode'))
      ->set('etracker_track_paths', $form_state->getValue('etracker_track_paths'))
      // Roles.
      ->set('etracker_track_roles_mode', $form_state->getValue('etracker_track_roles_mode'))
      ->set('etracker_track_roles', array_values(array_filter($form_state->getValue('etracker_track_roles'))))
      // User.
      ->set('etracker_track_user', $form_state->getValue('etracker_track_user'))
      // Breadcrumb.
      ->set('etracker_mode_breadcrumb_as_area', $form_state->getValue('etracker_mode_breadcrumb_as_area'))
      // Privacy.
      ->set('etracker_script_settings', $privacy_settings)
      // Event tracking: Messages, links and downloads.
      ->set('event_tracking', $event_tracking)
      ->save();

    Cache::invalidateTags(['library_info']);

    parent::submitForm($form, $form_state);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc