You are here

class EuCookieComplianceConfigForm in EU Cookie Compliance (GDPR Compliance) 2.0.x

Same name and namespace in other branches
  1. 8 src/Form/EuCookieComplianceConfigForm.php \Drupal\eu_cookie_compliance\Form\EuCookieComplianceConfigForm

Provides settings for eu_cookie_compliance module.

Hierarchy

Expanded class hierarchy of EuCookieComplianceConfigForm

1 string reference to 'EuCookieComplianceConfigForm'
eu_cookie_compliance.routing.yml in ./eu_cookie_compliance.routing.yml
eu_cookie_compliance.routing.yml

File

src/Form/EuCookieComplianceConfigForm.php, line 20

Namespace

Drupal\eu_cookie_compliance\Form
View source
class EuCookieComplianceConfigForm extends ConfigFormBase {
  use StringTranslationTrait;

  /**
   * The role storage.
   *
   * @var \Drupal\user\RoleStorageInterface
   */
  protected $roleStorage;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * Constructs an EuCookieComplianceConfigForm object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\user\RoleStorageInterface $role_storage
   *   The role storage.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   */
  public function __construct(ConfigFactoryInterface $config_factory, RoleStorageInterface $role_storage, ModuleHandlerInterface $module_handler) {
    parent::__construct($config_factory);
    $this->roleStorage = $role_storage;
    $this->moduleHandler = $module_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('entity_type.manager')
      ->getStorage('user_role'), $container
      ->get('module_handler'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() : string {
    return 'eu_cookie_compliance_config_form';
  }

  /**
   * Gets the roles to display in this form.
   *
   * @return \Drupal\Core\Entity\EntityInterface[]
   *   An array of role objects.
   */
  protected function getRoles() : array {
    return $this->roleStorage
      ->loadMultiple();
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() : array {
    return [
      'eu_cookie_compliance.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) : array {
    $config = $this
      ->config('eu_cookie_compliance.settings');
    $consent_storages = \Drupal::service('plugin.manager.eu_cookie_compliance.consent_storage');
    $plugin_definitions = $consent_storages
      ->getDefinitions();
    $consent_storage_options = [];
    $consent_storage_options['do_not_store'] = $this
      ->t('Do not store');
    foreach ($plugin_definitions as $plugin_name => $plugin_definition) {

      /** @var \Drupal\Core\StringTranslation\TranslatableMarkup $plugin_definition_name */
      $plugin_definition_name = $plugin_definition['name'];
      $consent_storage_options[$plugin_name] = $plugin_definition_name
        ->render();
    }

    // List of checkbox values.
    $role_names = [];

    // Permissions per role.
    $role_permissions = [];

    // Which checkboxes should be ticked.
    $role_values = [];
    $perm = 'display eu cookie compliance popup';
    foreach ($this
      ->getRoles() as $role_name => $role) {

      // Exclude Admin roles.

      /** @var \Drupal\user\Entity\Role $role */
      if (!$role
        ->isAdmin()) {
        $role_names[$role_name] = $role
          ->label();

        // Fetch permissions for the roles.
        $role_permissions[$role_name] = $role
          ->getPermissions();

        // Indicate whether the checkbox should be ticked.
        if (in_array($perm, $role_permissions[$role_name])) {
          $role_values[] = $role_name;
        }
      }
    }
    $form['permissions'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Permissions'),
      '#open' => TRUE,
    ];
    $form['permissions']['display_banner_for'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Display the banner for'),
      '#options' => $role_names,
      '#default_value' => $role_values,
    ];
    $form['consent_option'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Consent for processing of personal information'),
      '#open' => TRUE,
    ];
    $form['consent_option']['method'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Consent method'),
      '#options' => [
        'default' => $this
          ->t("Consent by default. Don't provide any option to opt in or out. Cookies are always set."),
        'opt_in' => $this
          ->t("Opt-in (with optional categories). Don't track visitors unless they specifically give consent. (GDPR compliant)"),
        'opt_out' => $this
          ->t('Opt-out (with optional categories). Track visitors by default, unless they choose to opt out.'),
      ],
      '#default_value' => $config
        ->get('method'),
    ];
    if ($this->moduleHandler
      ->moduleExists('smart_ip') || $this->moduleHandler
      ->moduleExists('geoip') || extension_loaded('geoip')) {
      $form['consent_option']['show_only_in_eu_countries'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Only display banner in EU countries.'),
        '#default_value' => $config
          ->get('show_only_in_eu_countries'),
        '#description' => $this
          ->t('The feature is Javascript based and works with Varnish. You can limit the number of countries for which the banner is displayed by checking this option. If you want to provide a list of countries other than current EU countries, you may place an array in <code>$config[\'eu_cookie_compliance.settings\'][\'eu_countries\']</code> in your <code>settings.php</code> file. Using the <a href="https://drupal.org/project/smart_ip">smart_ip</a> module, the <a href="https://drupal.org/project/geoip">geoip</a> module or the <a href="https://www.php.net/manual/en/function.geoip-country-code-by-name.php">geoip_country_code_by_name()</a> PHP function.'),
      ];
      $form['consent_option']['method_for_non_eu_countries'] = [
        '#type' => 'radios',
        '#title' => $this
          ->t('Consent method for non-EU countries'),
        '#options' => [
          'default' => $this
            ->t("Consent by default. Don't provide any option to opt in or out. Cookies are always set."),
          'opt_in' => $this
            ->t("Opt-in (with optional categories). Don't track visitors unless they specifically give consent. (GDPR compliant)"),
          'opt_out' => $this
            ->t('Opt-out (with optional categories). Track visitors by default, unless they choose to opt out.'),
          'no_banner' => $this
            ->t("None. Do not show a banner."),
        ],
        '#default_value' => $config
          ->get('method_for_non_eu_countries'),
      ];
    }
    else {
      $form['consent_option']['info'] = [
        '#markup' => $this
          ->t('You can choose to show the banner only to visitors from EU countries, and also the consent method for visitors from non-EU countries. In order to achieve this, you need to install the <a href="https://drupal.org/project/smart_ip">smart_ip</a> module, the <a href="https://drupal.org/project/geoip">geoip</a> module or enable the <a href="https://www.php.net/manual/en/function.geoip-country-code-by-name.php">geoip_country_code_by_name()</a> PHP function.'),
      ];
    }
    $form['javascripts'] = [
      '#type' => 'details',
      '#title' => $this
        ->t("Disable the following JavaScripts when consent isn't given, or after an opt-out"),
      '#open' => TRUE,
      '#states' => [
        'visible' => [
          "input[name='method']" => [
            '!value' => 'default',
          ],
        ],
      ],
    ];
    $form['javascripts']['disabled_javascripts'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Disable JavaScripts'),
      '#default_value' => $config
        ->get('disabled_javascripts'),
      '#description' => $this
        ->t("<span class='eu-cookie-compliance-word-break'>Include the full path of JavaScripts, each on a separate line. When using the opt-in or opt-out consent options, you can block certain JavaScript files from being loaded when consent isn't given. The on-site JavaScripts should be written as root relative paths <strong>without the leading slash</strong>. You can also use public://path/to/file.js and private://path/to/file.js. Off-site JavaScripts should be written as complete URLs <strong>with the leading http(s)://</strong>. Note that after the user gives consent, the scripts will be executed in the order you enter here.<br /><br />Libraries and scripts that attach to Drupal.behaviors are supported. To indicate a behavior that needs to be loaded on consent, append the behavior name after the script with a | (vertical bar). If you also want to conditionally load a library, place that as the third parameter, following another | (vertical bar). <strong>Example: modules/custom/custom_module/js/custom.js|customModule|custom_module/custom_module</strong> (script url|behavior|library).<br />If your script file does not attach to Drupal.attributes, you may skip the second parameter. <strong>Example: modules/custom/custom_module/js/custom.js||custom_module/custom_module</strong> (script url||library).<br /><strong>Note that Drupal behavior name and library parameters are both optional</strong>, but may be required to achieve your objective.</span>") . '<br /><br />' . $this
        ->t('When using categories, you can link the script to a specific category by using the format: "category:path/to/the/script.js".'),
    ];
    $form['cookies'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Cookie handling'),
      '#open' => TRUE,
      '#states' => [
        'visible' => [
          "input[name='method']" => [
            '!value' => 'default',
          ],
        ],
      ],
    ];
    $form['cookies']['automatic_cookies_removal'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t("Enable cookie(s) automatic-removal when consent isn't given, or after opted out."),
      '#default_value' => $config
        ->get('automatic_cookies_removal'),
    ];
    $form['cookies']['allowed_cookies'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Allowed cookies'),
      '#default_value' => $config
        ->get('allowed_cookies'),
      '#description' => $this
        ->t("Include the name of cookies, each on a separate line. When using the opt-in or opt-out consent options, this module will <strong>delete cookies from your domain that are not allowed</strong> every few seconds when consent isn't given. PHP session cookies and the cookies used to store consent status are always allowed.") . '<br /><br />' . $this
        ->t('When using categories, you can link the cookie to a specific consent category by using the format: "category:cookie_name".  Only when consent is given for the given category, will the cookie be allowed.') . '<br /><br />' . $this
        ->t('Cookie names can contain "*" characters which mean a series of characters.'),
      '#states' => [
        'visible' => [
          'input[name="automatic_cookies_removal"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['consent_storage'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Store record of consent'),
      '#open' => TRUE,
      '#states' => [
        'visible' => [
          "input[name='method']" => [
            '!value' => 'default',
          ],
        ],
      ],
    ];
    $form['consent_storage']['info'] = [
      '#type' => 'markup',
      '#markup' => $this
        ->t('This module comes with a basic consent storage plugin that writes a record to the database on every user consent. Note that if your site has significant traffic, the basic consent storage may become a bottleneck, as every consent action will require a write to the database. You can easily create your own module with a ConsentStorage Plugin that extends ConsentStorageBase, using BasicConsentStorage from this module as a template. If you create a highly performant consent storage plugin, please consider contributing it back to the Drupal community as a contrib module.'),
    ];
    $form['consent_storage']['consent_storage_method'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Consent storage method'),
      '#default_value' => $config
        ->get('consent_storage_method'),
      '#options' => $consent_storage_options,
    ];
    $form['privacy'] = [
      '#type' => 'details',
      '#open' => TRUE,
      '#title' => $this
        ->t('Privacy policy'),
    ];
    $form['privacy']['privacy_policy_link'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Privacy policy link'),
      '#default_value' => $config
        ->get('privacy_policy_link'),
      '#maxlength' => 1024,
      '#required' => TRUE,
      '#description' => $this
        ->t('Enter a link to your privacy policy or other page that contains details on cookies. External links should start with http:// or https://.'),
      '#element_validate' => [
        [
          $this,
          'validatePopupLink',
        ],
      ],
    ];
    $form['privacy']['privacy_policy_version'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Privacy policy version'),
      '#description' => $this
        ->t('Change this value to make the cookie information banner reappear for all visitors. A typical usage of this field is to increase the value when the privacy policy has been changed.'),
      '#default_value' => $config
        ->get('privacy_policy_version') ?: '1.0.0',
      '#required' => TRUE,
    ];
    $form['cookie'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Consent cookie'),
      '#open' => TRUE,
    ];
    $form['cookie']['cookie_name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Cookie name'),
      '#default_value' => $config
        ->get('cookie_name'),
      '#description' => $this
        ->t('Sets the cookie name that is used to check whether the user has agreed or not.'),
    ];
    $form['cookie']['cookie_value_disagreed'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Cookie value (disagreed or opted out)'),
      '#default_value' => $config
        ->get('cookie_value_disagreed'),
      '#description' => $this
        ->t('The cookie value which will be set when the user has disagreed.'),
    ];
    $form['cookie']['cookie_value_agreed'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Cookie value (agreed or opted in)'),
      '#default_value' => $config
        ->get('cookie_value_agreed'),
      '#description' => $this
        ->t('The cookie value which will be set when the user has agreed.'),
    ];
    $form['cookie']['cookie_same_site'] = [
      '#type' => 'radios',
      '#options' => [
        'strict' => 'Strict',
        'lax' => 'Lax',
        'none' => 'None',
      ],
      '#title' => $this
        ->t('Cookie Same-Site value'),
      '#default_value' => $config
        ->get('cookie_same_site'),
    ];
    $form['advanced'] = [
      '#type' => 'details',
      '#open' => FALSE,
      '#title' => $this
        ->t('Advanced'),
    ];
    $form['advanced']['reload_page_on_agree'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Reload page after user clicks the "Agree" button.'),
      '#default_value' => $config
        ->get('reload_page_on_agree'),
    ];
    $form['advanced']['reload_include_or_exclude_list'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Handling of listed routes'),
      '#default_value' => $config
        ->get('reload_include_or_exclude_list'),
      '#options' => [
        'include' => $this
          ->t('Include'),
        'exclude' => $this
          ->t('Exclude'),
      ],
      '#description' => $this
        ->t('Specify if you want to include or exclude the routes listed below for reloading the page after agreeing.'),
      '#states' => [
        'visible' => [
          [
            'input[name="reload_page_on_agree"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
      ],
    ];
    $form['advanced']['reload_routes_list'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Routes list'),
      '#default_value' => $config
        ->get('reload_routes_list'),
      '#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. Leave the list empty to reload all pages. This field does not support url aliases.", [
        '%blog' => '/blog',
        '%blog-wildcard' => '/blog/*',
      ]),
      '#states' => [
        'visible' => [
          [
            'input[name="reload_page_on_agree"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
      ],
    ];
    $form['advanced']['domains_option'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('show/hide banner on specified domains'),
      '#default_value' => $config
        ->get('domains_option'),
      '#options' => [
        'show' => $this
          ->t('Show'),
        'hide' => $this
          ->t('Hide'),
      ],
      '#description' => $this
        ->t('Specify if you want to show or hide the banner on the domains listed below.'),
    ];
    $form['advanced']['domains_list'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Domains list'),
      '#default_value' => $config
        ->get('domains_list'),
      '#description' => $this
        ->t('Specify domains with protocol (e.g., http:// or https://). Enter one domain per line.'),
    ];
    $form['advanced']['exclude_paths'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Exclude paths'),
      '#default_value' => $config
        ->get('exclude_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>',
      ]),
    ];
    $form['advanced']['exclude_admin_role'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t("Don't show the banner for site administrators (including UID 1)."),
      '#default_value' => $config
        ->get('exclude_admin_role'),
    ];
    $form['advanced']['domain'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Domain'),
      '#default_value' => $config
        ->get('domain'),
      '#description' => $this
        ->t('Sets the domain of the cookie to a specific url. Used when you need consistency across domains. Note: Make sure you actually enter a domain that the browser can make use of. For example if your site is accessible at both www.domain.com and domain.com, you will not be able to hide the banner at domain.com if your value for this field is www.domain.com.'),
    ];
    $form['advanced']['set_domain_for_all_sites'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Allow the cookie to be set for all sites on the same domain.'),
      '#default_value' => $config
        ->get('set_domain_for_all_sites'),
      '#description' => $this
        ->t("Sets the path of the cookie to '/' so that the cookie works across all sites on the domain."),
    ];
    $form['advanced']['set_cookie_session_zero_on_disagree'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Set cookie lifetime to 0 if the user clicks the "Decline" or the "Withdraw consent" button.'),
      '#description' => $this
        ->t('Enable this if you want to show the consent banner at every new session until the user clicks the "Agree" button.'),
      '#default_value' => $config
        ->get('set_cookie_session_zero_on_disagree'),
    ];
    $form['advanced']['prompt_on_every_session'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Prompt for consent (from the same user) at every new browser session.'),
      '#description' => $this
        ->t("This sets cookie lifetime to 0, invalidating the cookie at the end of the browser session. To set a cookie lifetime greater than 0, uncheck this option. Note that some users will find this behavior highly annoying, and it's recommended to double-check with the legal advisor whether you really need this option enabled."),
      '#default_value' => $config
        ->get('prompt_on_every_session'),
    ];
    $form['#attached']['library'][] = 'eu_cookie_compliance/admin';
    return parent::buildForm($form, $form_state);
  }

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

    // Validate cookie name against valid characters.
    if (preg_match('/[&\'\\x00-\\x20\\x22\\x28-\\x29\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5d\\x7b\\x7d\\x7f]/', $form_state
      ->getValue('cookie_name'))) {
      $form_state
        ->setErrorByName('cookie_name', $this
        ->t('Invalid cookie name, please remove any special characters and try again.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($form_state
      ->getValue('privacy_policy_link') === '<front>') {
      $this
        ->messenger()
        ->addError($this
        ->t('Your privacy policy link is pointing at the front page. This is the default value after installation, and unless your privacy policy is actually posted at the front page, you will need to create a separate page for the privacy policy and link to that page.'));
    }

    // Save permissions.
    $permission_name = 'display eu cookie compliance popup';
    $readonly_enabled = $this->moduleHandler
      ->moduleExists('config_readonly') && Settings::get('config_readonly');
    $allowlist_patterns = Settings::get('config_readonly_whitelist_patterns');
    foreach ($this
      ->getRoles() as $role_name => $role) {

      /** @var \Drupal\user\Entity\Role $role */
      if (!$role
        ->isAdmin()) {
        $user_settings_allowlisted = !empty($allowlist_patterns) && in_array('user.role.' . $role_name, $allowlist_patterns);
        if (!$readonly_enabled || $readonly_enabled && $user_settings_allowlisted) {
          if (array_key_exists($role_name, $form_state
            ->getValue('see_the_banner')) && $form_state
            ->getValue('see_the_banner')[$role_name]) {
            user_role_grant_permissions($role_name, [
              $permission_name,
            ]);
          }
          else {
            user_role_revoke_permissions($role_name, [
              $permission_name,
            ]);
          }
        }
        else {
          $this
            ->messenger()
            ->addWarning($this
            ->t('The user role permission could not be set because the <code>config_readonly</code> module is enabled. To allow setting of user role permissions, please add <code>user.role.%name</code> to the <code>config_readonly</code> allowlist.', [
            '%name' => $role_name,
          ]));
        }
      }
    }
    $method = $form_state
      ->getValue('method');
    if ($method === 'default') {
      $form_state
        ->setValue('allowed_cookies', '');
      $form_state
        ->setValue('disabled_javascripts', '');
    }

    // Clear cached javascript.
    Cache::invalidateTags([
      'library_info',
    ]);
    $extension_settings_allowlisted = !empty($allowlist_patterns) && in_array('core.extension', $allowlist_patterns);
    if (!$readonly_enabled || $readonly_enabled && $extension_settings_allowlisted) {
      _eu_cookie_compliance_module_set_weight();
    }
    else {
      $this
        ->messenger()
        ->addWarning($this
        ->t('The module weight could not be set because the <code>config_readonly</code> module is enabled. To allow setting of module weight, please add <code>core.extension</code> to the <code>config_readonly</code> allowlist.'));
    }

    // Save settings.
    $this
      ->config('eu_cookie_compliance.settings')
      ->set('method', $form_state
      ->getValue('method'))
      ->set('show_only_in_eu_countries', $form_state
      ->getValue('show_only_in_eu_countries'))
      ->set('method_for_non_eu_countries', $form_state
      ->getValue('method_for_non_eu_countries'))
      ->set('disabled_javascripts', $form_state
      ->getValue('disabled_javascripts'))
      ->set('automatic_cookies_removal', $form_state
      ->getValue('automatic_cookies_removal'))
      ->set('allowed_cookies', $form_state
      ->getValue('allowed_cookies'))
      ->set('consent_storage_method', $form_state
      ->getValue('consent_storage_method'))
      ->set('privacy_policy_link', $form_state
      ->getValue('privacy_policy_link'))
      ->set('privacy_policy_version', $form_state
      ->getValue('privacy_policy_version'))
      ->set('cookie_name', $form_state
      ->getValue('cookie_name'))
      ->set('cookie_value_disagreed', $form_state
      ->getValue('cookie_value_disagreed'))
      ->set('cookie_value_agreed', $form_state
      ->getValue('cookie_value_agreed'))
      ->set('cookie_same_site', $form_state
      ->getValue('cookie_same_site'))
      ->set('reload_page_on_agree', $form_state
      ->getValue('reload_page_on_agree'))
      ->set('reload_include_or_exclude_list', $form_state
      ->getValue('reload_include_or_exclude_list'))
      ->set('reload_routes_list', $form_state
      ->getValue('reload_routes_list'))
      ->set('domains_option', $form_state
      ->getValue('domains_option'))
      ->set('domains_list', $form_state
      ->getValue('domains_list'))
      ->set('exclude_paths', $form_state
      ->getValue('exclude_paths'))
      ->set('exclude_admin_role', $form_state
      ->getValue('exclude_admin_role'))
      ->set('domain', $form_state
      ->getValue('domain'))
      ->set('set_domain_for_all_sites', $form_state
      ->getValue('set_domain_for_all_sites'))
      ->set('set_cookie_session_zero_on_disagree', $form_state
      ->getValue('set_cookie_session_zero_on_disagree'))
      ->set('prompt_on_every_session', $form_state
      ->getValue('prompt_on_every_session'))
      ->save();
    parent::submitForm($form, $form_state);
  }

  /**
   * Validates the banner link field.
   *
   * @param array $element
   *   Element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state.
   */
  public function validatePopupLink(array $element, FormStateInterface &$form_state) {
    if (empty($element['#value'])) {
      return;
    }
    $input = $element['#value'];
    if (UrlHelper::isExternal($input)) {
      $allowed_protocols = [
        'http',
        'https',
      ];
      if (!in_array(parse_url($input, PHP_URL_SCHEME), $allowed_protocols)) {
        $form_state
          ->setError($element, $this
          ->t('Invalid protocol specified for the %name (valid protocols: %protocols).', [
          '%name' => $element['#title'],
          '%protocols' => implode(', ', $allowed_protocols),
        ]));
      }
      else {
        try {
          Url::fromUri($input);
        } catch (\Exception $exc) {
          $form_state
            ->setError($element, $this
            ->t('Invalid %name (:message).', [
            '%name' => $element['#title'],
            ':message' => $exc
              ->getMessage(),
          ]));
        }
      }
    }
    else {

      // Special case for '<front>'.
      if ($input === '<front>') {
        $input = '/';
      }
      try {
        Url::fromUserInput($input);
      } catch (\Exception $exc) {
        $form_state
          ->setError($element, $this
          ->t('Invalid URL in %name field (:message).', [
          '%name' => $element['#title'],
          ':message' => $exc
            ->getMessage(),
        ]));
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
EuCookieComplianceConfigForm::$moduleHandler protected property The module handler.
EuCookieComplianceConfigForm::$roleStorage protected property The role storage.
EuCookieComplianceConfigForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
EuCookieComplianceConfigForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
EuCookieComplianceConfigForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
EuCookieComplianceConfigForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
EuCookieComplianceConfigForm::getRoles protected function Gets the roles to display in this form.
EuCookieComplianceConfigForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
EuCookieComplianceConfigForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
EuCookieComplianceConfigForm::validatePopupLink public function Validates the banner link field.
EuCookieComplianceConfigForm::__construct public function Constructs an EuCookieComplianceConfigForm object. Overrides ConfigFormBase::__construct
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route.
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.