You are here

class ContentAccessAdminSettingsForm in Content Access 8

Node Access settings form.

Hierarchy

Expanded class hierarchy of ContentAccessAdminSettingsForm

1 string reference to 'ContentAccessAdminSettingsForm'
content_access.routing.yml in ./content_access.routing.yml
content_access.routing.yml

File

src/Form/ContentAccessAdminSettingsForm.php, line 15

Namespace

Drupal\content_access\Form
View source
class ContentAccessAdminSettingsForm extends FormBase {
  use ContentAccessRoleBasedFormTrait;

  /**
   * The permission handler.
   *
   * @var \Drupal\user\PermissionHandlerInterface
   */
  protected $permissionHandler;

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

  /**
   * Constructs a new ContentAccessAdminSettingsForm.
   *
   * @param \Drupal\user\PermissionHandlerInterface $permission_handler
   *   The permission handler.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   */
  public function __construct(PermissionHandlerInterface $permission_handler, ModuleHandlerInterface $module_handler) {
    $this->permissionHandler = $permission_handler;
    $this->moduleHandler = $module_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('user.permissions'), $container
      ->get('module_handler'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $node_type = NULL) {
    $storage = [
      'node_type' => $node_type,
    ];
    $form_state
      ->setStorage($storage);

    // Add role based per content type settings.
    $defaults = [];
    foreach (_content_access_get_operations() as $op => $label) {
      $defaults[$op] = content_access_get_settings($op, $node_type);
    }
    $this
      ->roleBasedForm($form, $defaults, $node_type);

    // Per node:
    $form['node'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Per content node access control settings'),
      '#collapsible' => TRUE,
      '#description' => $this
        ->t('Optionally you can enable per content node access control settings. If enabled, a new tab for the content access settings appears when viewing content. You have to configure permission to access these settings at the <a href=":url">permissions</a> page.', [
        ':url' => Url::fromRoute('user.admin_permissions')
          ->toString(),
      ]),
    ];
    $form['node']['per_node'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enable per content node access control settings'),
      '#default_value' => content_access_get_settings('per_node', $node_type),
    ];
    $form['advanced'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Advanced'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    ];
    $form['advanced']['priority'] = [
      '#type' => 'weight',
      '#title' => $this
        ->t('Give content node grants priority'),
      '#default_value' => content_access_get_settings('priority', $node_type),
      '#description' => $this
        ->t('If you are only using this access control module, you can safely ignore this. If you are using multiple access control modules you can adjust the priority of this module.'),
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
      '#weight' => 10,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $storage = $form_state
      ->getStorage();
    $roles = array_keys(user_roles());
    $roles_permissions = user_role_permissions($roles);
    $permissions = $this->permissionHandler
      ->getPermissions();
    $node_type = $storage['node_type'];

    // Remove disabled modules permissions, so they can't raise exception
    // in ::savePermissions().
    foreach ($roles_permissions as $rid => $role_permissions) {
      foreach ($role_permissions as $permission => $value) {
        if (!array_key_exists($permission, $permissions)) {
          unset($roles_permissions[$rid][$permission]);
        }
      }
    }
    foreach ([
      'update',
      'update_own',
      'delete',
      'delete_own',
    ] as $op) {
      foreach ($values[$op] as $rid => $value) {
        $permission = content_access_get_permission_by_op($op, $node_type);
        if ($value) {
          $roles_permissions[$rid][$permission] = TRUE;
        }
        else {
          $roles_permissions[$rid][$permission] = FALSE;
        }
      }

      // Don't save the setting, so its default value (get permission) is
      // applied always.
      unset($values[$op]);
    }
    $this
      ->savePermissions($roles_permissions);

    // Update content access settings.
    $settings = content_access_get_settings('all', $node_type);
    foreach (content_access_available_settings() as $setting) {
      if (isset($values[$setting])) {
        $settings[$setting] = is_array($values[$setting]) ? array_keys(array_filter($values[$setting])) : $values[$setting];
      }
    }
    content_access_set_settings($settings, $node_type);

    // Mass update the nodes, but only if necessary.
    if (content_access_get_settings('per_node', $node_type) || content_access_get_settings('view', $node_type) != $form['per_role']['view']['#default_value'] || content_access_get_settings('view_own', $node_type) != $form['per_role']['view_own']['#default_value'] || content_access_get_settings('priority', $node_type) != $form['advanced']['priority']['#default_value'] || content_access_get_settings('per_node', $node_type) != $form['node']['per_node']['#default_value']) {

      // If per node has been disabled and we use the ACL integration, we have
      // to remove possible ACLs now.
      if (!content_access_get_settings('per_node', $node_type) && $form['node']['per_node']['#default_value'] && $this->moduleHandler
        ->moduleExists('acl')) {
        _content_access_remove_acls($node_type);
      }
      if (content_access_mass_update([
        $node_type,
      ])) {
        $node_types = node_type_get_names();

        // This does not gurantee a rebuild.
        $this
          ->messenger()
          ->addMessage($this
          ->t('Permissions have been changed for the content type @types.<br />You may have to <a href=":rebuild">rebuild permissions</a> for your changes to take effect.', [
          '@types' => $node_types[$node_type],
          ':rebuild' => Url::fromRoute('node.configure_rebuild_confirm')
            ->toString(),
        ]));
      }
    }
    else {
      $this
        ->messenger()
        ->addMessage($this
        ->t('No change.'));
    }
  }

  /**
   * Saves the given permissions by role to the database.
   */
  protected function savePermissions($roles_permissions) {
    foreach ($roles_permissions as $rid => $permissions) {
      user_role_change_permissions($rid, $permissions);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContentAccessAdminSettingsForm::$moduleHandler protected property The module handler service.
ContentAccessAdminSettingsForm::$permissionHandler protected property The permission handler.
ContentAccessAdminSettingsForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ContentAccessAdminSettingsForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ContentAccessAdminSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ContentAccessAdminSettingsForm::savePermissions protected function Saves the given permissions by role to the database.
ContentAccessAdminSettingsForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ContentAccessAdminSettingsForm::__construct public function Constructs a new ContentAccessAdminSettingsForm.
ContentAccessRoleBasedFormTrait::disableCheckboxes public static function Checkboxes access for content.
ContentAccessRoleBasedFormTrait::roleBasedForm protected function Builds the role based permission form for the given defaults.
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::config protected function Retrieves a configuration object.
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
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.