clean install

This commit is contained in:
2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 changed files with 3555714 additions and 0 deletions

View File

@@ -0,0 +1,99 @@
<?php
namespace Drupal\content_moderation\Access;
use Drupal\Core\Access\AccessException;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\EntityOwnerInterface;
use Symfony\Component\Routing\Route;
/**
* Access check for the entity moderation tab.
*/
class LatestRevisionCheck implements AccessInterface {
/**
* The moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInfo;
/**
* Constructs a new LatestRevisionCheck.
*
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_information
* The moderation information service.
*/
public function __construct(ModerationInformationInterface $moderation_information) {
$this->moderationInfo = $moderation_information;
}
/**
* Checks that there is a pending revision available.
*
* This checker assumes the presence of an '_entity_access' requirement key
* in the same form as used by EntityAccessCheck.
*
* @param \Symfony\Component\Routing\Route $route
* The route to check against.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The parametrized route.
* @param \Drupal\Core\Session\AccountInterface $account
* The current user account.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*
* @see \Drupal\Core\Entity\EntityAccessCheck
*/
public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
// This tab should not show up unless there's a reason to show it.
$entity = $this->loadEntity($route, $route_match);
if ($this->moderationInfo->hasPendingRevision($entity)) {
// Check the global permissions first.
$access_result = AccessResult::allowedIfHasPermissions($account, ['view latest version', 'view any unpublished content']);
if (!$access_result->isAllowed()) {
// Check entity owner access.
$owner_access = AccessResult::allowedIfHasPermissions($account, ['view latest version', 'view own unpublished content']);
$owner_access = $owner_access->andIf((AccessResult::allowedIf($entity instanceof EntityOwnerInterface && ($entity->getOwnerId() == $account->id()))));
$access_result = $access_result->orIf($owner_access);
}
return $access_result->addCacheableDependency($entity);
}
return AccessResult::forbidden('No pending revision for moderated entity.')->addCacheableDependency($entity);
}
/**
* Returns the default revision of the entity this route is for.
*
* @param \Symfony\Component\Routing\Route $route
* The route to check against.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The parametrized route.
*
* @return \Drupal\Core\Entity\ContentEntityInterface
* returns the Entity in question.
*
* @throws \Drupal\Core\Access\AccessException
* An AccessException is thrown if the entity couldn't be loaded.
*/
protected function loadEntity(Route $route, RouteMatchInterface $route_match) {
$entity_type = $route->getOption('_content_moderation_entity_type');
if ($entity = $route_match->getParameter($entity_type)) {
if ($entity instanceof EntityInterface) {
return $entity;
}
}
throw new AccessException(sprintf('%s is not a valid entity route. The LatestRevisionCheck access checker may only be used with a route that has a single entity parameter.', $route_match->getRouteName()));
}
}

View File

