You are here

class SettingsForm in Security Review 8

Settings page for Security Review.

Hierarchy

Expanded class hierarchy of SettingsForm

1 string reference to 'SettingsForm'
security_review.routing.yml in ./security_review.routing.yml
security_review.routing.yml

File

src/Form/SettingsForm.php, line 18

Namespace

Drupal\security_review\Form
View source
class SettingsForm extends ConfigFormBase {

  /**
   * The security_review.checklist service.
   *
   * @var \Drupal\security_review\Checklist
   */
  protected $checklist;

  /**
   * The security_review.security service.
   *
   * @var \Drupal\security_review\Security
   */
  protected $security;

  /**
   * The security_review service.
   *
   * @var \Drupal\security_review\SecurityReview
   */
  protected $securityReview;

  /**
   * The date.formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  private $dateFormatter;

  /**
   * Constructs a SettingsForm.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\security_review\Checklist $checklist
   *   The security_review.checklist service.
   * @param \Drupal\security_review\Security $security
   *   The security_review.security service.
   * @param \Drupal\security_review\SecurityReview $security_review
   *   The security_review service.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $dateFormatter
   *   The date.formatter service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, Checklist $checklist, Security $security, SecurityReview $security_review, DateFormatterInterface $dateFormatter) {
    parent::__construct($config_factory);
    $this->checklist = $checklist;
    $this->security = $security;
    $this->securityReview = $security_review;
    $this->dateFormatter = $dateFormatter;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('security_review.checklist'), $container
      ->get('security_review.security'), $container
      ->get('security_review'), $container
      ->get('date.formatter'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'security-review-settings';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // Get the list of checks.
    $checks = $this->checklist
      ->getChecks();

    // Get the user roles.
    $roles = user_roles();
    $options = [];
    foreach ($roles as $rid => $role) {
      $options[$rid] = $role
        ->label();
    }

    // Notify the user if anonymous users can create accounts.
    $message = '';
    if (in_array(AccountInterface::AUTHENTICATED_ROLE, $this->security
      ->defaultUntrustedRoles())) {
      $message = $this
        ->t('You have allowed anonymous users to create accounts without approval so the authenticated role defaults to untrusted.');
    }

    // Show the untrusted roles form element.
    $form['untrusted_roles'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Untrusted roles'),
      '#description' => $this
        ->t('Define which roles are for less trusted users. The anonymous role defaults to untrusted. @message Most Security Review checks look for resources usable by untrusted roles.', [
        '@message' => $message,
      ]),
      '#options' => $options,
      '#default_value' => $this->security
        ->untrustedRoles(),
    ];
    $form['advanced'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Advanced'),
      '#open' => TRUE,
    ];

    // Show the logging setting.
    $form['advanced']['logging'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Log checklist results and skips'),
      '#description' => $this
        ->t('The result of each check and skip can be logged to watchdog for tracking.'),
      '#default_value' => $this->securityReview
        ->isLogging(),
    ];

    // Skipped checks.
    $values = [];
    $options = [];
    foreach ($checks as $check) {

      // Determine if check is being skipped.
      if ($check
        ->isSkipped()) {
        $values[] = $check
          ->id();
        $label = $this
          ->t('@name <em>skipped by UID @uid on @date</em>', [
          '@name' => $check
            ->getTitle(),
          '@uid' => $check
            ->skippedBy()
            ->id(),
          '@date' => $this->dateFormatter
            ->format($check
            ->skippedOn()),
        ]);
      }
      else {
        $label = $check
          ->getTitle();
      }
      $options[$check
        ->id()] = $label;
    }
    $form['advanced']['skip'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Checks to skip'),
      '#description' => $this
        ->t('Skip running certain checks. This can also be set on the <em>Run & review</em> page. It is recommended that you do not skip any checks unless you know the result is wrong or the process times out while running.'),
      '#options' => $options,
      '#default_value' => $values,
    ];

    // Iterate through checklist and get check-specific setting pages.
    foreach ($checks as $check) {

      // Get the check's setting form.
      $check_form = $check
        ->settings()
        ->buildForm();

      // If not empty, add it to the form.
      if (!empty($check_form)) {

        // If this is the first non-empty setting page initialize the 'details'
        if (!isset($form['advanced']['check_specific'])) {
          $form['advanced']['check_specific'] = [
            '#type' => 'details',
            '#title' => $this
              ->t('Check-specific settings'),
            '#open' => FALSE,
            '#tree' => TRUE,
          ];
        }

        // Add the form.
        $sub_form =& $form['advanced']['check_specific'][$check
          ->id()];
        $title = $check
          ->getTitle();

        // If it's an external check, show its namespace.
        if ($check
          ->getMachineNamespace() != 'security_review') {
          $title .= $this
            ->t('%namespace', [
            '%namespace' => $check
              ->getNamespace(),
          ]);
        }
        $sub_form = [
          '#type' => 'details',
          '#title' => $title,
          '#open' => TRUE,
          '#tree' => TRUE,
          'form' => $check_form,
        ];
      }
    }

    // Return the finished form.
    return parent::buildForm($form, $form_state);
  }

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

    // Run validation for check-specific settings.
    if (isset($form['advanced']['check_specific'])) {
      $check_specific_values = $form_state
        ->getValue('check_specific');
      foreach ($this->checklist
        ->getChecks() as $check) {
        $check_form =& $form['advanced']['check_specific'][$check
          ->id()];
        if (isset($check_form)) {
          $check
            ->settings()
            ->validateForm($check_form, $check_specific_values[$check
            ->id()]);
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Frequently used configuration items.
    $check_settings = $this
      ->config('security_review.checks');

    // Save that the module has been configured.
    $this->securityReview
      ->setConfigured(TRUE);

    // Save the new untrusted roles.
    $untrusted_roles = array_keys(array_filter($form_state
      ->getValue('untrusted_roles')));
    $this->securityReview
      ->setUntrustedRoles($untrusted_roles);

    // Save the new logging setting.
    $logging = $form_state
      ->getValue('logging') == 1;
    $this->securityReview
      ->setLogging($logging);

    // Skip selected checks.
    $skipped = array_keys(array_filter($form_state
      ->getValue('skip')));
    foreach ($this->checklist
      ->getChecks() as $check) {
      if (in_array($check
        ->id(), $skipped)) {
        $check
          ->skip();
      }
      else {
        $check
          ->enable();
      }
    }

    // Save the check-specific settings.
    if (isset($form['advanced']['check_specific'])) {
      $check_specific_values = $form_state
        ->getValue('check_specific');
      foreach ($check_specific_values as $id => $values) {

        // Get corresponding Check.
        $check = $this->checklist
          ->getCheckById($id);

        // Submit parameters.
        $check_form =& $form['advanced']['check_specific'][$id]['form'];
        $check_form_values = $check_specific_values[$id]['form'];

        // Submit.
        $check
          ->settings()
          ->submitForm($check_form, $check_form_values);
      }
    }

    // Commit the settings.
    $check_settings
      ->save();

    // Finish submitting the form.
    parent::submitForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'security_review.checks',
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
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. 1
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. Overrides UrlGeneratorTrait::redirect
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.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
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. 29
MessengerTrait::messenger public function Gets the messenger. 29
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.
SettingsForm::$checklist protected property The security_review.checklist service.
SettingsForm::$dateFormatter private property The date.formatter service.
SettingsForm::$security protected property The security_review.security service.
SettingsForm::$securityReview protected property The security_review service.
SettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
SettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
SettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
SettingsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
SettingsForm::__construct public function Constructs a SettingsForm. Overrides ConfigFormBase::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.