You are here

class ContentAccessPageForm in Content Access 8

Node Access settings form.

@package Drupal\content_access\Form

Hierarchy

Expanded class hierarchy of ContentAccessPageForm

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

File

src/Form/ContentAccessPageForm.php, line 21

Namespace

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

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   *   The entity type manager.
   */
  protected $entityTypeManager;

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

  /**
   * The node grant storage.
   *
   * @var \Drupal\node\NodeGrantDatabaseStorageInterface
   */
  protected $grantStorage;

  /**
   * ContentAccessPageForm constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   * @param \Drupal\node\NodeGrantDatabaseStorageInterface $grant_storage
   *   The node grant storage.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, NodeGrantDatabaseStorageInterface $grant_storage) {
    $this->entityTypeManager = $entity_type_manager;
    $this->moduleHandler = $module_handler;
    $this->grantStorage = $grant_storage;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
    $defaults = [];
    foreach (_content_access_get_operations() as $op => $label) {
      $defaults[$op] = content_access_per_node_setting($op, $node);
    }
    $this
      ->roleBasedForm($form, $defaults, $node
      ->getType());

    // Add an after_build handler that disables checkboxes, which are enforced
    // by permissions.
    $build_info = $form_state
      ->getBuildInfo();
    $build_info['files'][] = [
      'module' => 'content_access',
      'type' => 'inc',
      'name' => 'content_access.admin',
    ];
    $form_state
      ->setBuildInfo($build_info);
    foreach ([
      'update',
      'update_own',
      'delete',
      'delete_own',
    ] as $op) {
      $form['per_role'][$op]['#process'][] = '::forcePermissions';
    }

    // ACL form.
    if ($this->moduleHandler
      ->moduleExists('acl')) {

      // This is disabled when there is no node passed.
      $form['acl'] = [
        '#type' => 'fieldset',
        '#title' => $this
          ->t('User access control lists'),
        '#description' => $this
          ->t('These settings allow you to grant access to specific users.'),
        '#collapsible' => TRUE,
        '#tree' => TRUE,
      ];
      foreach ([
        'view',
        'update',
        'delete',
      ] as $op) {
        $acl_id = content_access_get_acl_id($node, $op);
        $view = (int) ($op == 'view');
        $update = (int) ($op == 'update');
        acl_node_add_acl($node
          ->id(), $acl_id, $view, $update, (int) ($op == 'delete'), content_access_get_settings('priority', $node
          ->getType()));
        $form['acl'][$op] = acl_edit_form($form_state, $acl_id, $this
          ->t('Grant @op access', [
          '@op' => $op,
        ]));
        $post_acl_id = $this
          ->getRequest()->request
          ->get('acl_' . $acl_id, NULL);
        $form['acl'][$op]['#collapsed'] = !isset($post_acl_id) && !unserialize($form['acl'][$op]['user_list']['#default_value']);
      }
    }
    $storage['node'] = $node;
    $form_state
      ->setStorage($storage);
    $form['reset'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Reset to defaults'),
      '#weight' => 10,
      '#submit' => [
        '::pageResetSubmit',
      ],
      '#access' => !empty(content_access_get_per_node_settings($node)),
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
      '#weight' => 10,
    ];

    // @todo not true anymore?
    // http://drupal.org/update/modules/6/7#hook_node_access_records
    if (!$node
      ->isPublished()) {
      $this
        ->messenger()
        ->addError($this
        ->t("Warning: Your content is not published, so this settings are not taken into account as long as the content remains unpublished."));
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $settings = [];
    $storage = $form_state
      ->getStorage();
    $values = $form_state
      ->getValues();
    $node = $storage['node'];
    foreach (_content_access_get_operations() as $op => $label) {

      // Set the settings so that further calls will return this settings.
      $filtered_values = array_filter($values[$op]);
      $settings[$op] = array_keys($filtered_values);
    }

    // Save per-node settings.
    content_access_save_per_node_settings($node, $settings);
    if ($this->moduleHandler
      ->moduleExists('acl')) {
      foreach ([
        'view',
        'update',
        'delete',
      ] as $op) {
        $values = $form_state
          ->getValues();
        acl_save_form($values['acl'][$op]);
        $this->moduleHandler
          ->invokeAll('user_acl', $settings);
      }
    }

    // Apply new settings.
    $grants = $this->entityTypeManager
      ->getAccessControlHandler('node')
      ->acquireGrants($node);
    $this->grantStorage
      ->write($node, $grants);
    $this->moduleHandler
      ->invokeAll('per_node', $settings);
    foreach (Cache::getBins() as $cache_backend) {
      $cache_backend
        ->deleteAll();
    }

    // xxxx
    // route: node.configure_rebuild_confirm:
    // path:  '/admin/reports/status/rebuild'.
    $this
      ->messenger()
      ->addMessage($this
      ->t('Your changes have been saved. You may have to <a href=":rebuild">rebuild permissions</a> for your changes to take effect.', [
      ':rebuild' => Url::fromRoute('node.configure_rebuild_confirm')
        ->toString(),
    ]));
  }

  /**
   * Submit callback for reset on content_access_page().
   */
  public function pageResetSubmit(array &$form, FormStateInterface $form_state) {
    $storage = $form_state
      ->getStorage();
    content_access_delete_per_node_settings($storage['node']);
    $node = $storage['node'];
    $grants = $this->entityTypeManager
      ->getAccessControlHandler('node')
      ->acquireGrants($node);
    $this->grantStorage
      ->write($node, $grants);
    $this
      ->messenger()
      ->addMessage($this
      ->t('The permissions have been reset to the content type defaults.'));
  }

  /**
   * Checkboxes access for content.
   *
   * Formapi #process callback, that disables checkboxes for roles without
   * access to content.
   */
  public function forcePermissions($element, FormStateInterface $form_state, &$complete_form) {
    $storage = $form_state
      ->getStorage();
    if (!empty($storage['node'] && is_array($element['#parents']))) {
      $node = $storage['node'];
      foreach (content_access_get_settings(reset($element['#parents']), $node
        ->getType()) as $rid) {
        $element[$rid]['#disabled'] = TRUE;
        $element[$rid]['#attributes']['disabled'] = 'disabled';
        $element[$rid]['#value'] = TRUE;
        $element[$rid]['#checked'] = TRUE;
        $prefix_attr = new Attribute([
          'title' => $this
            ->t("Permission is granted due to the content type\\'s access control settings."),
        ]);
        $element[$rid]['#prefix'] = '<span ' . $prefix_attr . '>';
        $element[$rid]['#suffix'] = "</span>";
      }
    }
    return $element;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContentAccessPageForm::$entityTypeManager protected property The entity type manager.
ContentAccessPageForm::$grantStorage protected property The node grant storage.
ContentAccessPageForm::$moduleHandler protected property The module handler service.
ContentAccessPageForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ContentAccessPageForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ContentAccessPageForm::forcePermissions public function Checkboxes access for content.
ContentAccessPageForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ContentAccessPageForm::pageResetSubmit public function Submit callback for reset on content_access_page().
ContentAccessPageForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ContentAccessPageForm::__construct public function ContentAccessPageForm constructor.
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.