@@ -0,0 +1,114 @@
<?php
namespace Drupal\content_moderation;
use Drupal\workflows\StateInterface;
/**
* A value object representing a workflow state for content moderation.
*/
class ContentModerationState implements StateInterface {
/**
* The vanilla state object from the Workflow module.
*
* @var \Drupal\workflows\StateInterface
*/
protected $state;
/**
* If entities should be published if in this state.
*
* @var bool
*/
protected $published;
/**
* If entities should be the default revision if in this state.
*
* @var bool
*/
protected $defaultRevision;
/**
* ContentModerationState constructor.
*
* Decorates state objects to add methods to determine if an entity should be
* published or made the default revision.
*
* @param \Drupal\workflows\StateInterface $state
* The vanilla state object from the Workflow module.
* @param bool $published
* (optional) TRUE if entities should be published if in this state, FALSE
* if not. Defaults to FALSE.
* @param bool $default_revision
* (optional) TRUE if entities should be the default revision if in this
* state, FALSE if not. Defaults to FALSE.
*/
public function __construct(StateInterface $state, $published = FALSE, $default_revision = FALSE) {
$this->state = $state;
$this->published = $published;
$this->defaultRevision = $default_revision;
}
/**
* Determines if entities should be published if in this state.
*
* @return bool
*/
public function isPublishedState() {
return $this->published;
}
/**
* Determines if entities should be the default revision if in this state.
*
* @return bool
*/
public function isDefaultRevisionState() {
return $this->defaultRevision;
}
/**
* {@inheritdoc}
*/
public function id() {
return $this->state->id();
}
/**
* {@inheritdoc}
*/
public function label() {
return $this->state->label();
}
/**
* {@inheritdoc}
*/
public function weight() {
return $this->state->weight();
}
/**
* {@inheritdoc}
*/
public function canTransitionTo($to_state_id) {
return $this->state->canTransitionTo($to_state_id);
}
/**
* {@inheritdoc}
*/
public function getTransitionTo($to_state_id) {
return $this->state->getTransitionTo($to_state_id);
}
/**
* {@inheritdoc}
*/
public function getTransitions() {
return $this->state->getTransitions();
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Drupal\content_moderation;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityInterface;
/**
* The access control handler for the content_moderation_state entity type.
*
* @see \Drupal\content_moderation\Entity\ContentModerationState
*/
class ContentModerationStateAccessControlHandler extends EntityAccessControlHandler {
/**
* {@inheritdoc}
*/
public function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
// ContentModerationState is an internal entity type. Access is denied for
// viewing, updating, and deleting. In order to update an entity's
// moderation state use its moderation_state field.
return AccessResult::forbidden('ContentModerationState is an internal entity type.');
}
/**
* {@inheritdoc}
*/
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
// ContentModerationState is an internal entity type. Access is denied for
// creating. In order to update an entity's moderation state use its
// moderation_state field.
return AccessResult::forbidden('ContentModerationState is an internal entity type.');
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Drupal\content_moderation;
use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema;
/**
* Defines the content moderation state schema handler.
*/
class ContentModerationStateStorageSchema extends SqlContentEntityStorageSchema {
/**
* {@inheritdoc}
*/
protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE) {
$schema = parent::getEntitySchema($entity_type, $reset);
// Creates unique keys to guarantee the integrity of the entity and to make
// the lookup in ModerationStateFieldItemList::getModerationState() fast.
$unique_keys = [
'content_entity_type_id',
'content_entity_id',
'content_entity_revision_id',
'workflow',
'langcode',
];
if ($data_table = $this->storage->getDataTable()) {
$schema[$data_table]['unique keys'] += [
'content_moderation_state__lookup' => $unique_keys,
];
}
if ($revision_data_table = $this->storage->getRevisionDataTable()) {
$schema[$revision_data_table]['unique keys'] += [
'content_moderation_state__lookup' => $unique_keys,
];
}
return $schema;
}
}

View File

@@ -0,0 +1,70 @@
<?php
namespace Drupal\content_moderation;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\node\Entity\Node;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Determines whether a route is the "Latest version" tab of a node.
*
* @internal
*/
class ContentPreprocess implements ContainerInjectionInterface {
/**
* The route match service.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $routeMatch;
/**
* Constructor.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* Current route match service.
*/
public function __construct(RouteMatchInterface $route_match) {
$this->routeMatch = $route_match;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('current_route_match')
);
}
/**
* @param array $variables
* Theme variables to preprocess.
*
* @see hook_preprocess_HOOK()
*/
public function preprocessNode(array &$variables) {
// Set the 'page' template variable when the node is being displayed on the
// "Latest version" tab provided by content_moderation.
$variables['page'] = $variables['page'] || $this->isLatestVersionPage($variables['node']);
}
/**
* Checks whether a route is the "Latest version" tab of a node.
*
* @param \Drupal\node\Entity\Node $node
* A node.
*
* @return bool
* True if the current route is the latest version tab of the given node.
*/
public function isLatestVersionPage(Node $node) {
return $this->routeMatch->getRouteName() == 'entity.node.latest_version'
&& ($pageNode = $this->routeMatch->getParameter('node'))
&& $pageNode->id() == $node->id();
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Drupal\content_moderation\Controller;
use Drupal\content_moderation\ModeratedNodeListBuilder;
use Drupal\Core\Controller\ControllerBase;
/**
* Defines a controller to list moderated nodes.
*/
class ModeratedContentController extends ControllerBase {
/**
* Provides the listing page for moderated nodes.
*
* @return array
* A render array as expected by
* \Drupal\Core\Render\RendererInterface::render().
*/
public function nodeListing() {
$entity_type = $this->entityTypeManager()->getDefinition('node');
return $this->entityTypeManager()->createHandlerInstance(ModeratedNodeListBuilder::class, $entity_type)->render();
}
}

View File

@@ -0,0 +1,204 @@
<?php
namespace Drupal\content_moderation\Entity;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\TypedData\TranslatableInterface;
use Drupal\user\EntityOwnerTrait;
/**
* Defines the Content moderation state entity.
*
* @ContentEntityType(
* id = "content_moderation_state",
* label = @Translation("Content moderation state"),
* label_singular = @Translation("content moderation state"),
* label_plural = @Translation("content moderation states"),
* label_count = @PluralTranslation(
* singular = "@count content moderation state",
* plural = "@count content moderation states"
* ),
* handlers = {
* "storage_schema" = "Drupal\content_moderation\ContentModerationStateStorageSchema",
* "views_data" = "\Drupal\views\EntityViewsData",
* "access" = "Drupal\content_moderation\ContentModerationStateAccessControlHandler",
* },
* base_table = "content_moderation_state",
* revision_table = "content_moderation_state_revision",
* data_table = "content_moderation_state_field_data",
* revision_data_table = "content_moderation_state_field_revision",
* translatable = TRUE,
* internal = TRUE,
* entity_keys = {
* "id" = "id",
* "revision" = "revision_id",
* "uuid" = "uuid",
* "uid" = "uid",
* "owner" = "uid",
* "langcode" = "langcode",
* }
* )
*
* @internal
* This entity is marked internal because it should not be used directly to
* alter the moderation state of an entity. Instead, the computed
* moderation_state field should be set on the entity directly.
*/
class ContentModerationState extends ContentEntityBase implements ContentModerationStateInterface {
use EntityOwnerTrait;
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
$fields += static::ownerBaseFieldDefinitions($entity_type);
$fields['uid']
->setLabel(t('User'))
->setDescription(t('The username of the entity creator.'))
->setRevisionable(TRUE);
$fields['workflow'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Workflow'))
->setDescription(t('The workflow the moderation state is in.'))
->setSetting('target_type', 'workflow')
->setRequired(TRUE)
->setRevisionable(TRUE);
$fields['moderation_state'] = BaseFieldDefinition::create('string')
->setLabel(t('Moderation state'))
->setDescription(t('The moderation state of the referenced content.'))
->setRequired(TRUE)
->setTranslatable(TRUE)
->setRevisionable(TRUE);
$fields['content_entity_type_id'] = BaseFieldDefinition::create('string')
->setLabel(t('Content entity type ID'))
->setDescription(t('The ID of the content entity type this moderation state is for.'))
->setRequired(TRUE)
->setSetting('max_length', EntityTypeInterface::ID_MAX_LENGTH)
->setRevisionable(TRUE);
$fields['content_entity_id'] = BaseFieldDefinition::create('integer')
->setLabel(t('Content entity ID'))
->setDescription(t('The ID of the content entity this moderation state is for.'))
->setRequired(TRUE)
->setRevisionable(TRUE);
$fields['content_entity_revision_id'] = BaseFieldDefinition::create('integer')
->setLabel(t('Content entity revision ID'))
->setDescription(t('The revision ID of the content entity this moderation state is for.'))
->setRequired(TRUE)
->setRevisionable(TRUE);
return $fields;
}
/**
* Creates or updates an entity's moderation state whilst saving that entity.
*
* @param \Drupal\content_moderation\Entity\ContentModerationState $content_moderation_state
* The content moderation entity content entity to create or save.
*
* @internal
* This method should only be called as a result of saving the related
* content entity.
*/
public static function updateOrCreateFromEntity(ContentModerationState $content_moderation_state) {
$content_moderation_state->realSave();
}
/**
* Loads a content moderation state entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* A moderated entity object.
*
* @return \Drupal\content_moderation\Entity\ContentModerationStateInterface|null
* The related content moderation state or NULL if none could be found.
*
* @internal
* This method should only be called by code directly handling the
* ContentModerationState entity objects.
*/
public static function loadFromModeratedEntity(EntityInterface $entity) {
$content_moderation_state = NULL;
$moderation_info = \Drupal::service('content_moderation.moderation_information');
if ($moderation_info->isModeratedEntity($entity)) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$storage = \Drupal::entityTypeManager()->getStorage('content_moderation_state');
// New entities may not have a loaded revision ID at this point, but the
// creation of a content moderation state entity may have already been
// triggered elsewhere. In this case we have to match on the revision ID
// (instead of the loaded revision ID).
$revision_id = $entity->getLoadedRevisionId() ?: $entity->getRevisionId();
$ids = $storage->getQuery()
->accessCheck(FALSE)
->condition('content_entity_type_id', $entity->getEntityTypeId())
->condition('content_entity_id', $entity->id())
->condition('workflow', $moderation_info->getWorkflowForEntity($entity)->id())
->condition('content_entity_revision_id', $revision_id)
->allRevisions()
->execute();
if ($ids) {
/** @var \Drupal\content_moderation\Entity\ContentModerationStateInterface $content_moderation_state */
$content_moderation_state = $storage->loadRevision(key($ids));
}
}
return $content_moderation_state;
}
/**
* {@inheritdoc}
*/
public function save() {
/** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
$storage = \Drupal::entityTypeManager()
->getStorage($this->content_entity_type_id->value);
$related_entity = $storage
->loadRevision($this->content_entity_revision_id->value);
if ($related_entity instanceof TranslatableInterface) {
$related_entity = $related_entity->getTranslation($this->activeLangcode);
}
$related_entity->moderation_state = $this->moderation_state;
return $related_entity->save();
}
/**
* Saves an entity permanently.
*
* When saving existing entities, the entity is assumed to be complete,
* partial updates of entities are not supported.
*
* @return int
* Either SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
*
* @throws \Drupal\Core\Entity\EntityStorageException
* In case of failures an exception is thrown.
*/
protected function realSave() {
return parent::save();
}
/**
* {@inheritdoc}
*/
protected function getFieldsToSkipFromTranslationChangesCheck() {
$field_names = parent::getFieldsToSkipFromTranslationChangesCheck();
// We need to skip the parent entity revision ID, since that will always
// change on every save, otherwise every translation would be marked as
// affected regardless of actual changes.
$field_names[] = 'content_entity_revision_id';
return $field_names;
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Drupal\content_moderation\Entity;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\user\EntityOwnerInterface;
/**
* An interface for Content moderation state entity.
*
* Content moderation state entities track the moderation state of other content
* entities.
*
* @internal
*/
interface ContentModerationStateInterface extends ContentEntityInterface, EntityOwnerInterface {
}

View File

@@ -0,0 +1,43 @@
<?php
namespace Drupal\content_moderation\Entity\Handler;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Customizations for block content entities.
*
* @internal
*/
class BlockContentModerationHandler extends ModerationHandler {
/**
* {@inheritdoc}
*/
public function enforceRevisionsEntityFormAlter(array &$form, FormStateInterface $form_state, $form_id) {
$form['revision']['#default_value'] = TRUE;
$form['revision']['#disabled'] = TRUE;
$form['revision']['#description'] = $this->t('Revisions must be required when moderation is enabled.');
}
/**
* {@inheritdoc}
*/
public function enforceRevisionsBundleFormAlter(array &$form, FormStateInterface $form_state, $form_id) {
$form['revision']['#default_value'] = 1;
$form['revision']['#disabled'] = TRUE;
$form['revision']['#description'] = $this->t('Revisions must be required when moderation is enabled.');
}
/**
* {@inheritdoc}
*/
public function isModeratedEntity(ContentEntityInterface $entity) {
// Only reusable blocks can be moderated individually. Non-reusable or
// inline blocks are moderated as part of the entity they are a composite
// of.
return $entity->isReusable();
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace Drupal\content_moderation\Entity\Handler;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Common customizations for most/all entities.
*
* This class is intended primarily as a base class.
*
* @internal
*/
class ModerationHandler implements ModerationHandlerInterface, EntityHandlerInterface {
use StringTranslationTrait;
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static();
}
/**
* {@inheritdoc}
*/
public function isModeratedEntity(ContentEntityInterface $entity) {
// Moderate all entities included in the moderation workflow by default.
return TRUE;
}
/**
* {@inheritdoc}
*/
public function onPresave(ContentEntityInterface $entity, $default_revision, $published_state) {
// When entities are syncing, content moderation should not force a new
// revision to be created and should not update the default status of a
// revision. This is useful if changes are being made to entities or
// revisions which are not part of editorial updates triggered by normal
// content changes.
if (!$entity->isSyncing()) {
$entity->setNewRevision(TRUE);
$entity->isDefaultRevision($default_revision);
}
// Update publishing status if it can be updated and if it needs updating.
if (($entity instanceof EntityPublishedInterface) && $entity->isPublished() !== $published_state) {
$published_state ? $entity->setPublished() : $entity->setUnpublished();
}
}
/**
* {@inheritdoc}
*/
public function enforceRevisionsEntityFormAlter(array &$form, FormStateInterface $form_state, $form_id) {
}
/**
* {@inheritdoc}
*/
public function enforceRevisionsBundleFormAlter(array &$form, FormStateInterface $form_state, $form_id) {
}
}

View File

@@ -0,0 +1,82 @@
<?php
namespace Drupal\content_moderation\Entity\Handler;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Defines operations that need to vary by entity type.
*
* Much of the logic contained in this handler is an indication of flaws
* in the Entity API that are insufficiently standardized between entity types.
* Hopefully over time functionality can be removed from this interface.
*
* @internal
*/
interface ModerationHandlerInterface {
/**
* Determines if an entity should be moderated.
*
* At the workflow level, moderation is enabled or disabled for entire entity
* types or bundles. After a bundle has been enabled, there maybe be further
* decisions each entity type may make to evaluate if a given entity is
* appropriate to be included in a moderation workflow. The handler is only
* consulted after the user has configured the associated entity type and
* bundle to be included in a moderation workflow.
*
* Returning FALSE will remove the moderation state field widget from the
* associated entity form and opt out of all moderation related entity
* semantics, such as creating new revisions and changing the publishing
* status of a revision.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity we may be moderating.
*
* @return bool
* TRUE if this entity should be moderated, FALSE otherwise.
*/
public function isModeratedEntity(ContentEntityInterface $entity);
/**
* Operates on moderated content entities preSave().
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity to modify.
* @param bool $default_revision
* Whether the new revision should be made the default revision.
* @param bool $published_state
* Whether the state being transitioned to is a published state or not.
*/
public function onPresave(ContentEntityInterface $entity, $default_revision, $published_state);
/**
* Alters entity forms to enforce revision handling.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param string $form_id
* The form id.
*
* @see hook_form_alter()
*/
public function enforceRevisionsEntityFormAlter(array &$form, FormStateInterface $form_state, $form_id);
/**
* Alters bundle forms to enforce revision handling.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param string $form_id
* The form id.
*
* @see hook_form_alter()
*/
public function enforceRevisionsBundleFormAlter(array &$form, FormStateInterface $form_state, $form_id);
}

View File

@@ -0,0 +1,61 @@
<?php
namespace Drupal\content_moderation\Entity\Handler;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Customizations for node entities.
*
* @internal
*/
class NodeModerationHandler extends ModerationHandler {
/**
* The moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInfo;
/**
* NodeModerationHandler constructor.
*
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_info
* The moderation information service.
*/
public function __construct(ModerationInformationInterface $moderation_info) {
$this->moderationInfo = $moderation_info;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$container->get('content_moderation.moderation_information')
);
}
/**
* {@inheritdoc}
*/
public function enforceRevisionsEntityFormAlter(array &$form, FormStateInterface $form_state, $form_id) {
$form['revision']['#disabled'] = TRUE;
$form['revision']['#default_value'] = TRUE;
$form['revision']['#description'] = $this->t('Revisions are required.');
}
/**
* {@inheritdoc}
*/
public function enforceRevisionsBundleFormAlter(array &$form, FormStateInterface $form_state, $form_id) {
// Force the revision checkbox on.
$form['workflow']['options']['revision']['#value'] = 'revision';
$form['workflow']['options']['revision']['#disabled'] = TRUE;
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace Drupal\content_moderation\Entity\Handler;
use Drupal\Core\Form\FormStateInterface;
/**
* Customizations for taxonomy term entities.
*
* @internal
*/
class TaxonomyTermModerationHandler extends ModerationHandler {
/**
* {@inheritdoc}
*/
public function enforceRevisionsEntityFormAlter(array &$form, FormStateInterface $form_state, $form_id): void {
$form['revision']['#default_value'] = TRUE;
$form['revision']['#disabled'] = TRUE;
$form['revision']['#description'] = $this->t('Revisions must be required when moderation is enabled.');
}
/**
* {@inheritdoc}
*/
public function enforceRevisionsBundleFormAlter(array &$form, FormStateInterface $form_state, $form_id): void {
$form['revision']['#default_value'] = TRUE;
$form['revision']['#disabled'] = TRUE;
$form['revision']['#description'] = $this->t('Revisions must be required when moderation is enabled.');
}
}

View File

@@ -0,0 +1,123 @@
<?php
namespace Drupal\content_moderation\Entity\Routing;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Entity\Routing\EntityRouteProviderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* Dynamic route provider for the Content moderation module.
*
* Provides the following routes:
* - The latest version tab, showing the latest revision of an entity, not the
* default one.
*
* @internal
*/
class EntityModerationRouteProvider implements EntityRouteProviderInterface, EntityHandlerInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* Constructs a new DefaultHtmlRouteProvider.
*
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
*/
public function __construct(EntityFieldManagerInterface $entity_field_manager) {
$this->entityFieldManager = $entity_field_manager;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$container->get('entity_field.manager')
);
}
/**
* {@inheritdoc}
*/
public function getRoutes(EntityTypeInterface $entity_type) {
$collection = new RouteCollection();
if ($moderation_route = $this->getLatestVersionRoute($entity_type)) {
$entity_type_id = $entity_type->id();
$collection->add("entity.{$entity_type_id}.latest_version", $moderation_route);
}
return $collection;
}
/**
* Gets the moderation-form route.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
*
* @return \Symfony\Component\Routing\Route|null
* The generated route, if available.
*/
protected function getLatestVersionRoute(EntityTypeInterface $entity_type) {
if ($entity_type->hasLinkTemplate('latest-version') && $entity_type->hasViewBuilderClass()) {
$entity_type_id = $entity_type->id();
$route = new Route($entity_type->getLinkTemplate('latest-version'));
$route
->addDefaults([
'_entity_view' => "{$entity_type_id}.full",
'_title_callback' => '\Drupal\Core\Entity\Controller\EntityController::title',
])
// If the entity type is a node, unpublished content will be visible
// if the user has the "view any unpublished content" permission.
->setRequirement('_entity_access', "{$entity_type_id}.view")
->setRequirement('_content_moderation_latest_version', 'TRUE')
->setOption('_content_moderation_entity_type', $entity_type_id)
->setOption('parameters', [
$entity_type_id => [
'type' => 'entity:' . $entity_type_id,
'load_latest_revision' => TRUE,
],
]);
// Entity types with serial IDs can specify this in their route
// requirements, improving the matching process.
if ($this->getEntityTypeIdKeyType($entity_type) === 'integer') {
$route->setRequirement($entity_type_id, '\d+');
}
return $route;
}
}
/**
* Gets the type of the ID key for a given entity type.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* An entity type.
*
* @return string|null
* The type of the ID key for a given entity type, or NULL if the entity
* type does not support fields.
*/
protected function getEntityTypeIdKeyType(EntityTypeInterface $entity_type) {
if (!$entity_type->entityClassImplements(FieldableEntityInterface::class)) {
return NULL;
}
$field_storage_definitions = $this->entityFieldManager->getFieldStorageDefinitions($entity_type->id());
return $field_storage_definitions[$entity_type->getKey('id')]->getType();
}
}

View File

@@ -0,0 +1,324 @@
<?php
namespace Drupal\content_moderation;
use Drupal\content_moderation\Entity\ContentModerationState as ContentModerationStateEntity;
use Drupal\content_moderation\Entity\ContentModerationStateInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\content_moderation\Form\EntityModerationForm;
use Drupal\Core\Routing\RouteBuilderInterface;
use Drupal\workflows\Entity\Workflow;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines a class for reacting to entity events.
*
* @internal
*/
class EntityOperations implements ContainerInjectionInterface {
/**
* The Moderation Information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInfo;
/**
* The Entity Type Manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The Form Builder service.
*
* @var \Drupal\Core\Form\FormBuilderInterface
*/
protected $formBuilder;
/**
* The entity bundle information service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $bundleInfo;
/**
* The router builder service.
*
* @var \Drupal\Core\Routing\RouteBuilderInterface
*/
protected $routerBuilder;
/**
* Constructs a new EntityOperations object.
*
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_info
* Moderation information service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* Entity type manager service.
* @param \Drupal\Core\Form\FormBuilderInterface $form_builder
* The form builder.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info
* The entity bundle information service.
* @param \Drupal\Core\Routing\RouteBuilderInterface $router_builder
* The router builder service.
*/
public function __construct(ModerationInformationInterface $moderation_info, EntityTypeManagerInterface $entity_type_manager, FormBuilderInterface $form_builder, EntityTypeBundleInfoInterface $bundle_info, RouteBuilderInterface $router_builder) {
$this->moderationInfo = $moderation_info;
$this->entityTypeManager = $entity_type_manager;
$this->formBuilder = $form_builder;
$this->bundleInfo = $bundle_info;
$this->routerBuilder = $router_builder;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('content_moderation.moderation_information'),
$container->get('entity_type.manager'),
$container->get('form_builder'),
$container->get('entity_type.bundle.info'),
$container->get('router.builder')
);
}
/**
* Acts on an entity and set published status based on the moderation state.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity being saved.
*
* @see hook_entity_presave()
*/
public function entityPresave(EntityInterface $entity) {
if (!$this->moderationInfo->isModeratedEntity($entity)) {
return;
}
if ($entity->moderation_state->value) {
$workflow = $this->moderationInfo->getWorkflowForEntity($entity);
/** @var \Drupal\content_moderation\ContentModerationState $current_state */
$current_state = $workflow->getTypePlugin()
->getState($entity->moderation_state->value);
// This entity is default if it is new, the default revision, or the
// default revision is not published.
$update_default_revision = $entity->isNew()
|| $current_state->isDefaultRevisionState()
|| !$this->moderationInfo->isDefaultRevisionPublished($entity);
// Fire per-entity-type logic for handling the save process.
$this->entityTypeManager
->getHandler($entity->getEntityTypeId(), 'moderation')
->onPresave($entity, $update_default_revision, $current_state->isPublishedState());
}
}
/**
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity that was just saved.
*
* @see hook_entity_insert()
*/
public function entityInsert(EntityInterface $entity) {
if ($this->moderationInfo->isModeratedEntity($entity)) {
$this->updateOrCreateFromEntity($entity);
}
}
/**
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity that was just saved.
*
* @see hook_entity_update()
*/
public function entityUpdate(EntityInterface $entity) {
if ($this->moderationInfo->isModeratedEntity($entity)) {
$this->updateOrCreateFromEntity($entity);
}
// When updating workflow settings for Content Moderation, we need to
// rebuild routes as we may be enabling new entity types and the related
// entity forms.
elseif ($entity instanceof Workflow && $entity->getTypePlugin()->getPluginId() == 'content_moderation') {
$this->routerBuilder->setRebuildNeeded();
}
}
/**
* Creates or updates the moderation state of an entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to update or create a moderation state for.
*/
protected function updateOrCreateFromEntity(EntityInterface $entity) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity_revision_id = $entity->getRevisionId();
$workflow = $this->moderationInfo->getWorkflowForEntity($entity);
$content_moderation_state = ContentModerationStateEntity::loadFromModeratedEntity($entity);
/** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
$storage = $this->entityTypeManager->getStorage('content_moderation_state');
if (!($content_moderation_state instanceof ContentModerationStateInterface)) {
$content_moderation_state = $storage->create([
'content_entity_type_id' => $entity->getEntityTypeId(),
'content_entity_id' => $entity->id(),
// Make sure that the moderation state entity has the same language code
// as the moderated entity.
'langcode' => $entity->language()->getId(),
]);
$content_moderation_state->workflow->target_id = $workflow->id();
}
// Sync translations.
if ($entity->getEntityType()->hasKey('langcode')) {
$entity_langcode = $entity->language()->getId();
if ($entity->isDefaultTranslation()) {
$content_moderation_state->langcode = $entity_langcode;
}
else {
if (!$content_moderation_state->hasTranslation($entity_langcode)) {
$content_moderation_state->addTranslation($entity_langcode);
}
if ($content_moderation_state->language()->getId() !== $entity_langcode) {
$content_moderation_state = $content_moderation_state->getTranslation($entity_langcode);
}
}
}
// If a new revision of the content has been created, add a new content
// moderation state revision.
if (!$content_moderation_state->isNew() && $content_moderation_state->content_entity_revision_id->value != $entity_revision_id) {
$content_moderation_state = $storage->createRevision($content_moderation_state, $entity->isDefaultRevision());
}
// Create the ContentModerationState entity for the inserted entity.
$moderation_state = $entity->moderation_state->value;
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
if (!$moderation_state) {
$moderation_state = $workflow->getTypePlugin()->getInitialState($entity)->id();
}
$content_moderation_state->set('content_entity_revision_id', $entity_revision_id);
$content_moderation_state->set('moderation_state', $moderation_state);
ContentModerationStateEntity::updateOrCreateFromEntity($content_moderation_state);
}
/**
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity being deleted.
*
* @see hook_entity_delete()
*/
public function entityDelete(EntityInterface $entity) {
$content_moderation_state = ContentModerationStateEntity::loadFromModeratedEntity($entity);
if ($content_moderation_state) {
$content_moderation_state->delete();
}
}
/**
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity revision being deleted.
*
* @see hook_entity_revision_delete()
*/
public function entityRevisionDelete(EntityInterface $entity) {
if ($content_moderation_state = ContentModerationStateEntity::loadFromModeratedEntity($entity)) {
if ($content_moderation_state->isDefaultRevision()) {
$content_moderation_state->delete();
}
else {
$this->entityTypeManager
->getStorage('content_moderation_state')
->deleteRevision($content_moderation_state->getRevisionId());
}
}
}
/**
* @param \Drupal\Core\Entity\EntityInterface $translation
* The entity translation being deleted.
*
* @see hook_entity_translation_delete()
*/
public function entityTranslationDelete(EntityInterface $translation) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $translation */
if (!$translation->isDefaultTranslation()) {
$langcode = $translation->language()->getId();
$content_moderation_state = ContentModerationStateEntity::loadFromModeratedEntity($translation);
if ($content_moderation_state && $content_moderation_state->hasTranslation($langcode)) {
$content_moderation_state->removeTranslation($langcode);
ContentModerationStateEntity::updateOrCreateFromEntity($content_moderation_state);
}
}
}
/**
* Act on entities being assembled before rendering.
*
* @see hook_entity_view()
* @see EntityFieldManagerInterface::getExtraFields()
*/
public function entityView(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
if (!$this->moderationInfo->isModeratedEntity($entity)) {
return;
}
if (isset($entity->in_preview) && $entity->in_preview) {
return;
}
// If the component is not defined for this display, we have nothing to do.
if (!$display->getComponent('content_moderation_control')) {
return;
}
// The moderation form should be displayed only when viewing the latest
// (translation-affecting) revision, unless it was created as published
// default revision.
if (($entity->isDefaultRevision() || $entity->wasDefaultRevision()) && $this->isPublished($entity)) {
return;
}
if (!$entity->isLatestRevision() && !$entity->isLatestTranslationAffectedRevision()) {
return;
}
$build['content_moderation_control'] = $this->formBuilder->getForm(EntityModerationForm::class, $entity);
}
/**
* Checks if the entity is published.
*
* This method is optimized to not have to unnecessarily load the moderation
* state and workflow if it is not required.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity to check.
*
* @return bool
* TRUE if the entity is published, FALSE otherwise.
*/
protected function isPublished(ContentEntityInterface $entity) {
// If the entity implements EntityPublishedInterface directly, check that
// first, otherwise fall back to check through the workflow state.
if ($entity instanceof EntityPublishedInterface) {
return $entity->isPublished();
}
if ($moderation_state = $entity->get('moderation_state')->value) {
$workflow = $this->moderationInfo->getWorkflowForEntity($entity);
return $workflow->getTypePlugin()->getState($moderation_state)->isPublishedState();
}
return FALSE;
}
}

View File

@@ -0,0 +1,409 @@
<?php
namespace Drupal\content_moderation;
use Drupal\content_moderation\Plugin\Field\ModerationStateFieldItemList;
use Drupal\Core\Entity\BundleEntityFormBase;
use Drupal\Core\Entity\ContentEntityFormInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\content_moderation\Entity\Handler\BlockContentModerationHandler;
use Drupal\content_moderation\Entity\Handler\ModerationHandler;
use Drupal\content_moderation\Entity\Handler\NodeModerationHandler;
use Drupal\content_moderation\Entity\Handler\TaxonomyTermModerationHandler;
use Drupal\content_moderation\Entity\Routing\EntityModerationRouteProvider;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Manipulates entity type information.
*
* This class contains primarily bridged hooks for compile-time or
* cache-clear-time hooks. Runtime hooks should be placed in EntityOperations.
*
* @internal
*/
class EntityTypeInfo implements ContainerInjectionInterface {
use StringTranslationTrait;
/**
* The moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInfo;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The bundle information service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $bundleInfo;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The state transition validation service.
*
* @var \Drupal\content_moderation\StateTransitionValidationInterface
*/
protected $validator;
/**
* A keyed array of custom moderation handlers for given entity types.
*
* Any entity not specified will use a common default.
*
* @var array
*/
protected $moderationHandlers = [
'node' => NodeModerationHandler::class,
'block_content' => BlockContentModerationHandler::class,
'taxonomy_term' => TaxonomyTermModerationHandler::class,
];
/**
* EntityTypeInfo constructor.
*
* @param \Drupal\Core\StringTranslation\TranslationInterface $translation
* The translation service. for form alters.
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_information
* The moderation information service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* Entity type manager.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info
* Bundle information service.
* @param \Drupal\Core\Session\AccountInterface $current_user
* Current user.
* @param \Drupal\content_moderation\StateTransitionValidationInterface $validator
* State transition validator.
*/
public function __construct(TranslationInterface $translation, ModerationInformationInterface $moderation_information, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $bundle_info, AccountInterface $current_user, StateTransitionValidationInterface $validator) {
$this->stringTranslation = $translation;
$this->moderationInfo = $moderation_information;
$this->entityTypeManager = $entity_type_manager;
$this->bundleInfo = $bundle_info;
$this->currentUser = $current_user;
$this->validator = $validator;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('string_translation'),
$container->get('content_moderation.moderation_information'),
$container->get('entity_type.manager'),
$container->get('entity_type.bundle.info'),
$container->get('current_user'),
$container->get('content_moderation.state_transition_validation')
);
}
/**
* Adds Moderation configuration to appropriate entity types.
*
* @param \Drupal\Core\Entity\EntityTypeInterface[] $entity_types
* The master entity type list to alter.
*
* @see hook_entity_type_alter()
*/
public function entityTypeAlter(array &$entity_types) {
foreach ($entity_types as $entity_type_id => $entity_type) {
// Internal entity types should never be moderated, and the 'path_alias'
// entity type needs to be excluded for now.
// @todo Enable moderation for path aliases after they become publishable
// in https://www.drupal.org/project/drupal/issues/3007669.
// Workspace entities can not be moderated because they use string IDs.
// @see \Drupal\content_moderation\Entity\ContentModerationState::baseFieldDefinitions()
// where the target entity ID is defined as an integer.
// @todo Moderation is disabled for taxonomy terms until integration is
// enabled for them.
// @see https://www.drupal.org/project/drupal/issues/3047110
$entity_type_to_exclude = [
'path_alias',
'workspace',
];
if ($entity_type->isRevisionable() && !$entity_type->isInternal() && !in_array($entity_type_id, $entity_type_to_exclude)) {
$entity_types[$entity_type_id] = $this->addModerationToEntityType($entity_type);
}
}
}
/**
* Modifies an entity definition to include moderation support.
*
* This primarily just means an extra handler. A Generic one is provided,
* but individual entity types can provide their own as appropriate.
*
* @param \Drupal\Core\Entity\ContentEntityTypeInterface $type
* The content entity definition to modify.
*
* @return \Drupal\Core\Entity\ContentEntityTypeInterface
* The modified content entity definition.
*/
protected function addModerationToEntityType(ContentEntityTypeInterface $type) {
if (!$type->hasHandlerClass('moderation')) {
$handler_class = !empty($this->moderationHandlers[$type->id()]) ? $this->moderationHandlers[$type->id()] : ModerationHandler::class;
$type->setHandlerClass('moderation', $handler_class);
}
if (!$type->hasLinkTemplate('latest-version') && $type->hasLinkTemplate('canonical')) {
$type->setLinkTemplate('latest-version', $type->getLinkTemplate('canonical') . '/latest');
}
$providers = $type->getRouteProviderClasses() ?: [];
if (empty($providers['moderation'])) {
$providers['moderation'] = EntityModerationRouteProvider::class;
$type->setHandlerClass('route_provider', $providers);
}
return $type;
}
/**
* Gets the "extra fields" for a bundle.
*
* @return array
* A nested array of 'pseudo-field' elements. Each list is nested within the
* following keys: entity type, bundle name, context (either 'form' or
* 'display'). The keys are the name of the elements as appearing in the
* renderable array (either the entity form or the displayed entity). The
* value is an associative array:
* - label: The human readable name of the element. Make sure you sanitize
* this appropriately.
* - description: A short description of the element contents.
* - weight: The default weight of the element.
* - visible: (optional) The default visibility of the element. Defaults to
* TRUE.
* - edit: (optional) String containing markup (normally a link) used as the
* element's 'edit' operation in the administration interface. Only for
* 'form' context.
* - delete: (optional) String containing markup (normally a link) used as
* the element's 'delete' operation in the administration interface. Only
* for 'form' context.
*
* @see hook_entity_extra_field_info()
*/
public function entityExtraFieldInfo() {
$return = [];
foreach ($this->getModeratedBundles() as $bundle) {
$return[$bundle['entity']][$bundle['bundle']]['display']['content_moderation_control'] = [
'label' => $this->t('Moderation control'),
'description' => $this->t("Status listing and form for the entity's moderation state."),
'weight' => -20,
'visible' => TRUE,
];
}
return $return;
}
/**
* Returns an iterable list of entity names and bundle names under moderation.
*
* That is, this method returns a list of bundles that have Content
* Moderation enabled on them.
*
* @return \Generator
* A generator, yielding a 2 element associative array:
* - entity: The machine name of an entity type, such as "node" or
* "block_content".
* - bundle: The machine name of a bundle, such as "page" or "article".
*/
protected function getModeratedBundles() {
$entity_types = array_filter($this->entityTypeManager->getDefinitions(), [$this->moderationInfo, 'canModerateEntitiesOfEntityType']);
foreach ($entity_types as $type_name => $type) {
foreach ($this->bundleInfo->getBundleInfo($type_name) as $bundle_id => $bundle) {
if ($this->moderationInfo->shouldModerateEntitiesOfBundle($type, $bundle_id)) {
yield ['entity' => $type_name, 'bundle' => $bundle_id];
}
}
}
}
/**
* Adds base field info to an entity type.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* Entity type for adding base fields to.
*
* @return \Drupal\Core\Field\BaseFieldDefinition[]
* New fields added by moderation state.
*
* @see hook_entity_base_field_info()
*/
public function entityBaseFieldInfo(EntityTypeInterface $entity_type) {
if (!$this->moderationInfo->isModeratedEntityType($entity_type)) {
return [];
}
$fields = [];
$fields['moderation_state'] = BaseFieldDefinition::create('string')
->setLabel(t('Moderation state'))
->setDescription(t('The moderation state of this piece of content.'))
->setComputed(TRUE)
->setClass(ModerationStateFieldItemList::class)
->setDisplayOptions('view', [
'label' => 'hidden',
'region' => 'hidden',
'weight' => -5,
])
->setDisplayOptions('form', [
'type' => 'moderation_state_default',
'weight' => 100,
'settings' => [],
])
->addConstraint('ModerationState', [])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', FALSE)
->setReadOnly(FALSE)
->setTranslatable(TRUE);
return $fields;
}
/**
* Replaces the entity form entity object with a proper revision object.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity being edited.
* @param string $operation
* The entity form operation.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @see hook_entity_prepare_form()
*/
public function entityPrepareForm(EntityInterface $entity, $operation, FormStateInterface $form_state) {
/** @var \Drupal\Core\Entity\EntityFormInterface $form_object */
$form_object = $form_state->getFormObject();
if ($this->isModeratedEntityEditForm($form_object) && !$entity->isNew()) {
// Generate a proper revision object for the current entity. This allows
// to correctly handle translatable entities having pending revisions.
/** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
$storage = $this->entityTypeManager->getStorage($entity->getEntityTypeId());
/** @var \Drupal\Core\Entity\ContentEntityInterface $new_revision */
$new_revision = $storage->createRevision($entity, FALSE);
// Restore the revision ID as other modules may expect to find it still
// populated. This will reset the "new revision" flag, however the entity
// object will be marked as a new revision again on submit.
// @see \Drupal\Core\Entity\ContentEntityForm::buildEntity()
$revision_key = $new_revision->getEntityType()->getKey('revision');
$new_revision->set($revision_key, $new_revision->getLoadedRevisionId());
$form_object->setEntity($new_revision);
}
}
/**
* Alters bundle forms to enforce revision handling.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param string $form_id
* The form id.
*
* @see hook_form_alter()
*/
public function formAlter(array &$form, FormStateInterface $form_state, $form_id) {
$form_object = $form_state->getFormObject();
if ($form_object instanceof BundleEntityFormBase) {
$config_entity = $form_object->getEntity();
$bundle_of = $config_entity->getEntityType()->getBundleOf();
if ($bundle_of
&& ($bundle_of_entity_type = $this->entityTypeManager->getDefinition($bundle_of))
&& $this->moderationInfo->shouldModerateEntitiesOfBundle($bundle_of_entity_type, $config_entity->id())) {
$this->entityTypeManager->getHandler($bundle_of, 'moderation')->enforceRevisionsBundleFormAlter($form, $form_state, $form_id);
}
}
elseif ($this->isModeratedEntityEditForm($form_object)) {
/** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $form_object->getEntity();
$this->entityTypeManager
->getHandler($entity->getEntityTypeId(), 'moderation')
->enforceRevisionsEntityFormAlter($form, $form_state, $form_id);
// Submit handler to redirect to the latest version, if available.
$form['actions']['submit']['#submit'][] = [EntityTypeInfo::class, 'bundleFormRedirect'];
// Move the 'moderation_state' field widget to the footer region, if
// available.
if (isset($form['footer']) && in_array($form_object->getOperation(), ['edit', 'default'], TRUE)) {
$form['moderation_state']['#group'] = 'footer';
}
// If the publishing status exists in the meta region, replace it with
// the current state instead.
if (isset($form['meta']['published'])) {
$form['meta']['published']['#markup'] = $this->moderationInfo->getWorkflowForEntity($entity)->getTypePlugin()->getState($entity->moderation_state->value)->label();
}
}
}
/**
* Checks whether the specified form allows to edit a moderated entity.
*
* @param \Drupal\Core\Form\FormInterface $form_object
* The form object.
*
* @return bool
* TRUE if the form should get form moderation, FALSE otherwise.
*/
protected function isModeratedEntityEditForm(FormInterface $form_object) {
return $form_object instanceof ContentEntityFormInterface &&
in_array($form_object->getOperation(), ['edit', 'default', 'layout_builder'], TRUE) &&
$this->moderationInfo->isModeratedEntity($form_object->getEntity());
}
/**
* Redirect content entity edit forms on save, if there is a pending revision.
*
* When saving their changes, editors should see those changes displayed on
* the next page.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
public static function bundleFormRedirect(array &$form, FormStateInterface $form_state) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $form_state->getFormObject()->getEntity();
$moderation_info = \Drupal::getContainer()->get('content_moderation.moderation_information');
if ($moderation_info->hasPendingRevision($entity) && $entity->hasLinkTemplate('latest-version')) {
$entity_type_id = $entity->getEntityTypeId();
$form_state->setRedirect("entity.$entity_type_id.latest_version", [$entity_type_id => $entity->id()]);
}
}
}

View File

@@ -0,0 +1,100 @@
<?php
namespace Drupal\content_moderation\EventSubscriber;
use Drupal\Core\Config\ConfigImporterEvent;
use Drupal\Core\Config\ConfigImportValidateEventSubscriberBase;
use Drupal\Core\Config\ConfigManagerInterface;
use Drupal\Core\Config\Entity\ConfigEntityStorage;
use Drupal\Core\Entity\EntityTypeManagerInterface;
/**
* Check moderation states are not being used before updating workflow config.
*/
class ConfigImportSubscriber extends ConfigImportValidateEventSubscriberBase {
/**
* The config manager.
*
* @var \Drupal\Core\Config\ConfigManagerInterface
*/
protected $configManager;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs the event subscriber.
*
* @param \Drupal\Core\Config\ConfigManagerInterface $config_manager
* The config manager
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(ConfigManagerInterface $config_manager, EntityTypeManagerInterface $entity_type_manager) {
$this->configManager = $config_manager;
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public function onConfigImporterValidate(ConfigImporterEvent $event) {
foreach (['update', 'delete'] as $op) {
$unprocessed_configurations = $event->getConfigImporter()->getUnprocessedConfiguration($op);
foreach ($unprocessed_configurations as $unprocessed_configuration) {
if (($workflow = $this->getWorkflow($unprocessed_configuration))
&& $workflow->getTypePlugin()->getPluginId() === 'content_moderation') {
if ($op === 'update') {
$original_workflow_config = $event->getConfigImporter()
->getStorageComparer()
->getSourceStorage()
->read($unprocessed_configuration);
$workflow_config = $event->getConfigImporter()
->getStorageComparer()
->getTargetStorage()
->read($unprocessed_configuration);
$diff = array_diff_key($workflow_config['type_settings']['states'], $original_workflow_config['type_settings']['states']);
foreach (array_keys($diff) as $state_id) {
$state = $workflow->getTypePlugin()->getState($state_id);
if ($workflow->getTypePlugin()->workflowStateHasData($workflow, $state)) {
$event->getConfigImporter()->logError($this->t('The moderation state @state_label is being used, but is not in the source storage.', ['@state_label' => $state->label()]));
}
}
}
if ($op === 'delete') {
if ($workflow->getTypePlugin()->workflowHasData($workflow)) {
$event->getConfigImporter()->logError($this->t('The workflow @workflow_label is being used, and cannot be deleted.', ['@workflow_label' => $workflow->label()]));
}
}
}
}
}
}
/**
* Get the workflow entity object from the configuration name.
*
* @param string $config_name
* The configuration object name.
*
* @return \Drupal\workflows\WorkflowInterface|null
* A workflow entity object. NULL if no matching entity is found.
*/
protected function getWorkflow($config_name) {
$entity_type_id = $this->configManager->getEntityTypeIdByName($config_name);
if ($entity_type_id !== 'workflow') {
return;
}
/** @var \Drupal\Core\Config\Entity\ConfigEntityTypeInterface $entity_type */
$entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
$entity_id = ConfigEntityStorage::getIDFromConfigName($config_name, $entity_type->getConfigPrefix());
return $this->entityTypeManager->getStorage($entity_type_id)->load($entity_id);
}
}

View File

@@ -0,0 +1,106 @@
<?php
namespace Drupal\content_moderation\EventSubscriber;
use Drupal\content_moderation\ContentModerationState;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\workspaces\Event\WorkspacePrePublishEvent;
use Drupal\workspaces\Event\WorkspacePublishEvent;
use Drupal\workspaces\WorkspaceAssociationInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Checks whether a workspace is publishable, and prevents publishing if needed.
*/
class WorkspaceSubscriber implements EventSubscriberInterface {
/**
* Constructs a new WorkspaceSubscriber instance.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
* The entity type manager service.
* @param \Drupal\workspaces\WorkspaceAssociationInterface|null $workspaceAssociation
* The workspace association service.
*/
public function __construct(
protected readonly EntityTypeManagerInterface $entityTypeManager,
protected readonly ?WorkspaceAssociationInterface $workspaceAssociation,
) {}
/**
* Prevents a workspace from being published based on certain conditions.
*
* @param \Drupal\workspaces\Event\WorkspacePublishEvent $event
* The workspace publish event.
*/
public function onWorkspacePrePublish(WorkspacePublishEvent $event): void {
// Prevent a workspace from being published if there are any pending
// revisions in a moderation state that doesn't create default revisions.
$workspace = $event->getWorkspace();
$tracked_revisions = $this->workspaceAssociation->getTrackedEntities($workspace->id());
// Gather a list of moderation states that don't create a default revision.
$workflow_non_default_states = [];
foreach ($this->entityTypeManager->getStorage('workflow')->loadByProperties(['type' => 'content_moderation']) as $workflow) {
/** @var \Drupal\content_moderation\Plugin\WorkflowType\ContentModerationInterface $workflow_type */
$workflow_type = $workflow->getTypePlugin();
// Find all workflows which are moderating entity types of the same type
// to those that are tracked by the workspace.
if (array_intersect($workflow_type->getEntityTypes(), array_keys($tracked_revisions))) {
$workflow_non_default_states[$workflow->id()] = array_filter(array_map(function (ContentModerationState $state) {
return !$state->isDefaultRevisionState() ? $state->id() : NULL;
}, $workflow_type->getStates()));
}
}
// If no tracked revisions are moderated then no status check is necessary.
if (empty($workflow_non_default_states)) {
return;
}
// Check if any revisions that are about to be published are in a
// non-default revision moderation state.
$query = $this->entityTypeManager->getStorage('content_moderation_state')->getQuery()
->allRevisions()
->accessCheck(FALSE);
$tracked_revisions_condition_group = $query->orConditionGroup();
foreach ($tracked_revisions as $tracked_type => $tracked_revision_ids) {
$entity_type_group = $query->andConditionGroup()
->condition('content_entity_type_id', $tracked_type)
->condition('content_entity_revision_id', array_keys($tracked_revision_ids), 'IN');
$tracked_revisions_condition_group->condition($entity_type_group);
}
$query->condition($tracked_revisions_condition_group);
$workflow_condition_group = $query->orConditionGroup();
foreach ($workflow_non_default_states as $workflow_id => $non_default_states) {
$group = $query->andConditionGroup()
->condition('workflow', $workflow_id, '=')
->condition('moderation_state', $non_default_states, 'IN');
$workflow_condition_group->condition($group);
}
$query->condition($workflow_condition_group);
if ($count = $query->count()->execute()) {
$message = \Drupal::translation()->formatPlural($count, 'The @label workspace can not be published because it contains 1 item in an unpublished moderation state.', 'The @label workspace can not be published because it contains @count items in an unpublished moderation state.', [
'@label' => $workspace->label(),
]);
$event->stopPublishing();
$event->setPublishingStoppedReason((string) $message);
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events[WorkspacePrePublishEvent::class][] = ['onWorkspacePrePublish'];
return $events;
}
}

View File

@@ -0,0 +1,232 @@
<?php
namespace Drupal\content_moderation\Form;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CloseDialogCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\workflows\WorkflowInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* The form for editing entity types associated with a workflow.
*
* @internal
*/
class ContentModerationConfigureEntityTypesForm extends FormBase {
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity type bundle information service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $bundleInfo;
/**
* The moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInformation;
/**
* The workflow entity object.
*
* @var \Drupal\workflows\WorkflowInterface
*/
protected $workflow;
/**
* The entity type definition object.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $entityType;
/**
* The Messenger service.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('entity_type.bundle.info'),
$container->get('content_moderation.moderation_information'),
$container->get('messenger')
);
}
/**
* {@inheritdoc}
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $bundle_info, ModerationInformationInterface $moderation_information, MessengerInterface $messenger) {
$this->entityTypeManager = $entity_type_manager;
$this->bundleInfo = $bundle_info;
$this->moderationInformation = $moderation_information;
$this->messenger = $messenger;
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'workflow_type_edit_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ?WorkflowInterface $workflow = NULL, $entity_type_id = NULL) {
$this->workflow = $workflow;
try {
$this->entityType = $this->entityTypeManager->getDefinition($entity_type_id);
}
catch (PluginNotFoundException $e) {
throw new NotFoundHttpException();
}
$options = $defaults = [];
foreach ($this->bundleInfo->getBundleInfo($this->entityType->id()) as $bundle_id => $bundle) {
// Check if moderation is enabled for this bundle on any workflow.
$moderation_enabled = $this->moderationInformation->shouldModerateEntitiesOfBundle($this->entityType, $bundle_id);
// Check if moderation is enabled for this bundle on this workflow.
$workflow_moderation_enabled = $this->workflow->getTypePlugin()->appliesToEntityTypeAndBundle($this->entityType->id(), $bundle_id);
// Only show bundles that are not enabled anywhere, or enabled on this
// workflow.
if (!$moderation_enabled || $workflow_moderation_enabled) {
// Add the bundle to the options if it's not enabled on a workflow,
// unless the workflow it's enabled on is this one.
$options[$bundle_id] = [
'title' => ['data' => ['#title' => $bundle['label']]],
'type' => $bundle['label'],
];
// Add the bundle to the list of default values if it's enabled on this
// workflow.
$defaults[$bundle_id] = $workflow_moderation_enabled;
}
}
if (!empty($options)) {
$bundles_header = $this->t('All @entity_type types', ['@entity_type' => $this->entityType->getLabel()]);
if ($bundle_entity_type_id = $this->entityType->getBundleEntityType()) {
$bundles_header = $this->t('All @entity_type_plural_label', ['@entity_type_plural_label' => $this->entityTypeManager->getDefinition($bundle_entity_type_id)->getPluralLabel()]);
}
$form['bundles'] = [
'#type' => 'tableselect',
'#header' => [
'type' => $bundles_header,
],
'#options' => $options,
'#default_value' => $defaults,
'#attributes' => ['class' => ['no-highlight']],
];
}
// Get unsupported features for this entity type.
$warnings = $this->moderationInformation->getUnsupportedFeatures($this->entityType);
// Display message into the Ajax form returned.
if ($this->getRequest()->get(MainContentViewSubscriber::WRAPPER_FORMAT) == 'drupal_modal' && !empty($warnings)) {
$form['warnings'] = ['#type' => 'status_messages', '#weight' => -1];
}
// Set warning message.
foreach ($warnings as $warning) {
$this->messenger->addWarning($warning);
}
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#button_type' => 'primary',
'#value' => $this->t('Save'),
'#ajax' => [
'callback' => [$this, 'ajaxCallback'],
],
];
$form['actions']['cancel'] = [
'#type' => 'button',
'#value' => $this->t('Cancel'),
'#ajax' => [
'callback' => [$this, 'ajaxCallback'],
],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
foreach ($form_state->getValue('bundles') as $bundle_id => $checked) {
if ($checked) {
$this->workflow->getTypePlugin()->addEntityTypeAndBundle($this->entityType->id(), $bundle_id);
}
else {
$this->workflow->getTypePlugin()->removeEntityTypeAndBundle($this->entityType->id(), $bundle_id);
}
}
$this->workflow->save();
}
/**
* Ajax callback to close the modal and update the selected text.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* An ajax response object.
*/
public function ajaxCallback() {
$selected_bundles = [];
foreach ($this->bundleInfo->getBundleInfo($this->entityType->id()) as $bundle_id => $bundle) {
if ($this->workflow->getTypePlugin()->appliesToEntityTypeAndBundle($this->entityType->id(), $bundle_id)) {
$selected_bundles[$bundle_id] = $bundle['label'];
}
}
$selected_bundles_list = [
'#theme' => 'item_list',
'#items' => $selected_bundles,
'#context' => ['list_style' => 'comma-list'],
'#empty' => $this->t('none'),
];
$response = new AjaxResponse();
$response->addCommand(new CloseDialogCommand());
$response->addCommand(new HtmlCommand('#selected-' . $this->entityType->id(), $selected_bundles_list));
return $response;
}
/**
* Route title callback.
*/
public function getTitle(WorkflowInterface $workflow, $entity_type_id) {
$this->entityType = $this->entityTypeManager->getDefinition($entity_type_id);
$title = $this->t('Select the @entity_type types for the @workflow workflow', ['@entity_type' => $this->entityType->getLabel(), '@workflow' => $workflow->label()]);
if ($bundle_entity_type_id = $this->entityType->getBundleEntityType()) {
$title = $this->t('Select the @entity_type_plural_label for the @workflow workflow', ['@entity_type_plural_label' => $this->entityTypeManager->getDefinition($bundle_entity_type_id)->getPluralLabel(), '@workflow' => $workflow->label()]);
}
return $title;
}
}

View File

@@ -0,0 +1,159 @@
<?php
namespace Drupal\content_moderation\Form;
use Drupal\Component\Serialization\Json;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\workflows\Plugin\WorkflowTypeConfigureFormBase;
use Drupal\workflows\State;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* The content moderation WorkflowType configuration form.
*
* @see \Drupal\content_moderation\Plugin\WorkflowType\ContentModeration
*/
class ContentModerationConfigureForm extends WorkflowTypeConfigureFormBase implements ContainerInjectionInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The moderation info service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInfo;
/**
* The entity type bundle info service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $entityTypeBundleInfo;
/**
* Create an instance of ContentModerationConfigureForm.
*/
public function __construct(EntityTypeManagerInterface $entityTypeManager, ModerationInformationInterface $moderationInformation, EntityTypeBundleInfoInterface $entityTypeBundleInfo) {
$this->entityTypeManager = $entityTypeManager;
$this->moderationInfo = $moderationInformation;
$this->entityTypeBundleInfo = $entityTypeBundleInfo;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('content_moderation.moderation_information'),
$container->get('entity_type.bundle.info')
);
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$workflow = $form_state->getFormObject()->getEntity();
$header = [
'type' => $this->t('Items'),
'operations' => $this->t('Operations'),
];
$form['entity_types_container'] = [
'#type' => 'details',
'#title' => $this->t('This workflow applies to:'),
'#open' => TRUE,
];
$form['entity_types_container']['entity_types'] = [
'#type' => 'table',
'#header' => $header,
'#empty' => $this->t('There are no entity types.'),
];
$entity_types = $this->entityTypeManager->getDefinitions();
foreach ($entity_types as $entity_type) {
if (!$this->moderationInfo->canModerateEntitiesOfEntityType($entity_type)) {
continue;
}
$selected_bundles = [];
foreach ($this->entityTypeBundleInfo->getBundleInfo($entity_type->id()) as $bundle_id => $bundle) {
if ($this->workflowType->appliesToEntityTypeAndBundle($entity_type->id(), $bundle_id)) {
$selected_bundles[$bundle_id] = $bundle['label'];
}
}
$selected_bundles_list = [
'#theme' => 'item_list',
'#items' => $selected_bundles,
'#context' => ['list_style' => 'comma-list'],
'#empty' => $this->t('none'),
];
$form['entity_types_container']['entity_types'][$entity_type->id()] = [
'type' => [
'#type' => 'inline_template',
'#template' => '<strong>{{ label }}</strong><br><span id="selected-{{ entity_type_id }}">{{ selected_bundles }}</span>',
'#context' => [
'label' => $this->t('@bundle types', ['@bundle' => $entity_type->getLabel()]),
'entity_type_id' => $entity_type->id(),
'selected_bundles' => $selected_bundles_list,
],
],
'operations' => [
'#type' => 'operations',
'#links' => [
'select' => [
'title' => $this->t('Select'),
'url' => Url::fromRoute('content_moderation.workflow_type_edit_form', ['workflow' => $workflow->id(), 'entity_type_id' => $entity_type->id()]),
'attributes' => [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 880,
]),
],
],
],
],
];
}
$workflow_type_configuration = $this->workflowType->getConfiguration();
$form['workflow_settings'] = [
'#type' => 'details',
'#title' => $this->t('Workflow Settings'),
'#open' => TRUE,
];
$form['workflow_settings']['default_moderation_state'] = [
'#title' => $this->t('Default moderation state'),
'#type' => 'select',
'#required' => TRUE,
'#options' => array_map([State::class, 'labelCallback'], $this->workflowType->getStates()),
'#description' => $this->t('Select the state that new content will be assigned. This state will appear as the default in content forms and the available target states will be based on the transitions available from this state.'),
'#default_value' => $workflow_type_configuration['default_moderation_state'] ?? 'draft',
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$configuration = $this->workflowType->getConfiguration();
$configuration['default_moderation_state'] = $form_state->getValue(['workflow_settings', 'default_moderation_state']);
$this->workflowType->setConfiguration($configuration);
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Drupal\content_moderation\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\workflows\Plugin\WorkflowTypeStateFormBase;
use Drupal\workflows\StateInterface;
/**
* The content moderation state form.
*
* @see \Drupal\content_moderation\Plugin\WorkflowType\ContentModeration
*/
class ContentModerationStateForm extends WorkflowTypeStateFormBase {
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state, ?StateInterface $state = NULL) {
/** @var \Drupal\content_moderation\ContentModerationState $state */
$state = $form_state->get('state');
$is_required_state = isset($state) ? in_array($state->id(), $this->workflowType->getRequiredStates(), TRUE) : FALSE;
$form = [];
$form['published'] = [
'#type' => 'checkbox',
'#title' => $this->t('Published'),
'#description' => $this->t('When content reaches this state it should be published.'),
'#default_value' => isset($state) ? $state->isPublishedState() : FALSE,
'#disabled' => $is_required_state,
];
$form['default_revision'] = [
'#type' => 'checkbox',
'#title' => $this->t('Default revision'),
'#description' => $this->t('When content reaches this state it should be made the default revision; this is implied for published states.'),
'#default_value' => isset($state) ? $state->isDefaultRevisionState() : FALSE,
'#disabled' => $is_required_state,
// @todo Add form #state to force "make default" on when "published" is
// on for a state.
// @see https://www.drupal.org/node/2645614
];
return $form;
}
}

View File

@@ -0,0 +1,172 @@
<?php
namespace Drupal\content_moderation\Form;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\RevisionLogInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\content_moderation\StateTransitionValidationInterface;
use Drupal\workflows\Transition;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* The EntityModerationForm provides a simple UI for changing moderation state.
*
* @internal
*/
class EntityModerationForm extends FormBase {
/**
* The moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInfo;
/**
* The time service.
*
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected $time;
/**
* The moderation state transition validation service.
*
* @var \Drupal\content_moderation\StateTransitionValidationInterface
*/
protected $validation;
/**
* EntityModerationForm constructor.
*
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_info
* The moderation information service.
* @param \Drupal\content_moderation\StateTransitionValidationInterface $validation
* The moderation state transition validation service.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
*/
public function __construct(ModerationInformationInterface $moderation_info, StateTransitionValidationInterface $validation, TimeInterface $time) {
$this->moderationInfo = $moderation_info;
$this->validation = $validation;
$this->time = $time;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('content_moderation.moderation_information'),
$container->get('content_moderation.state_transition_validation'),
$container->get('datetime.time')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'content_moderation_entity_moderation_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ?ContentEntityInterface $entity = NULL) {
$current_state = $entity->moderation_state->value;
$workflow = $this->moderationInfo->getWorkflowForEntity($entity);
/** @var \Drupal\workflows\Transition[] $transitions */
$transitions = $this->validation->getValidTransitions($entity, $this->currentUser());
// Exclude self-transitions.
$transitions = array_filter($transitions, function (Transition $transition) use ($current_state) {
return $transition->to()->id() != $current_state;
});
$target_states = [];
foreach ($transitions as $transition) {
$target_states[$transition->to()->id()] = $transition->to()->label();
}
if (!count($target_states)) {
return $form;
}
if ($current_state) {
$form['current'] = [
'#type' => 'item',
'#title' => $this->t('Moderation state'),
'#markup' => $workflow->getTypePlugin()->getState($current_state)->label(),
];
}
// Persist the entity so we can access it in the submit handler.
$form_state->set('entity', $entity);
$form['new_state'] = [
'#type' => 'select',
'#title' => $this->t('Change to'),
'#options' => $target_states,
];
$form['revision_log'] = [
'#type' => 'textfield',
'#title' => $this->t('Log message'),
'#size' => 30,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Apply'),
];
$form['#theme'] = ['entity_moderation_form'];
$form['#attached']['library'][] = 'content_moderation/content_moderation';
// Moderating an entity is allowed in a workspace.
$form_state->set('workspace_safe', TRUE);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $form_state->get('entity');
/** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
$storage = \Drupal::entityTypeManager()->getStorage($entity->getEntityTypeId());
$entity = $storage->createRevision($entity, $entity->isDefaultRevision());
$new_state = $form_state->getValue('new_state');
$entity->set('moderation_state', $new_state);
if ($entity instanceof RevisionLogInterface) {
$entity->setRevisionCreationTime($this->time->getRequestTime());
$entity->setRevisionLogMessage($form_state->getValue('revision_log'));
$entity->setRevisionUserId($this->currentUser()->id());
}
$entity->save();
$this->messenger()->addStatus($this->t('The moderation state has been updated.'));
$new_state = $this->moderationInfo->getWorkflowForEntity($entity)->getTypePlugin()->getState($new_state);
// The page we're on likely won't be visible if we just set the entity to
// the default state, as we hide that latest-revision tab if there is no
// pending revision. Redirect to the canonical URL instead, since that will
// still exist.
if ($new_state->isDefaultRevisionState()) {
$form_state->setRedirectUrl($entity->toUrl('canonical'));
}
}
}

View File

@@ -0,0 +1,130 @@
<?php
namespace Drupal\content_moderation;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\RedirectDestinationInterface;
use Drupal\node\NodeListBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines a class to build a listing of moderated node entities.
*/
class ModeratedNodeListBuilder extends NodeListBuilder {
/**
* The entity storage class.
*
* @var \Drupal\Core\Entity\RevisionableStorageInterface
*/
protected $storage;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a new ModeratedNodeListBuilder object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
* @param \Drupal\Core\Entity\EntityStorageInterface $storage
* The entity storage class.
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter service.
* @param \Drupal\Core\Routing\RedirectDestinationInterface $redirect_destination
* The redirect destination service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, DateFormatterInterface $date_formatter, RedirectDestinationInterface $redirect_destination, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($entity_type, $storage, $date_formatter, $redirect_destination);
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
$entity_type_manager = $container->get('entity_type.manager');
return new static(
$entity_type,
$entity_type_manager->getStorage($entity_type->id()),
$container->get('date.formatter'),
$container->get('redirect.destination'),
$entity_type_manager
);
}
/**
* {@inheritdoc}
*/
public function load() {
$revision_ids = $this->getEntityRevisionIds();
return $this->storage->loadMultipleRevisions($revision_ids);
}
/**
* Loads entity revision IDs using a pager sorted by the entity revision ID.
*
* @return array
* An array of entity revision IDs.
*/
protected function getEntityRevisionIds() {
$query = $this->entityTypeManager->getStorage('content_moderation_state')->getAggregateQuery()
->accessCheck(TRUE)
->aggregate('content_entity_id', 'MAX')
->groupBy('content_entity_revision_id')
->condition('content_entity_type_id', $this->entityTypeId)
->condition('moderation_state', 'published', '<>')
->sort('content_entity_revision_id', 'DESC');
// Only add the pager if a limit is specified.
if ($this->limit) {
$query->pager($this->limit);
}
$result = $query->execute();
return $result ? array_column($result, 'content_entity_revision_id') : [];
}
/**
* {@inheritdoc}
*/
public function buildHeader() {
$header = parent::buildHeader();
$header['status'] = $this->t('Moderation state');
return $header;
}
/**
* {@inheritdoc}
*/
public function buildRow(EntityInterface $entity) {
$row = parent::buildRow($entity);
$row['status'] = $entity->moderation_state->value;
return $row;
}
/**
* {@inheritdoc}
*/
public function render() {
$build = parent::render();
$build['table']['#empty'] = $this->t('There is no moderated @label yet. Only pending versions of @label, such as drafts, are listed here.', ['@label' => $this->entityType->getLabel()]);
return $build;
}
}

View File

@@ -0,0 +1,256 @@
<?php
namespace Drupal\content_moderation;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\TypedData\TranslatableInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* General service for moderation-related questions about Entity API.
*/
class ModerationInformation implements ModerationInformationInterface {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The bundle information service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $bundleInfo;
/**
* Creates a new ModerationInformation instance.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info
* The bundle information service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $bundle_info) {
$this->entityTypeManager = $entity_type_manager;
$this->bundleInfo = $bundle_info;
}
/**
* {@inheritdoc}
*/
public function isModeratedEntity(EntityInterface $entity) {
if (!$entity instanceof ContentEntityInterface) {
return FALSE;
}
if (!$this->shouldModerateEntitiesOfBundle($entity->getEntityType(), $entity->bundle())) {
return FALSE;
}
return $this->entityTypeManager->getHandler($entity->getEntityTypeId(), 'moderation')->isModeratedEntity($entity);
}
/**
* {@inheritdoc}
*/
public function isModeratedEntityType(EntityTypeInterface $entity_type) {
$bundles = $this->bundleInfo->getBundleInfo($entity_type->id());
return !empty(array_column($bundles, 'workflow'));
}
/**
* {@inheritdoc}
*/
public function canModerateEntitiesOfEntityType(EntityTypeInterface $entity_type) {
return $entity_type->hasHandlerClass('moderation');
}
/**
* {@inheritdoc}
*/
public function shouldModerateEntitiesOfBundle(EntityTypeInterface $entity_type, $bundle) {
if ($this->canModerateEntitiesOfEntityType($entity_type)) {
$bundles = $this->bundleInfo->getBundleInfo($entity_type->id());
return isset($bundles[$bundle]['workflow']);
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function getDefaultRevisionId($entity_type_id, $entity_id) {
if ($storage = $this->entityTypeManager->getStorage($entity_type_id)) {
$result = $storage->getQuery()
->currentRevision()
->condition($this->entityTypeManager->getDefinition($entity_type_id)->getKey('id'), $entity_id)
// No access check is performed here since this is an API function and
// should return the same ID regardless of the current user.
->accessCheck(FALSE)
->execute();
if ($result) {
return key($result);
}
}
}
/**
* {@inheritdoc}
*/
public function getAffectedRevisionTranslation(ContentEntityInterface $entity) {
foreach ($entity->getTranslationLanguages() as $language) {
$translation = $entity->getTranslation($language->getId());
if (!$translation->isDefaultRevision() && $translation->isRevisionTranslationAffected()) {
return $translation;
}
}
}
/**
* {@inheritdoc}
*/
public function hasPendingRevision(ContentEntityInterface $entity) {
$result = FALSE;
if ($this->isModeratedEntity($entity)) {
/** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
$storage = $this->entityTypeManager->getStorage($entity->getEntityTypeId());
$latest_revision_id = $storage->getLatestTranslationAffectedRevisionId($entity->id(), $entity->language()->getId());
$default_revision_id = $entity->isDefaultRevision() && !$entity->isNewRevision() && ($revision_id = $entity->getRevisionId()) ?
$revision_id : $this->getDefaultRevisionId($entity->getEntityTypeId(), $entity->id());
if ($latest_revision_id !== NULL && $latest_revision_id != $default_revision_id) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $latest_revision */
$latest_revision = $storage->loadRevision($latest_revision_id);
$result = !$latest_revision->wasDefaultRevision();
}
}
return $result;
}
/**
* {@inheritdoc}
*/
public function isLiveRevision(ContentEntityInterface $entity) {
$workflow = $this->getWorkflowForEntity($entity);
return $entity->isLatestRevision()
&& $entity->isDefaultRevision()
&& $entity->moderation_state->value
&& $workflow->getTypePlugin()->getState($entity->moderation_state->value)->isPublishedState();
}
/**
* {@inheritdoc}
*/
public function isDefaultRevisionPublished(ContentEntityInterface $entity) {
$workflow = $this->getWorkflowForEntity($entity);
$default_revision = $this->entityTypeManager->getStorage($entity->getEntityTypeId())->load($entity->id());
// If no default revision could be loaded, the entity has not yet been
// saved. In this case the moderation_state of the unsaved entity can be
// used, since once saved it will become the default.
$default_revision = $default_revision ?: $entity;
// Ensure we are checking all translations of the default revision.
if ($default_revision instanceof TranslatableInterface && $default_revision->isTranslatable()) {
// Loop through each language that has a translation.
foreach ($default_revision->getTranslationLanguages() as $language) {
// Load the translated revision.
$translation = $default_revision->getTranslation($language->getId());
// If the moderation state is empty, it was not stored yet so no point
// in doing further work.
$moderation_state = $translation->moderation_state->value;
if (!$moderation_state) {
continue;
}
// Return TRUE if a translation with a published state is found.
if ($workflow->getTypePlugin()->getState($moderation_state)->isPublishedState()) {
return TRUE;
}
}
}
return $workflow->getTypePlugin()->getState($default_revision->moderation_state->value)->isPublishedState();
}
/**
* {@inheritdoc}
*/
public function getWorkflowForEntity(ContentEntityInterface $entity) {
return $this->getWorkflowForEntityTypeAndBundle($entity->getEntityTypeId(), $entity->bundle());
}
/**
* {@inheritdoc}
*/
public function getWorkflowForEntityTypeAndBundle($entity_type_id, $bundle_id) {
$bundles = $this->bundleInfo->getBundleInfo($entity_type_id);
if (isset($bundles[$bundle_id]['workflow'])) {
return $this->entityTypeManager->getStorage('workflow')->load($bundles[$bundle_id]['workflow']);
}
return NULL;
}
/**
* {@inheritdoc}
*/
public function getUnsupportedFeatures(EntityTypeInterface $entity_type) {
$features = [];
// Test if entity is publishable.
if (!$entity_type->entityClassImplements(EntityPublishedInterface::class)) {
$features['publishing'] = $this->t("@entity_type_plural_label do not support publishing statuses. For example, even after transitioning from a published workflow state to an unpublished workflow state they will still be visible to site visitors.", ['@entity_type_plural_label' => $entity_type->getCollectionLabel()]);
}
return $features;
}
/**
* {@inheritdoc}
*/
public function getOriginalState(ContentEntityInterface $entity) {
$state = NULL;
$workflow_type = $this->getWorkflowForEntity($entity)->getTypePlugin();
if (!$entity->isNew() && !$this->isFirstTimeModeration($entity)) {
/** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
$storage = $this->entityTypeManager->getStorage($entity->getEntityTypeId());
/** @var \Drupal\Core\Entity\ContentEntityInterface $original_entity */
$original_entity = $storage->loadRevision($entity->getLoadedRevisionId());
if (!$entity->isDefaultTranslation() && $original_entity->hasTranslation($entity->language()->getId())) {
$original_entity = $original_entity->getTranslation($entity->language()->getId());
}
if ($workflow_type->hasState($original_entity->moderation_state->value)) {
$state = $workflow_type->getState($original_entity->moderation_state->value);
}
}
return $state ?: $workflow_type->getInitialState($entity);
}
/**
* Determines if this entity is being moderated for the first time.
*
* If the previous version of the entity has no moderation state, we assume
* that means it predates the presence of moderation states.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity being moderated.
*
* @return bool
* TRUE if this is the entity's first time being moderated, FALSE otherwise.
*/
protected function isFirstTimeModeration(ContentEntityInterface $entity) {
/** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
$storage = $this->entityTypeManager->getStorage($entity->getEntityTypeId());
$original_entity = $storage->loadRevision($storage->getLatestRevisionId($entity->id()));
if ($original_entity) {
$original_id = $original_entity->moderation_state;
}
return !($entity->moderation_state && $original_entity && $original_id);
}
}

View File

@@ -0,0 +1,183 @@
<?php
namespace Drupal\content_moderation;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
/**
* Interface for moderation_information service.
*/
interface ModerationInformationInterface {
/**
* Determines if an entity is moderated.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity we may be moderating.
*
* @return bool
* TRUE if this entity is moderated, FALSE otherwise.
*/
public function isModeratedEntity(EntityInterface $entity);
/**
* Determines if an entity type can have moderated entities.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* An entity type object.
*
* @return bool
* TRUE if this entity type can have moderated entities, FALSE otherwise.
*/
public function canModerateEntitiesOfEntityType(EntityTypeInterface $entity_type);
/**
* Determines if an entity type/bundle entities should be moderated.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition to check.
* @param string $bundle
* The bundle to check.
*
* @return bool
* TRUE if an entity type/bundle entities should be moderated, FALSE
* otherwise.
*/
public function shouldModerateEntitiesOfBundle(EntityTypeInterface $entity_type, $bundle);
/**
* Determines if an entity type has at least one moderated bundle.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition to check.
*
* @return bool
* TRUE if an entity type has a moderated bundle, FALSE otherwise.
*/
public function isModeratedEntityType(EntityTypeInterface $entity_type);
/**
* Returns the revision ID of the default revision for the specified entity.
*
* @param string $entity_type_id
* The entity type ID.
* @param int $entity_id
* The entity ID.
*
* @return int
* The revision ID of the default revision, or NULL if the entity was
* not found.
*/
public function getDefaultRevisionId($entity_type_id, $entity_id);
/**
* Returns the revision translation affected translation of a revision.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The content entity.
*
* @return \Drupal\Core\Entity\ContentEntityInterface
* The revision translation affected translation.
*/
public function getAffectedRevisionTranslation(ContentEntityInterface $entity);
/**
* Determines if a pending revision exists for the specified entity.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity which may or may not have a pending revision.
*
* @return bool
* TRUE if this entity has pending revisions available, FALSE otherwise.
*/
public function hasPendingRevision(ContentEntityInterface $entity);
/**
* Determines if an entity is "live".
*
* A "live" entity revision is one whose latest revision is also the default,
* and whose moderation state, if any, is a published state.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity to check.
*
* @return bool
* TRUE if the specified entity is a live revision, FALSE otherwise.
*/
public function isLiveRevision(ContentEntityInterface $entity);
/**
* Determines if the default revision for the given entity is published.
*
* The default revision is the same as the entity retrieved by "default" from
* the storage handler. If the entity is translated, check if any of the
* translations are published.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity being saved.
*
* @return bool
* TRUE if the default revision is published. FALSE otherwise.
*/
public function isDefaultRevisionPublished(ContentEntityInterface $entity);
/**
* Gets the workflow for the given content entity.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The content entity to get the workflow for.
*
* @return \Drupal\workflows\WorkflowInterface|null
* The workflow entity. NULL if there is no workflow.
*/
public function getWorkflowForEntity(ContentEntityInterface $entity);
/**
* Gets the workflow for the given entity type and bundle.
*
* @param string $entity_type_id
* The entity type ID.
* @param string $bundle_id
* The entity bundle ID.
*
* @return \Drupal\workflows\WorkflowInterface|null
* The associated workflow. NULL if there is no workflow.
*/
public function getWorkflowForEntityTypeAndBundle($entity_type_id, $bundle_id);
/**
* Gets unsupported features for a given entity type.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type to get the unsupported features for.
*
* @return array
* An array of unsupported features for this entity type.
*/
public function getUnsupportedFeatures(EntityTypeInterface $entity_type);
/**
* Gets the original or initial state of the given entity.
*
* When a state is being validated, the original state is used to validate
* that a valid transition exists for target state and the user has access
* to the transition between those two states. If the entity has been
* moderated before, we can load the original unmodified revision and
* translation for this state.
*
* If the entity is new we need to load the initial state from the workflow.
* Even if a value was assigned to the moderation_state field, the initial
* state is used to compute an appropriate transition for the purposes of
* validation.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The content entity to get the workflow for.
*
* @return \Drupal\content_moderation\ContentModerationState
* The original or default moderation state.
*/
public function getOriginalState(ContentEntityInterface $entity);
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Drupal\content_moderation;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\workflows\Entity\Workflow;
use Drupal\workflows\State;
/**
* Defines a class for dynamic permissions based on transitions.
*
* @internal
*/
class Permissions {
use StringTranslationTrait;
/**
* Returns an array of transition permissions.
*
* @return array
* The transition permissions.
*/
public function transitionPermissions() {
$permissions = [];
/** @var \Drupal\workflows\WorkflowInterface $workflow */
foreach (Workflow::loadMultipleByType('content_moderation') as $workflow) {
foreach ($workflow->getTypePlugin()->getTransitions() as $transition) {
$permissions['use ' . $workflow->id() . ' transition ' . $transition->id()] = [
'title' => $this->t('%workflow workflow: Use %transition transition.', [
'%workflow' => $workflow->label(),
'%transition' => $transition->label(),
]),
'description' => $this->formatPlural(
count($transition->from()),
'Move content from %from state to %to state.',
'Move content from %from states to %to state.', [
'%from' => implode(', ', array_map([State::class, 'labelCallback'], $transition->from())),
'%to' => $transition->to()->label(),
]
),
'dependencies' => [
$workflow->getConfigDependencyKey() => [$workflow->getConfigDependencyName()],
],
];
}
}
return $permissions;
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace Drupal\content_moderation\Plugin\Action;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Action\Plugin\Action\PublishAction;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\content_moderation\ModerationInformationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Alternate action plugin that can opt-out of modifying moderated entities.
*
* @see \Drupal\Core\Action\Plugin\Action\PublishAction
*/
class ModerationOptOutPublish extends PublishAction implements ContainerFactoryPluginInterface {
/**
* Moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInfo;
/**
* Bundle info service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $bundleInfo;
/**
* Messenger service.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* ModerationOptOutPublish constructor.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_info
* The moderation information service.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info
* Bundle info service.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* Messenger service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModerationInformationInterface $moderation_info, EntityTypeBundleInfoInterface $bundle_info, MessengerInterface $messenger) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager);
$this->moderationInfo = $moderation_info;
$this->bundleInfo = $bundle_info;
$this->messenger = $messenger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration, $plugin_id, $plugin_definition,
$container->get('entity_type.manager'),
$container->get('content_moderation.moderation_information'),
$container->get('entity_type.bundle.info'),
$container->get('messenger')
);
}
/**
* {@inheritdoc}
*/
public function access($entity, ?AccountInterface $account = NULL, $return_as_object = FALSE) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
if ($entity && $this->moderationInfo->isModeratedEntity($entity)) {
$bundle_info = $this->bundleInfo->getBundleInfo($entity->getEntityTypeId());
$bundle_label = $bundle_info[$entity->bundle()]['label'];
$this->messenger->addWarning($this->t("@bundle @label were skipped as they are under moderation and may not be directly published.", [
'@bundle' => $bundle_label,
'@label' => $entity->getEntityType()->getPluralLabel(),
]));
$result = AccessResult::forbidden('Cannot directly publish moderated entities.');
return $return_as_object ? $result : $result->isAllowed();
}
return parent::access($entity, $account, $return_as_object);
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace Drupal\content_moderation\Plugin\Action;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Action\Plugin\Action\UnpublishAction;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\content_moderation\ModerationInformationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Alternate action plugin that can opt-out of modifying moderated entities.
*
* @see \Drupal\Core\Action\Plugin\Action\UnpublishAction
*/
class ModerationOptOutUnpublish extends UnpublishAction {
/**
* Moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInfo;
/**
* Bundle info service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $bundleInfo;
/**
* Messenger service.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* ModerationOptOutUnpublish constructor.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_info
* The moderation information service.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info
* Bundle info service.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* Messenger service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModerationInformationInterface $moderation_info, EntityTypeBundleInfoInterface $bundle_info, MessengerInterface $messenger) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager);
$this->moderationInfo = $moderation_info;
$this->bundleInfo = $bundle_info;
$this->messenger = $messenger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration, $plugin_id, $plugin_definition,
$container->get('entity_type.manager'),
$container->get('content_moderation.moderation_information'),
$container->get('entity_type.bundle.info'),
$container->get('messenger')
);
}
/**
* {@inheritdoc}
*/
public function access($entity, ?AccountInterface $account = NULL, $return_as_object = FALSE) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
if ($entity && $this->moderationInfo->isModeratedEntity($entity)) {
$bundle_info = $this->bundleInfo->getBundleInfo($entity->getEntityTypeId());
$bundle_label = $bundle_info[$entity->bundle()]['label'];
$this->messenger->addWarning($this->t("@bundle @label were skipped as they are under moderation and may not be directly unpublished.", [
'@bundle' => $bundle_label,
'@label' => $entity->getEntityType()->getPluralLabel(),
]));
$result = AccessResult::forbidden('Cannot directly unpublish moderated entities.');
return $return_as_object ? $result : $result->isAllowed();
}
return parent::access($entity, $account, $return_as_object);
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace Drupal\content_moderation\Plugin\ConfigAction;
use Drupal\content_moderation\Plugin\WorkflowType\ContentModerationInterface;
use Drupal\Core\Config\Action\Attribute\ConfigAction;
use Drupal\Core\Config\Action\ConfigActionException;
use Drupal\Core\Config\Action\ConfigActionPluginInterface;
use Drupal\Core\Config\ConfigManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\workflows\WorkflowInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
#[ConfigAction(
id: 'add_moderation',
entity_types: ['workflow'],
deriver: AddModerationDeriver::class,
)]
final class AddModeration implements ConfigActionPluginInterface, ContainerFactoryPluginInterface {
public function __construct(
private readonly ConfigManagerInterface $configManager,
private readonly EntityTypeManagerInterface $entityTypeManager,
private readonly string $pluginId,
private readonly string $targetEntityType,
) {}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
assert(is_array($plugin_definition));
$target_entity_type = $plugin_definition['target_entity_type'];
return new static(
$container->get(ConfigManagerInterface::class),
$container->get(EntityTypeManagerInterface::class),
$plugin_id,
$target_entity_type,
);
}
/**
* {@inheritdoc}
*/
public function apply(string $configName, mixed $value): void {
$workflow = $this->configManager->loadConfigEntityByName($configName);
assert($workflow instanceof WorkflowInterface);
$plugin = $workflow->getTypePlugin();
if (!$plugin instanceof ContentModerationInterface) {
throw new ConfigActionException("The $this->pluginId config action only works with Content Moderation workflows.");
}
assert($value === '*' || is_array($value));
if ($value === '*') {
/** @var \Drupal\Core\Entity\EntityTypeInterface $definition */
$definition = $this->entityTypeManager->getDefinition($this->targetEntityType);
/** @var string $bundle_entity_type */
$bundle_entity_type = $definition->getBundleEntityType();
$value = $this->entityTypeManager->getStorage($bundle_entity_type)
->getQuery()
->accessCheck(FALSE)
->execute();
}
foreach ($value as $bundle) {
$plugin->addEntityTypeAndBundle($this->targetEntityType, $bundle);
}
$workflow->save();
}
}

View File

@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace Drupal\content_moderation\Plugin\ConfigAction;
// cspell:ignore inflector
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\String\Inflector\EnglishInflector;
final class AddModerationDeriver extends DeriverBase implements ContainerDeriverInterface {
use StringTranslationTrait;
public function __construct(
private readonly EntityTypeManagerInterface $entityTypeManager,
) {}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id): static {
return new static(
$container->get(EntityTypeManagerInterface::class),
);
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
$inflector = new EnglishInflector();
foreach ($this->entityTypeManager->getDefinitions() as $id => $entity_type) {
if ($bundle_entity_type = $entity_type->getBundleEntityType()) {
/** @var \Drupal\Core\Entity\EntityTypeInterface $bundle_entity_type */
$bundle_entity_type = $this->entityTypeManager->getDefinition($bundle_entity_type);
// Convert unique plugin IDs, like `taxonomy_vocabulary`, into strings
// like `TaxonomyVocabulary`.
$suffix = Container::camelize($bundle_entity_type->id());
[$suffix] = $inflector->pluralize($suffix);
$this->derivatives["add{$suffix}"] = [
'target_entity_type' => $id,
'admin_label' => $this->t('Add moderation to all @bundles', [
'@bundles' => $bundle_entity_type->getPluralLabel() ?: $bundle_entity_type->id(),
]),
] + $base_plugin_definition;
}
}
return parent::getDerivativeDefinitions($base_plugin_definition);
}
}

View File

@@ -0,0 +1,118 @@
<?php
namespace Drupal\content_moderation\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\RouterInterface;
/**
* Generates moderation-related local tasks.
*/
class DynamicLocalTasks extends DeriverBase implements ContainerDeriverInterface {
use StringTranslationTrait;
/**
* The base plugin ID.
*
* @var string
*/
protected $basePluginId;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInfo;
/**
* The router.
*
* @var \Symfony\Component\Routing\RouterInterface
*/
protected $router;
/**
* Creates a FieldUiLocalTask object.
*
* @param string $base_plugin_id
* The base plugin ID.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The translation manager.
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_information
* The moderation information service.
* @param \Symfony\Component\Routing\RouterInterface $router
* The router.
*/
public function __construct($base_plugin_id, EntityTypeManagerInterface $entity_type_manager, TranslationInterface $string_translation, ModerationInformationInterface $moderation_information, RouterInterface $router) {
$this->entityTypeManager = $entity_type_manager;
$this->stringTranslation = $string_translation;
$this->basePluginId = $base_plugin_id;
$this->moderationInfo = $moderation_information;
$this->router = $router;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static(
$base_plugin_id,
$container->get('entity_type.manager'),
$container->get('string_translation'),
$container->get('content_moderation.moderation_information'),
$container->get('router')
);
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
$this->derivatives = [];
// Add the moderated content task if the route exists.
if ($this->router->getRouteCollection()->get('content_moderation.admin_moderated_content') !== NULL) {
$this->derivatives['content_moderation.moderated_content'] = [
'route_name' => 'content_moderation.admin_moderated_content',
'title' => $this->t('Moderated content'),
'parent_id' => 'system.admin_content',
'weight' => 1,
];
}
// Add the latest version tab to entities.
$latest_version_entities = array_filter($this->entityTypeManager->getDefinitions(), function (EntityTypeInterface $type) {
return $this->moderationInfo->canModerateEntitiesOfEntityType($type) && $type->hasLinkTemplate('latest-version');
});
foreach ($latest_version_entities as $entity_type_id => $entity_type) {
$this->derivatives["$entity_type_id.latest_version_tab"] = [
'route_name' => "entity.$entity_type_id.latest_version",
'title' => $this->t('Latest version'),
'base_route' => "entity.$entity_type_id.canonical",
'weight' => 1,
] + $base_plugin_definition;
}
return $this->derivatives;
}
}

View File

@@ -0,0 +1,77 @@
<?php
namespace Drupal\content_moderation\Plugin\Field\FieldFormatter;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of the 'content_moderation_state' formatter.
*/
#[FieldFormatter(
id: 'content_moderation_state',
label: new TranslatableMarkup('Content moderation state'),
field_types: [
'string',
],
)]
class ContentModerationStateFormatter extends FormatterBase {
/**
* The moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInformation;
/**
* Create an instance of ContentModerationStateFormatter.
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, ModerationInformationInterface $moderation_information) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->moderationInformation = $moderation_information;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['label'],
$configuration['view_mode'],
$configuration['third_party_settings'],
$container->get('content_moderation.moderation_information')
);
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$workflow = $this->moderationInformation->getWorkflowForEntity($items->getEntity());
foreach ($items as $delta => $item) {
$elements[$delta] = [
'#markup' => $workflow->getTypePlugin()->getState($item->value)->label(),
];
}
return $elements;
}
/**
* {@inheritdoc}
*/
public static function isApplicable(FieldDefinitionInterface $field_definition) {
return $field_definition->getName() === 'moderation_state' && $field_definition->getTargetEntityTypeId() !== 'content_moderation_state';
}
}

View File

@@ -0,0 +1,209 @@
<?php
namespace Drupal\content_moderation\Plugin\Field\FieldWidget;
use Drupal\content_moderation\Plugin\Field\ModerationStateFieldItemList;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\Attribute\FieldWidget;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsSelectWidget;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\content_moderation\ModerationInformation;
use Drupal\content_moderation\StateTransitionValidationInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of the 'moderation_state_default' widget.
*/
#[FieldWidget(
id: 'moderation_state_default',
label: new TranslatableMarkup('Moderation state'),
field_types: ['string'],
)]
class ModerationStateWidget extends OptionsSelectWidget {
/**
* Current user service.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* Moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformation
*/
protected $moderationInformation;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Moderation state transition validation service.
*
* @var \Drupal\content_moderation\StateTransitionValidationInterface
*/
protected $validator;
/**
* Constructs a new ModerationStateWidget object.
*
* @param string $plugin_id
* Plugin id.
* @param mixed $plugin_definition
* Plugin definition.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* Field definition.
* @param array $settings
* Field settings.
* @param array $third_party_settings
* Third party settings.
* @param \Drupal\Core\Session\AccountInterface $current_user
* Current user service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* Entity type manager.
* @param \Drupal\content_moderation\ModerationInformation $moderation_information
* Moderation information service.
* @param \Drupal\content_moderation\StateTransitionValidationInterface $validator
* Moderation state transition validation service.
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, AccountInterface $current_user, EntityTypeManagerInterface $entity_type_manager, ModerationInformation $moderation_information, StateTransitionValidationInterface $validator) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
$this->entityTypeManager = $entity_type_manager;
$this->currentUser = $current_user;
$this->moderationInformation = $moderation_information;
$this->validator = $validator;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['third_party_settings'],
$container->get('current_user'),
$container->get('entity_type.manager'),
$container->get('content_moderation.moderation_information'),
$container->get('content_moderation.state_transition_validation')
);
}
/**
* {@inheritdoc}
*/
public function form(FieldItemListInterface $items, array &$form, FormStateInterface $form_state, $get_delta = NULL) {
$entity = $items->getEntity();
if (!$this->moderationInformation->isModeratedEntity($entity)) {
return [];
}
return parent::form($items, $form, $form_state, $get_delta);
}
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $original_entity = $items->getEntity();
$default = $this->moderationInformation->getOriginalState($entity);
// If the entity already exists, grab the most recent revision and load it.
// The moderation state of the saved revision will be used to display the
// current state as well determine the appropriate transitions.
if (!$entity->isNew()) {
/** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
$storage = $this->entityTypeManager->getStorage($entity->getEntityTypeId());
/** @var \Drupal\Core\Entity\ContentEntityInterface $original_entity */
$original_entity = $storage->loadRevision($entity->getLoadedRevisionId());
if (!$entity->isDefaultTranslation() && $original_entity->hasTranslation($entity->language()->getId())) {
$original_entity = $original_entity->getTranslation($entity->language()->getId());
}
}
// For a new entity, ensure the moderation state of the original entity is
// always the default state. Despite the entity being unsaved, it may have
// previously been set to a new target state, for example previewed entities
// are retrieved from temporary storage with field values set.
else {
$original_entity->set('moderation_state', $default->id());
}
/** @var \Drupal\workflows\Transition[] $transitions */
$transitions = $this->validator->getValidTransitions($original_entity, $this->currentUser);
$transition_labels = [];
$default_value = $items->value;
foreach ($transitions as $transition) {
$transition_to_state = $transition->to();
$transition_labels[$transition_to_state->id()] = $transition_to_state->label();
if ($default->id() === $transition_to_state->id()) {
$default_value = $default->id();
}
}
$element += [
'#type' => 'container',
'current' => [
'#type' => 'item',
'#title' => $this->t('Current state'),
'#markup' => $default->label(),
'#access' => !$entity->isNew(),
'#wrapper_attributes' => [
'class' => ['container-inline'],
],
],
'state' => [
'#type' => 'select',
'#title' => $entity->isNew() ? $this->t('Save as') : $this->t('Change to'),
'#key_column' => $this->column,
'#options' => $transition_labels,
'#default_value' => $default_value,
'#access' => !empty($transition_labels),
'#wrapper_attributes' => [
'class' => ['container-inline'],
],
],
];
$element['#element_validate'][] = [static::class, 'validateElement'];
return $element;
}
/**
* {@inheritdoc}
*/
public static function validateElement(array $element, FormStateInterface $form_state) {
$form_state->setValueForElement($element, [$element['state']['#key_column'] => $element['state']['#value']]);
}
/**
* {@inheritdoc}
*/
public static function isApplicable(FieldDefinitionInterface $field_definition) {
return is_a($field_definition->getClass(), ModerationStateFieldItemList::class, TRUE);
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
$dependencies = parent::calculateDependencies();
if ($workflow = $this->moderationInformation->getWorkflowForEntityTypeAndBundle($this->fieldDefinition->getTargetEntityTypeId(), $this->fieldDefinition->getTargetBundle())) {
$dependencies[$workflow->getConfigDependencyKey()][] = $workflow->getConfigDependencyName();
}
return $dependencies;
}
}

View File

@@ -0,0 +1,186 @@
<?php
namespace Drupal\content_moderation\Plugin\Field;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Field\FieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;
/**
* A computed field that provides a content entity's moderation state.
*
* It links content entities to a moderation state configuration entity via a
* moderation state content entity.
*/
class ModerationStateFieldItemList extends FieldItemList {
use ComputedItemListTrait {
get as traitGet;
}
/**
* {@inheritdoc}
*/
protected function computeValue() {
$moderation_state = $this->getModerationStateId();
// Do not store NULL values, in the case where an entity does not have a
// moderation workflow associated with it, we do not create list items for
// the computed field.
if ($moderation_state) {
// An entity can only have a single moderation state.
$this->list[0] = $this->createItem(0, $moderation_state);
}
}
/**
* Gets the moderation state ID linked to a content entity revision.
*
* @return string|null
* The moderation state ID linked to a content entity revision.
*/
protected function getModerationStateId() {
$entity = $this->getEntity();
/** @var \Drupal\content_moderation\ModerationInformationInterface $moderation_info */
$moderation_info = \Drupal::service('content_moderation.moderation_information');
if (!$moderation_info->shouldModerateEntitiesOfBundle($entity->getEntityType(), $entity->bundle())) {
return NULL;
}
// Existing entities will have a corresponding content_moderation_state
// entity associated with them.
if (!$entity->isNew() && $content_moderation_state = $this->loadContentModerationStateRevision($entity)) {
return $content_moderation_state->moderation_state->value;
}
// It is possible that the bundle does not exist at this point. For example,
// the node type form creates a fake Node entity to get default values.
// @see \Drupal\node\NodeTypeForm::form()
$workflow = $moderation_info->getWorkFlowForEntity($entity);
return $workflow ? $workflow->getTypePlugin()->getInitialState($entity)->id() : NULL;
}
/**
* Load the content moderation state revision associated with an entity.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity the content moderation state entity will be loaded from.
*
* @return \Drupal\content_moderation\Entity\ContentModerationStateInterface|null
* The content_moderation_state revision or FALSE if none exists.
*/
protected function loadContentModerationStateRevision(ContentEntityInterface $entity) {
$moderation_info = \Drupal::service('content_moderation.moderation_information');
$content_moderation_storage = \Drupal::entityTypeManager()->getStorage('content_moderation_state');
$revisions = $content_moderation_storage->getQuery()
->accessCheck(FALSE)
->condition('content_entity_type_id', $entity->getEntityTypeId())
->condition('content_entity_id', $entity->id())
// Ensure the correct revision is loaded in scenarios where a revision is
// being reverted.
->condition('content_entity_revision_id', $entity->isNewRevision() ? $entity->getLoadedRevisionId() : $entity->getRevisionId())
->condition('workflow', $moderation_info->getWorkflowForEntity($entity)->id())
->condition('langcode', $entity->language()->getId())
->allRevisions()
->sort('revision_id', 'DESC')
->execute();
if (empty($revisions)) {
return NULL;
}
/** @var \Drupal\content_moderation\Entity\ContentModerationStateInterface $content_moderation_state */
$content_moderation_state = $content_moderation_storage->loadRevision(key($revisions));
if ($entity->getEntityType()->hasKey('langcode')) {
$langcode = $entity->language()->getId();
if (!$content_moderation_state->hasTranslation($langcode)) {
$content_moderation_state->addTranslation($langcode, $content_moderation_state->toArray());
}
if ($content_moderation_state->language()->getId() !== $langcode) {
$content_moderation_state = $content_moderation_state->getTranslation($langcode);
}
}
return $content_moderation_state;
}
/**
* {@inheritdoc}
*/
public function get($index) {
if ($index !== 0) {
throw new \InvalidArgumentException('An entity can not have multiple moderation states at the same time.');
}
return $this->traitGet($index);
}
/**
* {@inheritdoc}
*/
public function onChange($delta) {
$this->updateModeratedEntity($this->list[$delta]->value);
parent::onChange($delta);
}
/**
* {@inheritdoc}
*/
public function setValue($values, $notify = TRUE) {
parent::setValue($values, $notify);
$this->valueComputed = TRUE;
// If the parent created a field item and if the parent should be notified
// about the change (e.g. this is not initialized with the current value),
// update the moderated entity.
if (isset($this->list[0]) && $notify) {
$this->updateModeratedEntity($this->list[0]->value);
}
}
/**
* Updates the default revision flag and the publishing status of the entity.
*
* @param string $moderation_state_id
* The ID of the new moderation state.
*/
protected function updateModeratedEntity($moderation_state_id) {
$entity = $this->getEntity();
/** @var \Drupal\content_moderation\ModerationInformationInterface $content_moderation_info */
$content_moderation_info = \Drupal::service('content_moderation.moderation_information');
$workflow = $content_moderation_info->getWorkflowForEntity($entity);
// Change the entity's default revision flag and the publishing status only
// if the new workflow state is a valid one.
if ($workflow && $workflow->getTypePlugin()->hasState($moderation_state_id)) {
/** @var \Drupal\content_moderation\ContentModerationState $current_state */
$current_state = $workflow->getTypePlugin()->getState($moderation_state_id);
// This entity is default if it is new, the default revision state, or the
// default revision is not published.
if (!$entity->isSyncing()) {
$update_default_revision = $entity->isNew()
|| $current_state->isDefaultRevisionState()
|| !$content_moderation_info->isDefaultRevisionPublished($entity);
$entity->isDefaultRevision($update_default_revision);
}
// Update publishing status if it can be updated and if it needs updating.
$published_state = $current_state->isPublishedState();
if (($entity instanceof EntityPublishedInterface) && $entity->isPublished() !== $published_state) {
$published_state ? $entity->setPublished() : $entity->setUnpublished();
}
}
}
/**
* {@inheritdoc}
*/
public function generateSampleItems($count = 1) {
// No sample items generated since the starting moderation state is always
// computed based on the default state of the associated workflow.
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace Drupal\content_moderation\Plugin\Validation\Constraint;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Validation\Attribute\Constraint;
use Symfony\Component\Validator\Constraint as SymfonyConstraint;
/**
* Verifies that nodes have a valid moderation state.
*/
#[Constraint(
id: 'ModerationState',
label: new TranslatableMarkup('Valid moderation state', [], ['context' => 'Validation'])
)]
class ModerationStateConstraint extends SymfonyConstraint {
public $message = 'Invalid state transition from %from to %to';
public $invalidStateMessage = 'State %state does not exist on %workflow workflow';
public $invalidTransitionAccess = 'You do not have access to transition from %original_state to %new_state';
}

View File

@@ -0,0 +1,133 @@
<?php
namespace Drupal\content_moderation\Plugin\Validation\Constraint;
use Drupal\content_moderation\StateTransitionValidationInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Validation\Plugin\Validation\Constraint\NotNullConstraint;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Checks if a moderation state transition is valid.
*/
class ModerationStateConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
private $entityTypeManager;
/**
* The moderation info.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInformation;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* The state transition validation service.
*
* @var \Drupal\content_moderation\StateTransitionValidationInterface
*/
protected $stateTransitionValidation;
/**
* Creates a new ModerationStateConstraintValidator instance.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_information
* The moderation information.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
* @param \Drupal\content_moderation\StateTransitionValidationInterface $state_transition_validation
* The state transition validation service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, ModerationInformationInterface $moderation_information, AccountInterface $current_user, StateTransitionValidationInterface $state_transition_validation) {
$this->entityTypeManager = $entity_type_manager;
$this->moderationInformation = $moderation_information;
$this->currentUser = $current_user;
$this->stateTransitionValidation = $state_transition_validation;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('content_moderation.moderation_information'),
$container->get('current_user'),
$container->get('content_moderation.state_transition_validation')
);
}
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $value->getEntity();
// Ignore entities that are not subject to moderation anyway.
if (!$this->moderationInformation->isModeratedEntity($entity)) {
return;
}
// If the entity is moderated and the item list is empty, ensure users see
// the same required message as typical NotNull constraints.
if ($value->isEmpty()) {
$this->context->addViolation((new NotNullConstraint())->message);
return;
}
$workflow = $this->moderationInformation->getWorkflowForEntity($entity);
if (!$workflow->getTypePlugin()->hasState($entity->moderation_state->value)) {
// If the state we are transitioning to doesn't exist, we can't validate
// the transitions for this entity further.
$this->context->addViolation($constraint->invalidStateMessage, [
'%state' => $entity->moderation_state->value,
'%workflow' => $workflow->label(),
]);
return;
}
$new_state = $workflow->getTypePlugin()->getState($entity->moderation_state->value);
$original_state = $this->moderationInformation->getOriginalState($entity);
// If a new state is being set and there is an existing state, validate
// there is a valid transition between them.
if (!$original_state->canTransitionTo($new_state->id())) {
$this->context->addViolation($constraint->message, [
'%from' => $original_state->label(),
'%to' => $new_state->label(),
]);
}
else {
// If we're sure the transition exists, make sure the user has permission
// to use it.
if (!$this->stateTransitionValidation->isTransitionValid($workflow, $original_state, $new_state, $this->currentUser, $entity)) {
$this->context->addViolation($constraint->invalidTransitionAccess, [
'%original_state' => $original_state->label(),
'%new_state' => $new_state->label(),
]);
}
}
}
}

View File

@@ -0,0 +1,319 @@
<?php
namespace Drupal\content_moderation\Plugin\WorkflowType;
use Drupal\content_moderation\ModerationInformationInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\content_moderation\ContentModerationState;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\workflows\Attribute\WorkflowType;
use Drupal\workflows\Plugin\WorkflowTypeBase;
use Drupal\workflows\StateInterface;
use Drupal\workflows\WorkflowInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Attaches workflows to content entity types and their bundles.
*/
#[WorkflowType(
id: 'content_moderation',
label: new TranslatableMarkup('Content moderation'),
forms: [
'configure' => '\Drupal\content_moderation\Form\ContentModerationConfigureForm',
'state' => '\Drupal\content_moderation\Form\ContentModerationStateForm',
],
required_states: [
'draft',
'published',
]
)]
class ContentModeration extends WorkflowTypeBase implements ContentModerationInterface, ContainerFactoryPluginInterface {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity type bundle info service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $entityTypeBundleInfo;
/**
* The moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInfo;
/**
* Constructs a ContentModeration object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle info.
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_info
* Moderation information service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, ModerationInformationInterface $moderation_info) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->entityTypeBundleInfo = $entity_type_bundle_info;
$this->moderationInfo = $moderation_info;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('entity_type.bundle.info'),
$container->get('content_moderation.moderation_information')
);
}
/**
* {@inheritdoc}
*/
public function getState($state_id) {
$state = parent::getState($state_id);
if (isset($this->configuration['states'][$state->id()]['published']) && isset($this->configuration['states'][$state->id()]['default_revision'])) {
$state = new ContentModerationState($state, $this->configuration['states'][$state->id()]['published'], $this->configuration['states'][$state->id()]['default_revision']);
}
else {
$state = new ContentModerationState($state);
}
return $state;
}
/**
* {@inheritdoc}
*/
public function workflowHasData(WorkflowInterface $workflow) {
return (bool) $this->entityTypeManager
->getStorage('content_moderation_state')
->getQuery()
->condition('workflow', $workflow->id())
->count()
->accessCheck(FALSE)
->range(0, 1)
->execute();
}
/**
* {@inheritdoc}
*/
public function workflowStateHasData(WorkflowInterface $workflow, StateInterface $state) {
return (bool) $this->entityTypeManager
->getStorage('content_moderation_state')
->getQuery()
->condition('workflow', $workflow->id())
->condition('moderation_state', $state->id())
->count()
->accessCheck(FALSE)
->range(0, 1)
->execute();
}
/**
* {@inheritdoc}
*/
public function getEntityTypes() {
return array_keys($this->configuration['entity_types']);
}
/**
* {@inheritdoc}
*/
public function getBundlesForEntityType($entity_type_id) {
return $this->configuration['entity_types'][$entity_type_id] ?? [];
}
/**
* {@inheritdoc}
*/
public function appliesToEntityTypeAndBundle($entity_type_id, $bundle_id) {
return in_array($bundle_id, $this->getBundlesForEntityType($entity_type_id), TRUE);
}
/**
* {@inheritdoc}
*/
public function removeEntityTypeAndBundle($entity_type_id, $bundle_id) {
if (!isset($this->configuration['entity_types'][$entity_type_id])) {
return;
}
$key = array_search($bundle_id, $this->configuration['entity_types'][$entity_type_id], TRUE);
if ($key !== FALSE) {
unset($this->configuration['entity_types'][$entity_type_id][$key]);
if (empty($this->configuration['entity_types'][$entity_type_id])) {
unset($this->configuration['entity_types'][$entity_type_id]);
}
else {
$this->configuration['entity_types'][$entity_type_id] = array_values($this->configuration['entity_types'][$entity_type_id]);
}
}
}
/**
* {@inheritdoc}
*/
public function addEntityTypeAndBundle($entity_type_id, $bundle_id) {
if (!$this->appliesToEntityTypeAndBundle($entity_type_id, $bundle_id)) {
$this->configuration['entity_types'][$entity_type_id][] = $bundle_id;
sort($this->configuration['entity_types'][$entity_type_id]);
ksort($this->configuration['entity_types']);
}
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'states' => [
'draft' => [
'label' => 'Draft',
'published' => FALSE,
'default_revision' => FALSE,
'weight' => 0,
],
'published' => [
'label' => 'Published',
'published' => TRUE,
'default_revision' => TRUE,
'weight' => 1,
],
],
'transitions' => [
'create_new_draft' => [
'label' => 'Create New Draft',
'to' => 'draft',
'weight' => 0,
'from' => [
'draft',
'published',
],
],
'publish' => [
'label' => 'Publish',
'to' => 'published',
'weight' => 1,
'from' => [
'draft',
'published',
],
],
],
'entity_types' => [],
];
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
$dependencies = parent::calculateDependencies();
foreach ($this->getEntityTypes() as $entity_type_id) {
$entity_definition = $this->entityTypeManager->getDefinition($entity_type_id);
foreach ($this->getBundlesForEntityType($entity_type_id) as $bundle) {
$dependency = $entity_definition->getBundleConfigDependency($bundle);
$dependencies[$dependency['type']][] = $dependency['name'];
}
}
return $dependencies;
}
/**
* {@inheritdoc}
*/
public function onDependencyRemoval(array $dependencies) {
$changed = parent::onDependencyRemoval($dependencies);
// When bundle config entities are removed, ensure they are cleaned up from
// the workflow.
foreach ($dependencies['config'] as $removed_config) {
if ($entity_type_id = $removed_config->getEntityType()->getBundleOf()) {
$bundle_id = $removed_config->id();
$this->removeEntityTypeAndBundle($entity_type_id, $bundle_id);
$changed = TRUE;
}
}
// When modules that provide entity types are removed, ensure they are also
// removed from the workflow.
if (!empty($dependencies['module'])) {
// Gather all entity definitions provided by the dependent modules which
// are being removed.
$module_entity_definitions = [];
foreach ($this->entityTypeManager->getDefinitions() as $entity_definition) {
if (in_array($entity_definition->getProvider(), $dependencies['module'])) {
$module_entity_definitions[] = $entity_definition;
}
}
// For all entity types provided by the uninstalled modules, remove any
// configuration for those types.
foreach ($module_entity_definitions as $module_entity_definition) {
foreach ($this->getBundlesForEntityType($module_entity_definition->id()) as $bundle) {
$this->removeEntityTypeAndBundle($module_entity_definition->id(), $bundle);
$changed = TRUE;
}
}
}
return $changed;
}
/**
* {@inheritdoc}
*/
public function getConfiguration() {
$configuration = parent::getConfiguration();
// Ensure that states and entity types are ordered consistently.
ksort($configuration['states']);
ksort($configuration['entity_types']);
return $configuration;
}
/**
* {@inheritdoc}
*/
public function getInitialState($entity = NULL) {
// Workflows are not tied to entities, but Content Moderation adds the
// relationship between Workflows and entities. Content Moderation needs the
// entity object to be able to determine the initial state based on
// publishing status.
if (!($entity instanceof ContentEntityInterface)) {
throw new \InvalidArgumentException('A content entity object must be supplied.');
}
if ($entity instanceof EntityPublishedInterface && !$entity->isNew()) {
return $this->getState($entity->isPublished() ? 'published' : 'draft');
}
return $this->getState(!empty($this->configuration['default_moderation_state']) ? $this->configuration['default_moderation_state'] : 'draft');
}
}

View File

@@ -0,0 +1,77 @@
<?php
namespace Drupal\content_moderation\Plugin\WorkflowType;
use Drupal\workflows\WorkflowTypeInterface;
/**
* Interface for ContentModeration WorkflowType plugin.
*/
interface ContentModerationInterface extends WorkflowTypeInterface {
/**
* Gets the entity types the workflow is applied to.
*
* @return string[]
* The entity types the workflow is applied to.
*/
public function getEntityTypes();
/**
* Gets any bundles the workflow is applied to for the given entity type.
*
* @param string $entity_type_id
* The entity type ID to get the bundles for.
*
* @return string[]
* The bundles of the entity type the workflow is applied to or an empty
* array if the entity type is not applied to the workflow.
*/
public function getBundlesForEntityType($entity_type_id);
/**
* Checks if the workflow applies to the supplied entity type and bundle.
*
* @param string $entity_type_id
* The entity type ID to check.
* @param string $bundle_id
* The bundle ID to check.
*
* @return bool
* TRUE if the workflow applies to the supplied entity type ID and bundle
* ID. FALSE if not.
*/
public function appliesToEntityTypeAndBundle($entity_type_id, $bundle_id);
/**
* Removes an entity type ID / bundle ID from the workflow.
*
* @param string $entity_type_id
* The entity type ID to remove.
* @param string $bundle_id
* The bundle ID to remove.
*/
public function removeEntityTypeAndBundle($entity_type_id, $bundle_id);
/**
* Add an entity type ID / bundle ID to the workflow.
*
* @param string $entity_type_id
* The entity type ID to add. It is responsibility of the caller to provide
* a valid entity type ID.
* @param string $bundle_id
* The bundle ID to add. It is responsibility of the caller to provide a
* valid bundle ID.
*/
public function addEntityTypeAndBundle($entity_type_id, $bundle_id);
/**
* {@inheritdoc}
*
* @param $entity
* Content Moderation uses this parameter to determine the initial state
* based on publishing status.
*/
public function getInitialState($entity = NULL);
}

View File

@@ -0,0 +1,57 @@
<?php
namespace Drupal\content_moderation\Plugin\views;
use Drupal\views\Views;
/**
* Assist views handler plugins to join to the content_moderation_state entity.
*
* @internal
*/
trait ModerationStateJoinViewsHandlerTrait {
/**
* {@inheritdoc}
*/
public function ensureMyTable() {
if (!isset($this->tableAlias)) {
$table_alias = $this->query->ensureTable($this->table, $this->relationship);
// Join the moderation states of the content via the
// ContentModerationState field revision table, joining either the entity
// field data or revision table. This allows filtering states against
// either the default or latest revision, depending on the relationship of
// the filter.
$left_entity_type = $this->entityTypeManager->getDefinition($this->getEntityType());
$entity_type = $this->entityTypeManager->getDefinition('content_moderation_state');
$configuration = [
'table' => $entity_type->getRevisionDataTable(),
'field' => 'content_entity_revision_id',
'left_table' => $table_alias,
'left_field' => $left_entity_type->getKey('revision'),
'extra' => [
[
'field' => 'content_entity_type_id',
'value' => $left_entity_type->id(),
],
[
'field' => 'content_entity_id',
'left_field' => $left_entity_type->getKey('id'),
],
],
];
if ($left_entity_type->isTranslatable()) {
$configuration['extra'][] = [
'field' => $entity_type->getKey('langcode'),
'left_field' => $left_entity_type->getKey('langcode'),
];
}
$join = Views::pluginManager('join')->createInstance('standard', $configuration);
$this->tableAlias = $this->query->addRelationship('content_moderation_state', $join, 'content_moderation_state_field_revision');
}
return $this->tableAlias;
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace Drupal\content_moderation\Plugin\views\field;
use Drupal\content_moderation\Plugin\views\ModerationStateJoinViewsHandlerTrait;
use Drupal\views\Attribute\ViewsField;
use Drupal\views\Plugin\views\field\EntityField;
/**
* A field handler for the computed moderation_state field.
*
* @ingroup views_field_handlers
*/
#[ViewsField("moderation_state_field")]
class ModerationStateField extends EntityField {
use ModerationStateJoinViewsHandlerTrait;
/**
* {@inheritdoc}
*/
public function clickSort($order) {
$this->ensureMyTable();
// This could be derived from the content_moderation_state entity table
// mapping, however this is an internal entity type whose storage should
// remain constant.
$storage = $this->entityTypeManager->getStorage('content_moderation_state');
$storage_definition = $this->entityFieldManager->getActiveFieldStorageDefinitions('content_moderation_state')['moderation_state'];
$column_name = $storage->getTableMapping()->getFieldColumnName($storage_definition, 'value');
$this->aliases[$column_name] = $this->tableAlias . '.' . $column_name;
$this->query->addOrderBy(NULL, NULL, $order, $this->aliases[$column_name]);
}
}

View File

@@ -0,0 +1,258 @@
<?php
namespace Drupal\content_moderation\Plugin\views\filter;
use Drupal\content_moderation\Plugin\views\ModerationStateJoinViewsHandlerTrait;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\views\Attribute\ViewsFilter;
use Drupal\views\Plugin\DependentWithRemovalPluginInterface;
use Drupal\views\Plugin\views\filter\InOperator;
use Drupal\views\Views;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a filter for the moderation state of an entity.
*
* @ingroup views_filter_handlers
*/
#[ViewsFilter("moderation_state_filter")]
class ModerationStateFilter extends InOperator implements DependentWithRemovalPluginInterface {
use ModerationStateJoinViewsHandlerTrait;
/**
* {@inheritdoc}
*/
protected $valueFormType = 'select';
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The bundle information service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $bundleInfo;
/**
* The storage handler of the workflow entity type.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $workflowStorage;
/**
* Creates an instance of ModerationStateFilter.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $bundle_info, EntityStorageInterface $workflow_storage) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->bundleInfo = $bundle_info;
$this->workflowStorage = $workflow_storage;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('entity_type.bundle.info'),
$container->get('entity_type.manager')->getStorage('workflow')
);
}
/**
* {@inheritdoc}
*/
public function getCacheTags() {
return Cache::mergeTags(parent::getCacheTags(), $this->entityTypeManager->getDefinition('workflow')->getListCacheTags());
}
/**
* {@inheritdoc}
*/
public function getCacheContexts() {
return Cache::mergeContexts(parent::getCacheContexts(), $this->entityTypeManager->getDefinition('workflow')->getListCacheContexts());
}
/**
* {@inheritdoc}
*/
public function getValueOptions() {
if (isset($this->valueOptions)) {
return $this->valueOptions;
}
$this->valueOptions = [];
// Find all workflows which are moderating entity types of the same type the
// view is displaying.
foreach ($this->workflowStorage->loadByProperties(['type' => 'content_moderation']) as $workflow) {
/** @var \Drupal\content_moderation\Plugin\WorkflowType\ContentModerationInterface $workflow_type */
$workflow_type = $workflow->getTypePlugin();
if (in_array($this->getEntityType(), $workflow_type->getEntityTypes(), TRUE)) {
foreach ($workflow_type->getStates() as $state_id => $state) {
$this->valueOptions[$workflow->label()][implode('-', [$workflow->id(), $state_id])] = $state->label();
}
}
}
return $this->valueOptions;
}
/**
* {@inheritdoc}
*/
protected function opSimple() {
if (empty($this->value)) {
return;
}
$this->ensureMyTable();
$entity_type = $this->entityTypeManager->getDefinition($this->getEntityType());
$bundle_condition = NULL;
if ($entity_type->hasKey('bundle')) {
// Get a list of bundles that are being moderated by the workflows
// configured in this filter.
$workflow_ids = $this->getWorkflowIds();
$moderated_bundles = [];
foreach ($this->bundleInfo->getBundleInfo($this->getEntityType()) as $bundle_id => $bundle) {
if (isset($bundle['workflow']) && in_array($bundle['workflow'], $workflow_ids, TRUE)) {
$moderated_bundles[] = $bundle_id;
}
}
// If we have a list of moderated bundles, restrict the query to show only
// entities in those bundles.
if ($moderated_bundles) {
$entity_base_table_alias = $this->relationship ?: $this->table;
// The bundle field of an entity type is not revisionable so we need to
// join the base table.
$entity_base_table = $entity_type->getBaseTable();
$entity_revision_base_table = $entity_type->isTranslatable() ? $entity_type->getRevisionDataTable() : $entity_type->getRevisionTable();
if ($this->table === $entity_revision_base_table) {
$entity_revision_base_table_alias = $this->relationship ?: $this->table;
$configuration = [
'table' => $entity_base_table,
'field' => $entity_type->getKey('id'),
'left_table' => $entity_revision_base_table_alias,
'left_field' => $entity_type->getKey('id'),
'type' => 'INNER',
];
$join = Views::pluginManager('join')->createInstance('standard', $configuration);
$entity_base_table_alias = $this->query->addRelationship($entity_base_table, $join, $entity_revision_base_table_alias);
}
$bundle_condition = $this->view->query->getConnection()->condition('AND');
$bundle_condition->condition("$entity_base_table_alias.{$entity_type->getKey('bundle')}", $moderated_bundles, 'IN');
}
// Otherwise, force the query to return an empty result.
else {
$this->query->addWhereExpression($this->options['group'], '1 = 0');
return;
}
}
if ($this->operator === 'in') {
$operator = "=";
}
else {
$operator = "<>";
}
// The values are strings composed from the workflow ID and the state ID, so
// we need to create a complex WHERE condition.
$field = $this->view->query->getConnection()->condition('OR');
foreach ((array) $this->value as $value) {
[$workflow_id, $state_id] = explode('-', $value, 2);
$and = $this->view->query->getConnection()->condition('AND');
$and
->condition("$this->tableAlias.workflow", $workflow_id, '=')
->condition("$this->tableAlias.$this->realField", $state_id, $operator);
$field->condition($and);
}
if ($bundle_condition) {
// The query must match the bundle AND the workflow/state conditions.
$bundle_condition->condition($field);
$this->query->addWhere($this->options['group'], $bundle_condition);
}
else {
$this->query->addWhere($this->options['group'], $field);
}
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
$dependencies = parent::calculateDependencies();
if ($workflow_ids = $this->getWorkflowIds()) {
/** @var \Drupal\workflows\WorkflowInterface $workflow */
foreach ($this->workflowStorage->loadMultiple($workflow_ids) as $workflow) {
$dependencies[$workflow->getConfigDependencyKey()][] = $workflow->getConfigDependencyName();
}
}
return $dependencies;
}
/**
* {@inheritdoc}
*/
public function onDependencyRemoval(array $dependencies) {
// See if this handler is responsible for any of the dependencies being
// removed. If this is the case, indicate that this handler needs to be
// removed from the View.
$remove = FALSE;
// Get all the current dependencies for this handler.
$current_dependencies = $this->calculateDependencies();
foreach ($current_dependencies as $group => $dependency_list) {
// Check if any of the handler dependencies match the dependencies being
// removed.
foreach ($dependency_list as $config_key) {
if (isset($dependencies[$group]) && array_key_exists($config_key, $dependencies[$group])) {
// This handlers dependency matches a dependency being removed,
// indicate that this handler needs to be removed.
$remove = TRUE;
break 2;
}
}
}
return $remove;
}
/**
* Gets the list of Workflow IDs configured for this filter.
*
* @return array
* And array of workflow IDs.
*/
protected function getWorkflowIds() {
$workflow_ids = [];
foreach ((array) $this->value as $value) {
[$workflow_id] = explode('-', $value, 2);
$workflow_ids[] = $workflow_id;
}
return array_unique($workflow_ids);
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace Drupal\content_moderation\Plugin\views\sort;
use Drupal\content_moderation\Plugin\views\ModerationStateJoinViewsHandlerTrait;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\views\Attribute\ViewsSort;
use Drupal\views\Plugin\views\sort\SortPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Enables sorting for the computed moderation_state field.
*
* @ingroup views_sort_handlers
*/
#[ViewsSort("moderation_state_sort")]
class ModerationStateSort extends SortPluginBase {
use ModerationStateJoinViewsHandlerTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Creates an instance of ModerationStateFilter.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin ID for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager')
);
}
}

View File

@@ -0,0 +1,113 @@
<?php
namespace Drupal\content_moderation\Routing;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Drupal\workflows\Entity\Workflow;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* Subscriber for moderated revisionable entity forms.
*
* @internal
* There is ongoing discussion about how pending revisions should behave.
* The logic enabling pending revision support is likely to change once a
* decision is made.
*
* @see https://www.drupal.org/node/2940575
*/
class ContentModerationRouteSubscriber extends RouteSubscriberBase {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* An associative array of moderated entity types keyed by ID.
*
* @var \Drupal\Core\Entity\ContentEntityTypeInterface[]
*/
protected $moderatedEntityTypes;
/**
* ContentModerationRouteSubscriber constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
protected function alterRoutes(RouteCollection $collection) {
foreach ($collection as $route) {
$this->setLatestRevisionFlag($route);
}
}
/**
* Ensure revisionable entities load the latest revision on entity forms.
*
* @param \Symfony\Component\Routing\Route $route
* The route object.
*/
protected function setLatestRevisionFlag(Route $route) {
if (!$entity_form = $route->getDefault('_entity_form')) {
return;
}
// Only set the flag on entity types which are revisionable.
[$entity_type] = explode('.', $entity_form, 2);
if (!isset($this->getModeratedEntityTypes()[$entity_type]) || !$this->getModeratedEntityTypes()[$entity_type]->isRevisionable()) {
return;
}
$parameters = $route->getOption('parameters') ?: [];
foreach ($parameters as &$parameter) {
if (isset($parameter['type']) && $parameter['type'] === 'entity:' . $entity_type && !isset($parameter['load_latest_revision'])) {
$parameter['load_latest_revision'] = TRUE;
}
}
$route->setOption('parameters', $parameters);
}
/**
* Returns the moderated entity types.
*
* @return \Drupal\Core\Entity\ContentEntityTypeInterface[]
* An associative array of moderated entity types keyed by ID.
*/
protected function getModeratedEntityTypes() {
if (!isset($this->moderatedEntityTypes)) {
$entity_types = $this->entityTypeManager->getDefinitions();
/** @var \Drupal\workflows\WorkflowInterface $workflow */
foreach (Workflow::loadMultipleByType('content_moderation') as $workflow) {
/** @var \Drupal\content_moderation\Plugin\WorkflowType\ContentModeration $plugin */
$plugin = $workflow->getTypePlugin();
foreach ($plugin->getEntityTypes() as $entity_type_id) {
$this->moderatedEntityTypes[$entity_type_id] = $entity_types[$entity_type_id];
}
}
}
return $this->moderatedEntityTypes;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events = parent::getSubscribedEvents();
// This needs to run after that EntityResolverManager has set the route
// entity type.
$events[RoutingEvents::ALTER] = ['onAlterRoutes', -200];
return $events;
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace Drupal\content_moderation;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\workflows\StateInterface;
use Drupal\workflows\Transition;
use Drupal\workflows\WorkflowInterface;
/**
* Validates whether a certain state transition is allowed.
*/
class StateTransitionValidation implements StateTransitionValidationInterface {
/**
* The moderation information service.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInfo;
/**
* Stores the possible state transitions.
*
* @var array
*/
protected $possibleTransitions = [];
/**
* Constructs a new StateTransitionValidation.
*
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_info
* The moderation information service.
*/
public function __construct(ModerationInformationInterface $moderation_info) {
$this->moderationInfo = $moderation_info;
}
/**
* {@inheritdoc}
*/
public function getValidTransitions(ContentEntityInterface $entity, AccountInterface $user) {
$workflow = $this->moderationInfo->getWorkflowForEntity($entity);
$current_state = $entity->moderation_state->value ? $workflow->getTypePlugin()->getState($entity->moderation_state->value) : $workflow->getTypePlugin()->getInitialState($entity);
return array_filter($current_state->getTransitions(), function (Transition $transition) use ($workflow, $user) {
return $user->hasPermission('use ' . $workflow->id() . ' transition ' . $transition->id());
});
}
/**
* {@inheritdoc}
*/
public function isTransitionValid(WorkflowInterface $workflow, StateInterface $original_state, StateInterface $new_state, AccountInterface $user, ContentEntityInterface $entity) {
$transition = $workflow->getTypePlugin()->getTransitionFromStateToState($original_state->id(), $new_state->id());
return $user->hasPermission('use ' . $workflow->id() . ' transition ' . $transition->id());
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace Drupal\content_moderation;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\workflows\StateInterface;
use Drupal\workflows\WorkflowInterface;
/**
* Validates whether a certain state transition is allowed.
*/
interface StateTransitionValidationInterface {
/**
* Gets a list of transitions that are legal for this user on this entity.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity to be transitioned.
* @param \Drupal\Core\Session\AccountInterface $user
* The account that wants to perform a transition.
*
* @return \Drupal\workflows\Transition[]
* The list of transitions that are legal for this user on this entity.
*/
public function getValidTransitions(ContentEntityInterface $entity, AccountInterface $user);
/**
* Checks if a transition between two states if valid for the given user.
*
* @param \Drupal\workflows\WorkflowInterface $workflow
* The workflow entity.
* @param \Drupal\workflows\StateInterface $original_state
* The original workflow state.
* @param \Drupal\workflows\StateInterface $new_state
* The new workflow state.
* @param \Drupal\Core\Session\AccountInterface $user
* The user to validate.
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity to be transitioned.
*
* @return bool
* Returns TRUE if transition is valid, otherwise FALSE.
*/
public function isTransitionValid(WorkflowInterface $workflow, StateInterface $original_state, StateInterface $new_state, AccountInterface $user, ContentEntityInterface $entity);
}

View File

@@ -0,0 +1,88 @@
<?php
namespace Drupal\content_moderation;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Provides the content_moderation views integration.
*
* @internal
*/
class ViewsData {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The moderation information.
*
* @var \Drupal\content_moderation\ModerationInformationInterface
*/
protected $moderationInformation;
/**
* Creates a new ViewsData instance.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\content_moderation\ModerationInformationInterface $moderation_information
* The moderation information.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, ModerationInformationInterface $moderation_information) {
$this->entityTypeManager = $entity_type_manager;
$this->moderationInformation = $moderation_information;
}
/**
* Returns the views data.
*
* @return array
* The views data.
*/
public function getViewsData() {
$data = [];
$entity_types_with_moderation = array_filter($this->entityTypeManager->getDefinitions(), function (EntityTypeInterface $type) {
return $this->moderationInformation->isModeratedEntityType($type);
});
foreach ($entity_types_with_moderation as $entity_type) {
$table = $entity_type->getDataTable() ?: $entity_type->getBaseTable();
$data[$table]['moderation_state'] = [
'title' => t('Moderation state'),
'field' => [
'id' => 'moderation_state_field',
'default_formatter' => 'content_moderation_state',
'field_name' => 'moderation_state',
],
'filter' => ['id' => 'moderation_state_filter', 'allow empty' => TRUE],
'sort' => ['id' => 'moderation_state_sort'],
];
$revision_table = $entity_type->getRevisionDataTable() ?: $entity_type->getRevisionTable();
$data[$revision_table]['moderation_state'] = [
'title' => t('Moderation state'),
'field' => [
'id' => 'moderation_state_field',
'default_formatter' => 'content_moderation_state',
'field_name' => 'moderation_state',
],
'filter' => ['id' => 'moderation_state_filter', 'allow empty' => TRUE],
'sort' => ['id' => 'moderation_state_sort'],
];
}
return $data;
}
}