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,124 @@
<?php
namespace Drupal\content_translation\Access;
use Drupal\content_translation\ContentTranslationManager;
use Drupal\content_translation\ContentTranslationManagerInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\language\Entity\ContentLanguageSettings;
use Drupal\workflows\Entity\Workflow;
/**
* Access check for entity translation deletion.
*
* @internal This additional access checker only aims to prevent deletions in
* pending revisions until we are able to flag revision translations as
* deleted.
*
* @todo Remove this in https://www.drupal.org/node/2945956.
*/
class ContentTranslationDeleteAccess implements AccessInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The content translation manager.
*
* @var \Drupal\content_translation\ContentTranslationManagerInterface
*/
protected $contentTranslationManager;
/**
* Constructs a ContentTranslationDeleteAccess object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $manager
* The entity type manager.
* @param \Drupal\content_translation\ContentTranslationManagerInterface $content_translation_manager
* The content translation manager.
*/
public function __construct(EntityTypeManagerInterface $manager, ContentTranslationManagerInterface $content_translation_manager) {
$this->entityTypeManager = $manager;
$this->contentTranslationManager = $content_translation_manager;
}
/**
* Checks access to translation deletion for the specified route match.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The parameterized route.
* @param \Drupal\Core\Session\AccountInterface $account
* The currently logged in account.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function access(RouteMatchInterface $route_match, AccountInterface $account) {
$requirement = $route_match->getRouteObject()->getRequirement('_access_content_translation_delete');
$entity_type_id = current(explode('.', $requirement));
$entity = $route_match->getParameter($entity_type_id);
return $this->checkAccess($entity);
}
/**
* Checks access to translation deletion for the specified entity.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity translation to be deleted.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function checkAccess(ContentEntityInterface $entity) {
$result = AccessResult::allowed();
$entity_type_id = $entity->getEntityTypeId();
$result->addCacheableDependency($entity);
// Add the cache dependencies used by
// ContentTranslationManager::isPendingRevisionSupportEnabled().
if (\Drupal::moduleHandler()->moduleExists('content_moderation')) {
foreach (Workflow::loadMultipleByType('content_moderation') as $workflow) {
$result->addCacheableDependency($workflow);
}
}
if (!ContentTranslationManager::isPendingRevisionSupportEnabled($entity_type_id, $entity->bundle())) {
return $result;
}
if ($entity->isDefaultTranslation()) {
return $result;
}
$config = ContentLanguageSettings::load($entity_type_id . '.' . $entity->bundle());
$result->addCacheableDependency($config);
if (!$this->contentTranslationManager->isEnabled($entity_type_id, $entity->bundle())) {
return $result;
}
/** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
$storage = $this->entityTypeManager->getStorage($entity_type_id);
$revision_id = $storage->getLatestTranslationAffectedRevisionId($entity->id(), $entity->language()->getId());
if (!$revision_id) {
return $result;
}
/** @var \Drupal\Core\Entity\ContentEntityInterface $revision */
$revision = $storage->loadRevision($revision_id);
if ($revision->wasDefaultRevision()) {
return $result;
}
$result = $result->andIf(AccessResult::forbidden());
return $result;
}
}

View File

@@ -0,0 +1,151 @@
<?php
namespace Drupal\content_translation\Access;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\Routing\Route;
/**
* Access check for entity translation CRUD operation.
*/
class ContentTranslationManageAccessCheck implements AccessInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* Constructs a ContentTranslationManageAccessCheck object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, LanguageManagerInterface $language_manager) {
$this->entityTypeManager = $entity_type_manager;
$this->languageManager = $language_manager;
}
/**
* Checks translation access for the entity and operation on the given route.
*
* @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 currently logged in account.
* @param string $source
* (optional) For a create operation, the language code of the source.
* @param string $target
* (optional) For a create operation, the language code of the translation.
* @param string $language
* (optional) For an update or delete operation, the language code of the
* translation being updated or deleted.
* @param string $entity_type_id
* (optional) The entity type ID.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account, $source = NULL, $target = NULL, $language = NULL, $entity_type_id = NULL) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
if ($entity = $route_match->getParameter($entity_type_id)) {
$operation = $route->getRequirement('_access_content_translation_manage');
$language = $this->languageManager->getLanguage($language) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
$entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
if (in_array($operation, ['update', 'delete'])) {
// Translation operations cannot be performed on the default
// translation.
if ($language->getId() == $entity->getUntranslated()->language()->getId()) {
return AccessResult::forbidden()->addCacheableDependency($entity);
}
// Editors have no access to the translation operations, as entity
// access already grants them an equal or greater access level.
$templates = ['update' => 'edit-form', 'delete' => 'delete-form'];
if ($entity->access($operation) && $entity_type->hasLinkTemplate($templates[$operation])) {
return AccessResult::forbidden()->cachePerPermissions();
}
}
if ($account->hasPermission('translate any entity')) {
return AccessResult::allowed()->cachePerPermissions();
}
switch ($operation) {
case 'create':
/** @var \Drupal\content_translation\ContentTranslationHandlerInterface $handler */
$handler = $this->entityTypeManager->getHandler($entity->getEntityTypeId(), 'translation');
$translations = $entity->getTranslationLanguages();
$languages = $this->languageManager->getLanguages();
$source_language = $this->languageManager->getLanguage($source) ?: $entity->language();
$target_language = $this->languageManager->getLanguage($target) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
$is_new_translation = ($source_language->getId() != $target_language->getId()
&& isset($languages[$source_language->getId()])
&& isset($languages[$target_language->getId()])
&& !isset($translations[$target_language->getId()]));
return AccessResult::allowedIf($is_new_translation)->cachePerPermissions()->addCacheableDependency($entity)
->andIf($handler->getTranslationAccess($entity, $operation));
case 'delete':
// @todo Remove this in https://www.drupal.org/node/2945956.
/** @var \Drupal\Core\Access\AccessResultInterface $delete_access */
$delete_access = \Drupal::service('content_translation.delete_access')->checkAccess($entity);
$access = $this->checkAccess($entity, $language, $operation);
return $delete_access->andIf($access);
case 'update':
return $this->checkAccess($entity, $language, $operation);
}
}
// No opinion.
return AccessResult::neutral();
}
/**
* Performs access checks for the specified operation.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity being checked.
* @param \Drupal\Core\Language\LanguageInterface $language
* For an update or delete operation, the language code of the translation
* being updated or deleted.
* @param string $operation
* The operation to be checked.
*
* @return \Drupal\Core\Access\AccessResultInterface
* An access result object.
*/
protected function checkAccess(ContentEntityInterface $entity, LanguageInterface $language, $operation) {
/** @var \Drupal\content_translation\ContentTranslationHandlerInterface $handler */
$handler = $this->entityTypeManager->getHandler($entity->getEntityTypeId(), 'translation');
$translations = $entity->getTranslationLanguages();
$languages = $this->languageManager->getLanguages();
$has_translation = isset($languages[$language->getId()])
&& $language->getId() != $entity->getUntranslated()->language()->getId()
&& isset($translations[$language->getId()]);
return AccessResult::allowedIf($has_translation)->cachePerPermissions()->addCacheableDependency($entity)
->andIf($handler->getTranslationAccess($entity, $operation));
}
}

View File

@@ -0,0 +1,79 @@
<?php
namespace Drupal\content_translation\Access;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Access check for entity translation overview.
*/
class ContentTranslationOverviewAccess implements AccessInterface {
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a ContentTranslationOverviewAccess object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* Checks access to the translation overview for the entity and bundle.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The parametrized route.
* @param \Drupal\Core\Session\AccountInterface $account
* The currently logged in account.
* @param string $entity_type_id
* The entity type ID.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function access(RouteMatchInterface $route_match, AccountInterface $account, $entity_type_id) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $route_match->getParameter($entity_type_id);
if ($entity && $entity->isTranslatable()) {
// Get entity base info.
$bundle = $entity->bundle();
// Get entity access callback.
$definition = $this->entityTypeManager->getDefinition($entity_type_id);
$translation = $definition->get('translation');
$access_callback = $translation['content_translation']['access_callback'];
$access = call_user_func($access_callback, $entity);
if ($access->isAllowed()) {
return $access;
}
// Check "translate any entity" permission.
if ($account->hasPermission('translate any entity')) {
return AccessResult::allowed()->cachePerPermissions()->inheritCacheability($access);
}
// Check per entity permission.
$permission = "translate {$entity_type_id}";
if ($definition->getPermissionGranularity() == 'bundle') {
$permission = "translate {$bundle} {$entity_type_id}";
}
return AccessResult::allowedIfHasPermission($account, $permission)->inheritCacheability($access);
}
// No opinion.
return AccessResult::neutral();
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace Drupal\content_translation;
/**
* Interface providing support for content translation bundle settings.
*/
interface BundleTranslationSettingsInterface {
/**
* Returns translation settings for the specified bundle.
*
* @param string $entity_type_id
* The entity type identifier.
* @param string $bundle
* The bundle name.
*
* @return array
* An associative array of values keyed by setting name.
*/
public function getBundleTranslationSettings($entity_type_id, $bundle);
/**
* Sets translation settings for the specified bundle.
*
* @param string $entity_type_id
* The entity type identifier.
* @param string $bundle
* The bundle name.
* @param array $settings
* An associative array of values keyed by setting name.
*/
public function setBundleTranslationSettings($entity_type_id, $bundle, array $settings);
}

View File

@@ -0,0 +1,879 @@
<?php
namespace Drupal\content_translation;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\Core\Entity\EntityChangesDetectionTrait;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RedirectDestinationInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Drupal\user\Entity\User;
use Drupal\user\EntityOwnerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Base class for content translation handlers.
*
* @ingroup entity_api
*/
class ContentTranslationHandler implements ContentTranslationHandlerInterface, EntityHandlerInterface {
use EntityChangesDetectionTrait;
use DependencySerializationTrait;
use StringTranslationTrait;
/**
* The type of the entity being translated.
*
* @var string
*/
protected $entityTypeId;
/**
* Information about the entity type.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $entityType;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;
/**
* The content translation manager.
*
* @var \Drupal\content_translation\ContentTranslationManagerInterface
*/
protected $manager;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* Installed field storage definitions for the entity type.
*
* Keyed by field name.
*
* @var \Drupal\Core\Field\FieldStorageDefinitionInterface[]
*/
protected $fieldStorageDefinitions;
/**
* The messenger service.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* Initializes an instance of the content translation controller.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The info array of the given entity type.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\content_translation\ContentTranslationManagerInterface $manager
* The content translation manager service.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Session\AccountInterface $current_user
* The current user.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger service.
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter service.
* @param \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $entity_last_installed_schema_repository
* The installed entity definition repository service.
* @param \Drupal\Core\Routing\RedirectDestinationInterface|null $redirectDestination
* The request stack.
* @param \Drupal\Component\Datetime\TimeInterface|null $time
* The time service.
*/
public function __construct(
EntityTypeInterface $entity_type,
LanguageManagerInterface $language_manager,
ContentTranslationManagerInterface $manager,
EntityTypeManagerInterface $entity_type_manager,
AccountInterface $current_user,
MessengerInterface $messenger,
DateFormatterInterface $date_formatter,
EntityLastInstalledSchemaRepositoryInterface $entity_last_installed_schema_repository,
protected ?RedirectDestinationInterface $redirectDestination = NULL,
protected ?TimeInterface $time = NULL,
) {
$this->entityTypeId = $entity_type->id();
$this->entityType = $entity_type;
$this->languageManager = $language_manager;
$this->manager = $manager;
$this->entityTypeManager = $entity_type_manager;
$this->currentUser = $current_user;
$this->fieldStorageDefinitions = $entity_last_installed_schema_repository->getLastInstalledFieldStorageDefinitions($this->entityTypeId);
$this->messenger = $messenger;
$this->dateFormatter = $date_formatter;
if ($this->redirectDestination === NULL) {
@trigger_error('Calling ContentTranslationHandler::__construct() without the $redirectDestination argument is deprecated in drupal:10.2.0 and will be required in drupal:11.0.0. See https://www.drupal.org/node/3375487', E_USER_DEPRECATED);
$this->redirectDestination = \Drupal::service('redirect.destination');
}
if ($this->time === NULL) {
@trigger_error('Calling ' . __METHOD__ . ' without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3112298', E_USER_DEPRECATED);
$this->time = \Drupal::service('datetime.time');
}
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$entity_type,
$container->get('language_manager'),
$container->get('content_translation.manager'),
$container->get('entity_type.manager'),
$container->get('current_user'),
$container->get('messenger'),
$container->get('date.formatter'),
$container->get('entity.last_installed_schema.repository'),
$container->get('redirect.destination'),
$container->get('datetime.time'),
);
}
/**
* {@inheritdoc}
*/
public function getFieldDefinitions() {
$definitions = [];
$definitions['content_translation_source'] = BaseFieldDefinition::create('language')
->setLabel(t('Translation source'))
->setDescription(t('The source language from which this translation was created.'))
->setDefaultValue(LanguageInterface::LANGCODE_NOT_SPECIFIED)
->setInitialValue(LanguageInterface::LANGCODE_NOT_SPECIFIED)
->setRevisionable(TRUE)
->setTranslatable(TRUE);
$definitions['content_translation_outdated'] = BaseFieldDefinition::create('boolean')
->setLabel(t('Translation outdated'))
->setDescription(t('A boolean indicating whether this translation needs to be updated.'))
->setDefaultValue(FALSE)
->setInitialValue(FALSE)
->setRevisionable(TRUE)
->setTranslatable(TRUE);
if (!$this->hasAuthor()) {
$definitions['content_translation_uid'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Translation author'))
->setDescription(t('The author of this translation.'))
->setSetting('target_type', 'user')
->setSetting('handler', 'default')
->setRevisionable(TRUE)
->setDefaultValueCallback(static::class . '::getDefaultOwnerId')
->setTranslatable(TRUE);
}
if (!$this->hasPublishedStatus()) {
$definitions['content_translation_status'] = BaseFieldDefinition::create('boolean')
->setLabel(t('Translation status'))
->setDescription(t('A boolean indicating whether the translation is visible to non-translators.'))
->setDefaultValue(TRUE)
->setInitialValue(TRUE)
->setRevisionable(TRUE)
->setTranslatable(TRUE);
}
if (!$this->hasCreatedTime()) {
$definitions['content_translation_created'] = BaseFieldDefinition::create('created')
->setLabel(t('Translation created time'))
->setDescription(t('The Unix timestamp when the translation was created.'))
->setRevisionable(TRUE)
->setTranslatable(TRUE);
}
if (!$this->hasChangedTime()) {
$definitions['content_translation_changed'] = BaseFieldDefinition::create('changed')
->setLabel(t('Translation changed time'))
->setDescription(t('The Unix timestamp when the translation was most recently saved.'))
->setRevisionable(TRUE)
->setTranslatable(TRUE);
}
return $definitions;
}
/**
* Checks whether the entity type supports author natively.
*
* @return bool
* TRUE if metadata is natively supported, FALSE otherwise.
*/
protected function hasAuthor() {
// Check for field named uid, but only in case the entity implements the
// EntityOwnerInterface. This helps to exclude cases, where the uid is
// defined as field name, but is not meant to be an owner field; for
// instance, the User entity.
return $this->entityType->entityClassImplements(EntityOwnerInterface::class) && $this->checkFieldStorageDefinitionTranslatability('uid');
}
/**
* Checks whether the entity type supports published status natively.
*
* @return bool
* TRUE if metadata is natively supported, FALSE otherwise.
*/
protected function hasPublishedStatus() {
return $this->checkFieldStorageDefinitionTranslatability('status');
}
/**
* Checks whether the entity type supports modification time natively.
*
* @return bool
* TRUE if metadata is natively supported, FALSE otherwise.
*/
protected function hasChangedTime() {
return $this->entityType->entityClassImplements(EntityChangedInterface::class) && $this->checkFieldStorageDefinitionTranslatability('changed');
}
/**
* Checks whether the entity type supports creation time natively.
*
* @return bool
* TRUE if metadata is natively supported, FALSE otherwise.
*/
protected function hasCreatedTime() {
return $this->checkFieldStorageDefinitionTranslatability('created');
}
/**
* Checks the field storage definition for translatability support.
*
* Checks whether the given field is defined in the field storage definitions
* and if its definition specifies it as translatable.
*
* @param string $field_name
* The name of the field.
*
* @return bool
* TRUE if translatable field storage definition exists, FALSE otherwise.
*/
protected function checkFieldStorageDefinitionTranslatability($field_name) {
return array_key_exists($field_name, $this->fieldStorageDefinitions) && $this->fieldStorageDefinitions[$field_name]->isTranslatable();
}
/**
* {@inheritdoc}
*/
public function retranslate(EntityInterface $entity, $langcode = NULL) {
$updated_langcode = !empty($langcode) ? $langcode : $entity->language()->getId();
foreach ($entity->getTranslationLanguages() as $langcode => $language) {
$this->manager->getTranslationMetadata($entity->getTranslation($langcode))
->setOutdated($langcode != $updated_langcode);
}
}
/**
* {@inheritdoc}
*/
public function getTranslationAccess(EntityInterface $entity, $op) {
// @todo Move this logic into a translation access control handler checking also
// the translation language and the given account.
$entity_type = $entity->getEntityType();
$translate_permission = TRUE;
// If no permission granularity is defined this entity type does not need an
// explicit translate permission.
if (!$this->currentUser->hasPermission('translate any entity') && $permission_granularity = $entity_type->getPermissionGranularity()) {
$translate_permission = $this->currentUser->hasPermission($permission_granularity == 'bundle' ? "translate {$entity->bundle()} {$entity->getEntityTypeId()}" : "translate {$entity->getEntityTypeId()}");
}
$access = AccessResult::allowedIf(($translate_permission && $this->currentUser->hasPermission("$op content translations")))->cachePerPermissions();
if (!$access->isAllowed()) {
return AccessResult::allowedIfHasPermission($this->currentUser, 'translate editable entities')->andIf($entity->access('update', $this->currentUser, TRUE));
}
return $access;
}
/**
* {@inheritdoc}
*/
public function getSourceLangcode(FormStateInterface $form_state) {
if ($source = $form_state->get(['content_translation', 'source'])) {
return $source->getId();
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function entityFormAlter(array &$form, FormStateInterface $form_state, EntityInterface $entity) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$metadata = $this->manager->getTranslationMetadata($entity);
$form_object = $form_state->getFormObject();
$form_langcode = $form_object->getFormLangcode($form_state);
$entity_langcode = $entity->getUntranslated()->language()->getId();
$new_translation = $entity->isNewTranslation();
$translations = $entity->getTranslationLanguages();
if ($new_translation) {
// Make sure a new translation does not appear as existing yet.
unset($translations[$form_langcode]);
}
$is_translation = $new_translation || ($entity->language()->getId() != $entity_langcode);
$has_translations = count($translations) > 1;
// Adjust page title to specify the current language being edited, if we
// have at least one translation.
$languages = $this->languageManager->getLanguages();
if (isset($languages[$form_langcode]) && ($has_translations || $new_translation)) {
$title = $this->entityFormTitle($entity);
// When editing the original values display just the entity label.
if ($is_translation) {
$t_args = ['%language' => $languages[$form_langcode]->getName(), '%title' => $entity->label(), '@title' => $title];
$title = $new_translation ? t('Create %language translation of %title', $t_args) : t('@title [%language translation]', $t_args);
}
$form['#title'] = $title;
}
// Display source language selector only if we are creating a new
// translation and there are at least two translations available.
if ($has_translations && $new_translation) {
$source_langcode = $metadata->getSource();
$form['source_langcode'] = [
'#type' => 'details',
'#title' => t('Source language: @language', ['@language' => $languages[$source_langcode]->getName()]),
'#tree' => TRUE,
'#weight' => -100,
'#multilingual' => TRUE,
'source' => [
'#title' => t('Select source language'),
'#title_display' => 'invisible',
'#type' => 'select',
'#default_value' => $source_langcode,
'#options' => [],
],
'submit' => [
'#type' => 'submit',
'#value' => t('Change'),
'#submit' => [[$this, 'entityFormSourceChange']],
],
];
foreach ($this->languageManager->getLanguages() as $language) {
if (isset($translations[$language->getId()])) {
$form['source_langcode']['source']['#options'][$language->getId()] = $language->getName();
}
}
}
// Locate the language widget.
$langcode_key = $this->entityType->getKey('langcode');
if (isset($form[$langcode_key])) {
$language_widget = &$form[$langcode_key];
}
// If we are editing the source entity, limit the list of languages so that
// it is not possible to switch to a language for which a translation
// already exists. Note that this will only work if the widget is structured
// like \Drupal\Core\Field\Plugin\Field\FieldWidget\LanguageSelectWidget.
if (isset($language_widget['widget'][0]['value']) && !$is_translation && $has_translations) {
$language_select = &$language_widget['widget'][0]['value'];
if ($language_select['#type'] == 'language_select') {
$options = [];
foreach ($this->languageManager->getLanguages() as $language) {
// Show the current language, and the languages for which no
// translation already exists.
if (empty($translations[$language->getId()]) || $language->getId() == $entity_langcode) {
$options[$language->getId()] = $language->getName();
}
}
$language_select['#options'] = $options;
}
}
if ($is_translation) {
if (isset($language_widget)) {
$language_widget['widget']['#access'] = FALSE;
}
// Replace the delete button with the delete translation one.
if (!$new_translation) {
$weight = 100;
foreach (['delete', 'submit'] as $key) {
if (isset($form['actions'][$key]['weight'])) {
$weight = $form['actions'][$key]['weight'];
break;
}
}
/** @var \Drupal\Core\Access\AccessResultInterface $delete_access */
$delete_access = \Drupal::service('content_translation.delete_access')->checkAccess($entity);
$access = $delete_access->isAllowed() && (
$this->getTranslationAccess($entity, 'delete')->isAllowed() ||
($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form'))
);
$form['actions']['delete_translation'] = [
'#type' => 'link',
'#title' => $this->t('Delete translation'),
'#access' => $access,
'#weight' => $weight,
'#url' => $this->entityFormDeleteTranslationUrl($entity, $form_langcode),
'#attributes' => [
'class' => ['button', 'button--danger'],
],
];
}
// Always remove the delete button on translation forms.
unset($form['actions']['delete']);
}
// We need to display the translation tab only when there is at least one
// translation available or a new one is about to be created.
if ($new_translation || $has_translations) {
$form['content_translation'] = [
'#type' => 'details',
'#title' => t('Translation'),
'#tree' => TRUE,
'#weight' => 10,
'#access' => $this->getTranslationAccess($entity, $new_translation ? 'create' : 'update')->isAllowed(),
'#multilingual' => TRUE,
];
if (isset($form['advanced'])) {
$form['content_translation'] += [
'#group' => 'advanced',
'#weight' => 100,
'#attributes' => [
'class' => ['entity-translation-options'],
],
];
}
// A new translation is enabled by default.
$status = $new_translation || $metadata->isPublished();
// If there is only one published translation we cannot unpublish it,
// since there would be nothing left to display.
$enabled = TRUE;
if ($status) {
$published = 0;
foreach ($entity->getTranslationLanguages() as $langcode => $language) {
$published += $this->manager->getTranslationMetadata($entity->getTranslation($langcode))
->isPublished();
}
$enabled = $published > 1;
}
$description = $enabled ?
t('An unpublished translation will not be visible without translation permissions.') :
t('Only this translation is published. You must publish at least one more translation to unpublish this one.');
$form['content_translation']['status'] = [
'#type' => 'checkbox',
'#title' => t('This translation is published'),
'#default_value' => $status,
'#description' => $description,
'#disabled' => !$enabled,
];
$translate = !$new_translation && $metadata->isOutdated();
$outdated_access = !ContentTranslationManager::isPendingRevisionSupportEnabled($entity->getEntityTypeId(), $entity->bundle());
if (!$outdated_access) {
$form['content_translation']['outdated'] = [
'#markup' => $this->t('Translations cannot be flagged as outdated when content is moderated.'),
];
}
elseif (!$translate) {
$form['content_translation']['retranslate'] = [
'#type' => 'checkbox',
'#title' => t('Flag other translations as outdated'),
'#default_value' => FALSE,
'#description' => t('If you made a significant change, which means the other translations should be updated, you can flag all translations of this content as outdated. This will not change any other property of them, like whether they are published or not.'),
'#access' => $outdated_access,
];
}
else {
$form['content_translation']['outdated'] = [
'#type' => 'checkbox',
'#title' => t('This translation needs to be updated'),
'#default_value' => $translate,
'#description' => t('When this option is checked, this translation needs to be updated. Uncheck when the translation is up to date again.'),
'#access' => $outdated_access,
];
$form['content_translation']['#open'] = TRUE;
}
// Default to the anonymous user.
$uid = 0;
if ($new_translation) {
$uid = $this->currentUser->id();
}
elseif (($account = $metadata->getAuthor()) && $account->id()) {
$uid = $account->id();
}
$form['content_translation']['uid'] = [
'#type' => 'entity_autocomplete',
'#title' => t('Authored by'),
'#target_type' => 'user',
'#default_value' => User::load($uid),
// Validation is done by static::entityFormValidate().
'#validate_reference' => FALSE,
'#maxlength' => 60,
'#description' => t('Leave blank for %anonymous.', ['%anonymous' => \Drupal::config('user.settings')->get('anonymous')]),
];
$date = $new_translation ? $this->time->getRequestTime() : $metadata->getCreatedTime();
$form['content_translation']['created'] = [
'#type' => 'textfield',
'#title' => t('Authored on'),
'#maxlength' => 25,
'#description' => t('Leave blank to use the time of form submission.'),
'#default_value' => $new_translation || !$date ? '' : $this->dateFormatter->format($date, 'custom', 'Y-m-d H:i:s O'),
];
$form['#process'][] = [$this, 'entityFormSharedElements'];
}
// Process the submitted values before they are stored.
$form['#entity_builders'][] = [$this, 'entityFormEntityBuild'];
// Handle entity validation.
$form['#validate'][] = [$this, 'entityFormValidate'];
// Handle entity deletion.
if (isset($form['actions']['delete'])) {
$form['actions']['delete']['#submit'][] = [$this, 'entityFormDelete'];
}
// Handle entity form submission before the entity has been saved.
foreach (Element::children($form['actions']) as $action) {
if (isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] == 'submit') {
array_unshift($form['actions'][$action]['#submit'], [$this, 'entityFormSubmit']);
}
}
}
/**
* Process callback: determines which elements get clue in the form.
*
* @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
*/
public function entityFormSharedElements($element, FormStateInterface $form_state, $form) {
static $ignored_types;
// @todo Find a more reliable way to determine if a form element concerns a
// multilingual value.
if (!isset($ignored_types)) {
$ignored_types = array_flip(['actions', 'value', 'hidden', 'vertical_tabs', 'token', 'details', 'link']);
}
/** @var \Drupal\Core\Entity\ContentEntityForm $form_object */
$form_object = $form_state->getFormObject();
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $form_object->getEntity();
$display_translatability_clue = !$entity->isDefaultTranslationAffectedOnly();
$hide_untranslatable_fields = $entity->isDefaultTranslationAffectedOnly() && !$entity->isDefaultTranslation();
$translation_form = $form_state->get(['content_translation', 'translation_form']);
$display_warning = FALSE;
// We use field definitions to identify untranslatable field widgets to be
// hidden. Fields that are not involved in translation changes checks should
// not be affected by this logic (the "revision_log" field, for instance).
$field_definitions = array_diff_key($entity->getFieldDefinitions(), array_flip($this->getFieldsToSkipFromTranslationChangesCheck($entity)));
foreach (Element::children($element) as $key) {
if (!isset($element[$key]['#type'])) {
$this->entityFormSharedElements($element[$key], $form_state, $form);
}
else {
// Ignore non-widget form elements.
if (isset($ignored_types[$element[$key]['#type']])) {
continue;
}
// Elements are considered to be non multilingual by default.
if (empty($element[$key]['#multilingual'])) {
// If we are displaying a multilingual entity form we need to provide
// translatability clues, otherwise the non-multilingual form elements
// should be hidden.
if (!$translation_form) {
if ($display_translatability_clue) {
$this->addTranslatabilityClue($element[$key]);
}
// Hide widgets for untranslatable fields.
if ($hide_untranslatable_fields && isset($field_definitions[$key])) {
$element[$key]['#access'] = FALSE;
$display_warning = TRUE;
}
}
else {
$element[$key]['#access'] = FALSE;
}
}
}
}
if ($display_warning) {
$url = $entity->getUntranslated()->toUrl('edit-form')->toString();
$message['warning'][] = $this->t('Fields that apply to all languages are hidden to avoid conflicting changes. <a href=":url">Edit them on the original language form</a>.', [':url' => $url]);
// Explicitly renders this warning message. This prevents repetition on
// AJAX operations or form submission. Other messages will be rendered in
// the default location.
// @see \Drupal\Core\Render\Element\StatusMessages.
$element['hidden_fields_warning_message'] = [
'#theme' => 'status_messages',
'#message_list' => $message,
'#weight' => -100,
'#status_headings' => [
'warning' => $this->t('Warning message'),
],
];
}
return $element;
}
/**
* Adds a clue about the form element translatability.
*
* If the given element does not have a #title attribute, the function is
* recursively applied to child elements.
*
* @param array $element
* A form element array.
*/
protected function addTranslatabilityClue(&$element) {
static $suffix, $fapi_title_elements;
// Elements which can have a #title attribute according to FAPI Reference.
if (!isset($suffix)) {
$suffix = ' <span class="translation-entity-all-languages">(' . t('all languages') . ')</span>';
$fapi_title_elements = array_flip(['checkbox', 'checkboxes', 'date', 'details', 'fieldset', 'file', 'item', 'password', 'password_confirm', 'radio', 'radios', 'select', 'text_format', 'textarea', 'textfield', 'weight']);
}
// Update #title attribute for all elements that are allowed to have a
// #title attribute according to the Form API Reference. The reason for this
// check is because some elements have a #title attribute even though it is
// not rendered; for instance, field containers.
if (isset($element['#type']) && isset($fapi_title_elements[$element['#type']]) && isset($element['#title'])) {
$element['#title'] .= $suffix;
}
// If the current element does not have a (valid) title, try child elements.
elseif ($children = Element::children($element)) {
foreach ($children as $delta) {
$this->addTranslatabilityClue($element[$delta]);
}
}
// If there are no children, fall back to the current #title attribute if it
// exists.
elseif (isset($element['#title'])) {
$element['#title'] .= $suffix;
}
}
/**
* Entity builder method.
*
* @param string $entity_type
* The type of the entity.
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity whose form is being built.
* @param array $form
* A nested array form elements comprising the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
*/
public function entityFormEntityBuild($entity_type, EntityInterface $entity, array $form, FormStateInterface $form_state) {
$form_object = $form_state->getFormObject();
$form_langcode = $form_object->getFormLangcode($form_state);
$values = &$form_state->getValue('content_translation', []);
$metadata = $this->manager->getTranslationMetadata($entity);
$metadata->setAuthor(!empty($values['uid']) ? User::load($values['uid']) : User::load(0));
$metadata->setPublished(!empty($values['status']));
$metadata->setCreatedTime(!empty($values['created']) ? strtotime($values['created']) : $this->time->getRequestTime());
$metadata->setOutdated(!empty($values['outdated']));
if (!empty($values['retranslate'])) {
$this->retranslate($entity, $form_langcode);
}
}
/**
* Form validation handler for ContentTranslationHandler::entityFormAlter().
*
* Validates the submitted content translation metadata.
*/
public function entityFormValidate($form, FormStateInterface $form_state) {
if (!$form_state->isValueEmpty('content_translation')) {
$translation = $form_state->getValue('content_translation');
// Validate the "authored by" field.
if (!empty($translation['uid']) && !($account = User::load($translation['uid']))) {
$form_state->setErrorByName('content_translation][uid', t('The translation authoring username %name does not exist.', ['%name' => $account->getAccountName()]));
}
// Validate the "authored on" field.
if (!empty($translation['created']) && strtotime($translation['created']) === FALSE) {
$form_state->setErrorByName('content_translation][created', t('You have to specify a valid translation authoring date.'));
}
}
}
/**
* Form submission handler for ContentTranslationHandler::entityFormAlter().
*
* Updates metadata fields, which should be updated only after the validation
* has run and before the entity is saved.
*/
public function entityFormSubmit($form, FormStateInterface $form_state) {
/** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
$form_object = $form_state->getFormObject();
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $form_object->getEntity();
// ContentEntityForm::submit will update the changed timestamp on submit
// after the entity has been validated, so that it does not break the
// EntityChanged constraint validator. The content translation metadata
// field for the changed timestamp does not have such a constraint defined
// at the moment, but it is correct to update its value in a submission
// handler as well and have the same logic like in the Form API.
if ($entity->hasField('content_translation_changed')) {
$metadata = $this->manager->getTranslationMetadata($entity);
$metadata->setChangedTime($this->time->getRequestTime());
}
}
/**
* Form submission handler for ContentTranslationHandler::entityFormAlter().
*
* Takes care of the source language change.
*/
public function entityFormSourceChange($form, FormStateInterface $form_state) {
$form_object = $form_state->getFormObject();
$entity = $form_object->getEntity();
$source = $form_state->getValue(['source_langcode', 'source']);
$entity_type_id = $entity->getEntityTypeId();
$form_state->setRedirect("entity.$entity_type_id.content_translation_add", [
$entity_type_id => $entity->id(),
'source' => $source,
'target' => $form_object->getFormLangcode($form_state),
]);
$languages = $this->languageManager->getLanguages();
$this->messenger->addStatus(t('Source language set to: %language', ['%language' => $languages[$source]->getName()]));
}
/**
* Form submission handler for ContentTranslationHandler::entityFormAlter().
*
* Takes care of entity deletion.
*/
public function entityFormDelete($form, FormStateInterface $form_state) {
$form_object = $form_state->getFormObject();
$entity = $form_object->getEntity();
if (count($entity->getTranslationLanguages()) > 1) {
$this->messenger->addWarning(t('This will delete all the translations of %label.', ['%label' => $entity->label() ?? $entity->id()]));
}
}
/**
* Form submission handler for ContentTranslationHandler::entityFormAlter().
*
* Get the entity delete form route url.
*/
protected function entityFormDeleteTranslationUrl(EntityInterface $entity, $form_langcode) {
$entity_type_id = $entity->getEntityTypeId();
$options = [];
$options['query']['destination'] = $this->redirectDestination->get();
if ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form')) {
return $entity->toUrl('delete-form', $options);
}
return Url::fromRoute("entity.$entity_type_id.content_translation_delete", [
$entity_type_id => $entity->id(),
'language' => $form_langcode,
], $options);
}
/**
* Form submission handler for ContentTranslationHandler::entityFormAlter().
*
* Takes care of content translation deletion.
*/
public function entityFormDeleteTranslation($form, FormStateInterface $form_state) {
@trigger_error('Calling ContentTranslationHandler::entityFormDeleteTranslation() is deprecated in drupal:10.2.0 and will be removed in drupal:11.0.0. See https://www.drupal.org/node/3375492', E_USER_DEPRECATED);
/** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
$form_object = $form_state->getFormObject();
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $form_object->getEntity();
$entity_type_id = $entity->getEntityTypeId();
if ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form')) {
$form_state->setRedirectUrl($entity->toUrl('delete-form'));
}
else {
$form_state->setRedirect("entity.$entity_type_id.content_translation_delete", [
$entity_type_id => $entity->id(),
'language' => $form_object->getFormLangcode($form_state),
]);
}
}
/**
* Returns the title to be used for the entity form page.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity whose form is being altered.
*
* @return string|null
* The label of the entity, or NULL if there is no label defined.
*/
protected function entityFormTitle(EntityInterface $entity) {
return $entity->label();
}
/**
* Default value callback for the owner base field definition.
*
* @return int
* The user ID.
*/
public static function getDefaultOwnerId() {
return \Drupal::currentUser()->id();
}
}

View File

@@ -0,0 +1,73 @@
<?php
namespace Drupal\content_translation;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Interface for providing content translation.
*
* Defines a set of methods to allow any entity to be processed by the entity
* translation UI.
*/
interface ContentTranslationHandlerInterface {
/**
* Returns a set of field definitions to be used to store metadata items.
*
* @return \Drupal\Core\Field\FieldDefinitionInterface[]
*/
public function getFieldDefinitions();
/**
* Checks that the user can perform the operation on the entity translation.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity whose translation has to be accessed.
* @param $op
* The operation to be performed on the translation. Possible values are:
* - "create"
* - "update"
* - "delete"
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function getTranslationAccess(EntityInterface $entity, $op);
/**
* Retrieves the source language for the translation being created.
*
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @return string
* The source language code.
*/
public function getSourceLangcode(FormStateInterface $form_state);
/**
* Marks translations as outdated.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity being translated.
* @param string $langcode
* (optional) The language code of the updated language: all the other
* translations will be marked as outdated. Defaults to the entity language.
*/
public function retranslate(EntityInterface $entity, $langcode = NULL);
/**
* Performs the needed alterations to the entity form.
*
* @param array $form
* The entity form to be altered to provide the translation workflow.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity being created or edited.
*/
public function entityFormAlter(array &$form, FormStateInterface $form_state, EntityInterface $entity);
}

View File

@@ -0,0 +1,191 @@
<?php
namespace Drupal\content_translation;
use Drupal\Core\Entity\EntityInterface;
use Drupal\workflows\Entity\Workflow;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
/**
* Provides common functionality for content translation.
*/
class ContentTranslationManager implements ContentTranslationManagerInterface, BundleTranslationSettingsInterface {
/**
* The entity type bundle info provider.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $entityTypeBundleInfo;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a ContentTranslationManageAccessCheck object.
*
* @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 provider.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info) {
$this->entityTypeManager = $entity_type_manager;
$this->entityTypeBundleInfo = $entity_type_bundle_info;
}
/**
* {@inheritdoc}
*/
public function getTranslationHandler($entity_type_id) {
return $this->entityTypeManager->getHandler($entity_type_id, 'translation');
}
/**
* {@inheritdoc}
*/
public function getTranslationMetadata(EntityInterface $translation) {
// We need a new instance of the metadata handler wrapping each translation.
$entity_type = $translation->getEntityType();
$class = $entity_type->get('content_translation_metadata');
return new $class($translation, $this->getTranslationHandler($entity_type->id()));
}
/**
* {@inheritdoc}
*/
public function isSupported($entity_type_id) {
$entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
return $entity_type->isTranslatable() && ($entity_type->hasLinkTemplate('drupal:content-translation-overview') || $entity_type->get('content_translation_ui_skip'));
}
/**
* {@inheritdoc}
*/
public function getSupportedEntityTypes() {
$supported_types = [];
foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
if ($this->isSupported($entity_type_id)) {
$supported_types[$entity_type_id] = $entity_type;
}
}
return $supported_types;
}
/**
* {@inheritdoc}
*/
public function setEnabled($entity_type_id, $bundle, $value) {
$config = $this->loadContentLanguageSettings($entity_type_id, $bundle);
$config->setThirdPartySetting('content_translation', 'enabled', $value)->save();
}
/**
* {@inheritdoc}
*/
public function isEnabled($entity_type_id, $bundle = NULL) {
$enabled = FALSE;
if ($this->isSupported($entity_type_id)) {
$bundles = !empty($bundle) ? [$bundle] : array_keys($this->entityTypeBundleInfo->getBundleInfo($entity_type_id));
foreach ($bundles as $bundle) {
$config = $this->loadContentLanguageSettings($entity_type_id, $bundle);
if ($config->getThirdPartySetting('content_translation', 'enabled', FALSE)) {
$enabled = TRUE;
break;
}
}
}
return $enabled;
}
/**
* {@inheritdoc}
*/
public function setBundleTranslationSettings($entity_type_id, $bundle, array $settings) {
$config = $this->loadContentLanguageSettings($entity_type_id, $bundle);
$config->setThirdPartySetting('content_translation', 'bundle_settings', $settings)
->save();
}
/**
* {@inheritdoc}
*/
public function getBundleTranslationSettings($entity_type_id, $bundle) {
$config = $this->loadContentLanguageSettings($entity_type_id, $bundle);
return $config->getThirdPartySetting('content_translation', 'bundle_settings', []);
}
/**
* Loads a content language config entity based on the entity type and bundle.
*
* @param string $entity_type_id
* ID of the entity type.
* @param string $bundle
* Bundle name.
*
* @return \Drupal\language\Entity\ContentLanguageSettings
* The content language config entity if one exists. Otherwise, returns
* default values.
*/
protected function loadContentLanguageSettings($entity_type_id, $bundle) {
if ($entity_type_id == NULL || $bundle == NULL) {
return NULL;
}
$config = $this->entityTypeManager->getStorage('language_content_settings')->load($entity_type_id . '.' . $bundle);
if ($config == NULL) {
$config = $this->entityTypeManager->getStorage('language_content_settings')->create(['target_entity_type_id' => $entity_type_id, 'target_bundle' => $bundle]);
}
return $config;
}
/**
* Checks whether support for pending revisions should be enabled.
*
* @param string $entity_type_id
* The ID of the entity type to be checked.
* @param string $bundle_id
* (optional) The ID of the bundle to be checked. Defaults to none.
*
* @return bool
* TRUE if pending revisions should be enabled, FALSE otherwise.
*
* @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
*/
public static function isPendingRevisionSupportEnabled($entity_type_id, $bundle_id = NULL) {
if (!\Drupal::moduleHandler()->moduleExists('content_moderation')) {
return FALSE;
}
foreach (Workflow::loadMultipleByType('content_moderation') as $workflow) {
/** @var \Drupal\content_moderation\Plugin\WorkflowType\ContentModeration $plugin */
$plugin = $workflow->getTypePlugin();
$entity_type_ids = array_flip($plugin->getEntityTypes());
if (isset($entity_type_ids[$entity_type_id])) {
if (!isset($bundle_id)) {
return TRUE;
}
else {
$bundle_ids = array_flip($plugin->getBundlesForEntityType($entity_type_id));
if (isset($bundle_ids[$bundle_id])) {
return TRUE;
}
}
}
}
return FALSE;
}
}

View File

@@ -0,0 +1,80 @@
<?php
namespace Drupal\content_translation;
use Drupal\Core\Entity\EntityInterface;
/**
* Provides an interface for common functionality for content translation.
*/
interface ContentTranslationManagerInterface {
/**
* Gets the entity types that support content translation.
*
* @return \Drupal\Core\Entity\EntityTypeInterface[]
* An array of entity types that support content translation.
*/
public function getSupportedEntityTypes();
/**
* Checks whether an entity type supports translation.
*
* @param string $entity_type_id
* The entity type.
*
* @return bool
* TRUE if an entity type is supported, FALSE otherwise.
*/
public function isSupported($entity_type_id);
/**
* Returns an instance of the Content translation handler.
*
* @param string $entity_type_id
* The type of the entity being translated.
*
* @return \Drupal\content_translation\ContentTranslationHandlerInterface
* An instance of the content translation handler.
*/
public function getTranslationHandler($entity_type_id);
/**
* Returns an instance of the Content translation metadata.
*
* @param \Drupal\Core\Entity\EntityInterface $translation
* The entity translation whose metadata needs to be retrieved.
*
* @return \Drupal\content_translation\ContentTranslationMetadataWrapperInterface
* An instance of the content translation metadata.
*/
public function getTranslationMetadata(EntityInterface $translation);
/**
* Sets the value for translatability of the given entity type bundle.
*
* @param string $entity_type_id
* The entity type.
* @param string $bundle
* The bundle of the entity.
* @param bool $value
* The boolean value we need to save.
*/
public function setEnabled($entity_type_id, $bundle, $value);
/**
* Determines whether the given entity type is translatable.
*
* @param string $entity_type_id
* The type of the entity.
* @param string $bundle
* (optional) The bundle of the entity. If no bundle is provided, all the
* available bundles are checked.
*
* @return bool
* TRUE if the specified bundle is translatable. If no bundle is provided
* returns TRUE if at least one of the entity bundles is translatable.
*/
public function isEnabled($entity_type_id, $bundle = NULL);
}

View File

@@ -0,0 +1,150 @@
<?php
namespace Drupal\content_translation;
use Drupal\Core\Entity\EntityInterface;
use Drupal\user\UserInterface;
/**
* Base class for content translation metadata wrappers.
*/
class ContentTranslationMetadataWrapper implements ContentTranslationMetadataWrapperInterface {
/**
* The wrapped entity translation.
*
* @var \Drupal\Core\Entity\FieldableEntityInterface|\Drupal\Core\TypedData\TranslatableInterface
*/
protected $translation;
/**
* The content translation handler.
*
* @var \Drupal\content_translation\ContentTranslationHandlerInterface
*/
protected $handler;
/**
* Initializes an instance of the content translation metadata handler.
*
* @param \Drupal\Core\Entity\EntityInterface $translation
* The entity translation to be wrapped.
* @param ContentTranslationHandlerInterface $handler
* The content translation handler.
*/
public function __construct(EntityInterface $translation, ContentTranslationHandlerInterface $handler) {
$this->translation = $translation;
$this->handler = $handler;
}
/**
* {@inheritdoc}
*/
public function getSource() {
return $this->translation->get('content_translation_source')->value;
}
/**
* {@inheritdoc}
*/
public function setSource($source) {
$this->translation->set('content_translation_source', $source);
return $this;
}
/**
* {@inheritdoc}
*/
public function isOutdated() {
return (bool) $this->translation->get('content_translation_outdated')->value;
}
/**
* {@inheritdoc}
*/
public function setOutdated($outdated) {
$this->translation->set('content_translation_outdated', $outdated);
return $this;
}
/**
* {@inheritdoc}
*/
public function getAuthor() {
return $this->translation->hasField('content_translation_uid') ? $this->translation->get('content_translation_uid')->entity : $this->translation->getOwner();
}
/**
* {@inheritdoc}
*/
public function setAuthor(UserInterface $account) {
$field_name = $this->translation->hasField('content_translation_uid') ? 'content_translation_uid' : 'uid';
$this->setFieldOnlyIfTranslatable($field_name, $account->id());
return $this;
}
/**
* {@inheritdoc}
*/
public function isPublished() {
$field_name = $this->translation->hasField('content_translation_status') ? 'content_translation_status' : 'status';
return (bool) $this->translation->get($field_name)->value;
}
/**
* {@inheritdoc}
*/
public function setPublished($published) {
$field_name = $this->translation->hasField('content_translation_status') ? 'content_translation_status' : 'status';
$this->setFieldOnlyIfTranslatable($field_name, $published);
return $this;
}
/**
* {@inheritdoc}
*/
public function getCreatedTime() {
$field_name = $this->translation->hasField('content_translation_created') ? 'content_translation_created' : 'created';
return $this->translation->get($field_name)->value;
}
/**
* {@inheritdoc}
*/
public function setCreatedTime($timestamp) {
$field_name = $this->translation->hasField('content_translation_created') ? 'content_translation_created' : 'created';
$this->setFieldOnlyIfTranslatable($field_name, $timestamp);
return $this;
}
/**
* {@inheritdoc}
*/
public function getChangedTime() {
return $this->translation->hasField('content_translation_changed') ? $this->translation->get('content_translation_changed')->value : $this->translation->getChangedTime();
}
/**
* {@inheritdoc}
*/
public function setChangedTime($timestamp) {
$field_name = $this->translation->hasField('content_translation_changed') ? 'content_translation_changed' : 'changed';
$this->setFieldOnlyIfTranslatable($field_name, $timestamp);
return $this;
}
/**
* Updates a field value, only if the field is translatable.
*
* @param string $field_name
* The name of the field.
* @param mixed $value
* The field value to be set.
*/
protected function setFieldOnlyIfTranslatable($field_name, $value) {
if ($this->translation->getFieldDefinition($field_name)->isTranslatable()) {
$this->translation->set($field_name, $value);
}
}
}

View File

@@ -0,0 +1,131 @@
<?php
namespace Drupal\content_translation;
use Drupal\user\UserInterface;
/**
* Common interface for content translation metadata wrappers.
*
* This acts as a wrapper for an entity translation object, encapsulating the
* logic needed to retrieve translation metadata.
*/
interface ContentTranslationMetadataWrapperInterface {
/**
* Retrieves the source language for this translation.
*
* @return string
* The source language code.
*/
public function getSource();
/**
* Sets the source language for this translation.
*
* @param string $source
* The source language code.
*
* @return $this
*/
public function setSource($source);
/**
* Returns the translation outdated status.
*
* @return bool
* TRUE if the translation is outdated, FALSE otherwise.
*/
public function isOutdated();
/**
* Sets the translation outdated status.
*
* @param bool $outdated
* TRUE if the translation is outdated, FALSE otherwise.
*
* @return $this
*/
public function setOutdated($outdated);
/**
* Returns the translation author.
*
* @return \Drupal\user\UserInterface
* The user entity for the translation author.
*/
public function getAuthor();
/**
* Sets the translation author.
*
* The metadata field will be updated, only if it's translatable.
*
* @param \Drupal\user\UserInterface $account
* The translation author user entity.
*
* @return $this
*/
public function setAuthor(UserInterface $account);
/**
* Returns the translation published status.
*
* @return bool
* TRUE if the translation is published, FALSE otherwise.
*/
public function isPublished();
/**
* Sets the translation published status.
*
* The metadata field will be updated, only if it's translatable.
*
* @param bool $published
* TRUE if the translation is published, FALSE otherwise.
*
* @return $this
*/
public function setPublished($published);
/**
* Returns the translation creation timestamp.
*
* @return int
* The UNIX timestamp of when the translation was created.
*/
public function getCreatedTime();
/**
* Sets the translation creation timestamp.
*
* The metadata field will be updated, only if it's translatable.
*
* @param int $timestamp
* The UNIX timestamp of when the translation was created.
*
* @return $this
*/
public function setCreatedTime($timestamp);
/**
* Returns the timestamp of the last entity change from current translation.
*
* @return int
* The timestamp of the last entity save operation.
*/
public function getChangedTime();
/**
* Sets the translation modification timestamp.
*
* The metadata field will be updated, only if it's translatable.
*
* @param int $timestamp
* The UNIX timestamp of when the translation was last modified.
*
* @return $this
*/
public function setChangedTime($timestamp);
}

View File

@@ -0,0 +1,134 @@
<?php
namespace Drupal\content_translation;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides dynamic permissions for the content_translation module.
*/
class ContentTranslationPermissions implements ContainerInjectionInterface {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity bundle info.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $entityTypeBundleInfo;
/**
* The content translation manager.
*
* @var \Drupal\content_translation\ContentTranslationManagerInterface
*/
protected $contentTranslationManager;
/**
* Constructs a ContentTranslationPermissions instance.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\content_translation\ContentTranslationManagerInterface $content_translation_manager
* The content translation manager.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle info.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, ContentTranslationManagerInterface $content_translation_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info) {
$this->entityTypeManager = $entity_type_manager;
$this->contentTranslationManager = $content_translation_manager;
$this->entityTypeBundleInfo = $entity_type_bundle_info;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('content_translation.manager'),
$container->get('entity_type.bundle.info')
);
}
/**
* Returns an array of content translation permissions.
*
* @return array
*/
public function contentPermissions() {
$permissions = [];
// Create a translate permission for each enabled entity type and (optionally)
// bundle.
foreach ($this->entityTypeManager->getDefinitions() as $entity_type_id => $entity_type) {
if ($permission_granularity = $entity_type->getPermissionGranularity()) {
switch ($permission_granularity) {
case 'bundle':
foreach ($this->entityTypeBundleInfo->getBundleInfo($entity_type_id) as $bundle => $bundle_info) {
if ($this->contentTranslationManager->isEnabled($entity_type_id, $bundle)) {
$permissions["translate $bundle $entity_type_id"] = $this->buildBundlePermission($entity_type, $bundle, $bundle_info);
}
}
break;
case 'entity_type':
if ($this->contentTranslationManager->isEnabled($entity_type_id)) {
$permissions["translate $entity_type_id"] = [
'title' => $this->t('Translate @entity_label', ['@entity_label' => $entity_type->getSingularLabel()]),
'dependencies' => ['module' => [$entity_type->getProvider()]],
];
}
break;
}
}
}
return $permissions;
}
/**
* Builds a content translation permission array for a bundle.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
* @param string $bundle
* The bundle to build the translation permission for.
* @param array $bundle_info
* The bundle info.
*
* @return array
* The permission details, keyed by 'title' and 'dependencies'.
*/
private function buildBundlePermission(EntityTypeInterface $entity_type, string $bundle, array $bundle_info) {
$permission = [
'title' => $this->t('Translate %bundle_label @entity_label', [
'@entity_label' => $entity_type->getSingularLabel(),
'%bundle_label' => $bundle_info['label'] ?? $bundle,
]),
];
// If the entity type uses bundle entities, add a dependency on the bundle.
$bundle_entity_type = $entity_type->getBundleEntityType();
if ($bundle_entity_type && $bundle_entity = $this->entityTypeManager->getStorage($bundle_entity_type)->load($bundle)) {
$permission['dependencies'][$bundle_entity->getConfigDependencyKey()][] = $bundle_entity->getConfigDependencyName();
}
else {
$permission['dependencies']['module'][] = $entity_type->getProvider();
}
return $permission;
}
}

View File

@@ -0,0 +1,463 @@
<?php
namespace Drupal\content_translation\Controller;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\content_translation\ContentTranslationManager;
use Drupal\content_translation\ContentTranslationManagerInterface;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Base class for entity translation controllers.
*/
class ContentTranslationController extends ControllerBase {
/**
* The content translation manager.
*
* @var \Drupal\content_translation\ContentTranslationManagerInterface
*/
protected $manager;
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* Initializes a content translation controller.
*
* @param \Drupal\content_translation\ContentTranslationManagerInterface $manager
* A content translation manager instance.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager service.
* @param \Drupal\Component\Datetime\TimeInterface|null $time
* The time service.
*/
public function __construct(ContentTranslationManagerInterface $manager, EntityFieldManagerInterface $entity_field_manager, protected ?TimeInterface $time = NULL) {
$this->manager = $manager;
$this->entityFieldManager = $entity_field_manager;
if ($this->time === NULL) {
@trigger_error('Calling ' . __METHOD__ . ' without the $time argument is deprecated in drupal:10.3.0 and it will be required in drupal:11.0.0. See https://www.drupal.org/node/3112298', E_USER_DEPRECATED);
$this->time = \Drupal::service('datetime.time');
}
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('content_translation.manager'),
$container->get('entity_field.manager'),
$container->get('datetime.time'),
);
}
/**
* Populates target values with the source values.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity being translated.
* @param \Drupal\Core\Language\LanguageInterface $source
* The language to be used as source.
* @param \Drupal\Core\Language\LanguageInterface $target
* The language to be used as target.
*/
public function prepareTranslation(ContentEntityInterface $entity, LanguageInterface $source, LanguageInterface $target) {
$source_langcode = $source->getId();
/** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
$storage = $this->entityTypeManager()->getStorage($entity->getEntityTypeId());
// Once translations from the default revision are added, there may be
// additional draft translations that don't exist in the default revision.
// Add those translations too so that they aren't deleted when the new
// translation is saved.
/** @var \Drupal\Core\Entity\ContentEntityInterface $default_revision */
$default_revision = $storage->load($entity->id());
// Check the entity isn't missing any translations.
$languages = $this->languageManager()->getLanguages();
foreach ($languages as $language) {
$langcode = $language->getId();
if ($entity->hasTranslation($langcode) || $target->getId() === $langcode) {
continue;
}
$latest_revision_id = $storage->getLatestTranslationAffectedRevisionId($entity->id(), $langcode);
if ($latest_revision_id) {
if ($default_revision->hasTranslation($langcode)) {
$existing_translation = $default_revision->getTranslation($langcode);
$existing_translation->setNewRevision(FALSE);
$existing_translation->isDefaultRevision(FALSE);
$existing_translation->setRevisionTranslationAffected(FALSE);
$entity->addTranslation($langcode, $existing_translation->toArray());
}
}
}
/** @var \Drupal\Core\Entity\ContentEntityInterface $source_translation */
$source_translation = $entity->getTranslation($source_langcode);
$target_translation = $entity->addTranslation($target->getId(), $source_translation->toArray());
// Make sure we do not inherit the affected status from the source values.
if ($entity->getEntityType()->isRevisionable()) {
$target_translation->setRevisionTranslationAffected(NULL);
}
/** @var \Drupal\user\UserInterface $user */
$user = $this->entityTypeManager()->getStorage('user')->load($this->currentUser()->id());
$metadata = $this->manager->getTranslationMetadata($target_translation);
// Update the translation author to current user, as well the translation
// creation time.
$metadata->setAuthor($user);
$metadata->setCreatedTime($this->time->getRequestTime());
$metadata->setSource($source_langcode);
}
/**
* Builds the translations overview page.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match.
* @param string $entity_type_id
* (optional) The entity type ID.
*
* @return array
* Array of page elements to render.
*/
public function overview(RouteMatchInterface $route_match, $entity_type_id = NULL) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $route_match->getParameter($entity_type_id);
$account = $this->currentUser();
$handler = $this->entityTypeManager()->getHandler($entity_type_id, 'translation');
$manager = $this->manager;
$entity_type = $entity->getEntityType();
$use_latest_revisions = $entity_type->isRevisionable() && ContentTranslationManager::isPendingRevisionSupportEnabled($entity_type_id, $entity->bundle());
// Start collecting the cacheability metadata, starting with the entity and
// later merge in the access result cacheability metadata.
$cacheability = CacheableMetadata::createFromObject($entity);
$languages = $this->languageManager()->getLanguages();
$original = $entity->getUntranslated()->language()->getId();
$translations = $entity->getTranslationLanguages();
$field_ui = $this->moduleHandler()->moduleExists('field_ui') && $account->hasPermission('administer ' . $entity_type_id . ' fields');
$rows = [];
$show_source_column = FALSE;
/** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
$storage = $this->entityTypeManager()->getStorage($entity_type_id);
$default_revision = $storage->load($entity->id());
if ($this->languageManager()->isMultilingual()) {
// Determine whether the current entity is translatable.
$translatable = FALSE;
foreach ($this->entityFieldManager->getFieldDefinitions($entity_type_id, $entity->bundle()) as $instance) {
if ($instance->isTranslatable()) {
$translatable = TRUE;
break;
}
}
// Show source-language column if there are non-original source langcodes.
$additional_source_langcodes = array_filter(array_keys($translations), function ($langcode) use ($entity, $original, $manager) {
$source = $manager->getTranslationMetadata($entity->getTranslation($langcode))->getSource();
return $source != $original && $source != LanguageInterface::LANGCODE_NOT_SPECIFIED;
});
$show_source_column = !empty($additional_source_langcodes);
foreach ($languages as $language) {
$language_name = $language->getName();
$langcode = $language->getId();
// If the entity type is revisionable, we may have pending revisions
// with translations not available yet in the default revision. Thus we
// need to load the latest translation-affecting revision for each
// language to be sure we are listing all available translations.
if ($use_latest_revisions) {
$entity = $default_revision;
$latest_revision_id = $storage->getLatestTranslationAffectedRevisionId($entity->id(), $langcode);
if ($latest_revision_id) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $latest_revision */
$latest_revision = $storage->loadRevision($latest_revision_id);
// Make sure we do not list removed translations, i.e. translations
// that have been part of a default revision but no longer are.
if (!$latest_revision->wasDefaultRevision() || $default_revision->hasTranslation($langcode)) {
$entity = $latest_revision;
}
}
$translations = $entity->getTranslationLanguages();
}
$options = ['language' => $language];
$add_url = $entity->toUrl('drupal:content-translation-add', $options)
->setRouteParameter('source', $original)
->setRouteParameter('target', $language->getId());
$edit_url = $entity->toUrl('drupal:content-translation-edit', $options)
->setRouteParameter('language', $language->getId());
$delete_url = $entity->toUrl('drupal:content-translation-delete', $options)
->setRouteParameter('language', $language->getId());
$operations = [
'data' => [
'#type' => 'operations',
'#links' => [],
],
];
$links = &$operations['data']['#links'];
if (array_key_exists($langcode, $translations)) {
// Existing translation in the translation set: display status.
$translation = $entity->getTranslation($langcode);
$metadata = $manager->getTranslationMetadata($translation);
$source = $metadata->getSource() ?: LanguageInterface::LANGCODE_NOT_SPECIFIED;
$is_original = $langcode == $original;
$label = $entity->getTranslation($langcode)->label() ?? $entity->id();
$link = ['url' => $entity->toUrl()];
if (!empty($link['url'])) {
$link['url']->setOption('language', $language);
$row_title = Link::fromTextAndUrl($label, $link['url'])->toString();
}
if (empty($link['url'])) {
$row_title = $is_original ? $label : $this->t('n/a');
}
// If the user is allowed to edit the entity we point the edit link to
// the entity form, otherwise if we are not dealing with the original
// language we point the link to the translation form.
$update_access = $entity->access('update', NULL, TRUE);
$translation_access = $handler->getTranslationAccess($entity, 'update');
$cacheability = $cacheability
->merge(CacheableMetadata::createFromObject($update_access))
->merge(CacheableMetadata::createFromObject($translation_access));
if ($update_access->isAllowed() && $entity_type->hasLinkTemplate('edit-form')) {
$links['edit']['url'] = $entity->toUrl('edit-form');
$links['edit']['language'] = $language;
}
elseif (!$is_original && $translation_access->isAllowed()) {
$links['edit']['url'] = $edit_url;
}
if (isset($links['edit'])) {
$links['edit']['title'] = $this->t('Edit');
}
$status = [
'data' => [
'#type' => 'inline_template',
'#template' => '<span class="status">{% if status %}{{ "Published"|t }}{% else %}{{ "Not published"|t }}{% endif %}</span>{% if outdated %} <span class="marker">{{ "outdated"|t }}</span>{% endif %}',
'#context' => [
'status' => $metadata->isPublished(),
'outdated' => $metadata->isOutdated(),
],
],
];
if ($is_original) {
$language_name = $this->t('<strong>@language_name (Original language)</strong>', ['@language_name' => $language_name]);
$source_name = $this->t('n/a');
}
else {
/** @var \Drupal\Core\Access\AccessResultInterface $delete_route_access */
$delete_route_access = \Drupal::service('content_translation.delete_access')->checkAccess($translation);
$cacheability->addCacheableDependency($delete_route_access);
if ($delete_route_access->isAllowed()) {
$source_name = isset($languages[$source]) ? $languages[$source]->getName() : $this->t('n/a');
$delete_access = $entity->access('delete', NULL, TRUE);
$translation_access = $handler->getTranslationAccess($entity, 'delete');
$cacheability
->addCacheableDependency($delete_access)
->addCacheableDependency($translation_access);
if ($delete_access->isAllowed() && $entity_type->hasLinkTemplate('delete-form')) {
$links['delete'] = [
'title' => $this->t('Delete'),
'url' => $entity->toUrl('delete-form'),
'language' => $language,
];
}
elseif ($translation_access->isAllowed()) {
$links['delete'] = [
'title' => $this->t('Delete'),
'url' => $delete_url,
];
}
}
else {
$this->messenger()->addWarning($this->t('The "Delete translation" action is only available for published translations.'), FALSE);
}
}
}
else {
// No such translation in the set yet: help user to create it.
$row_title = $source_name = $this->t('n/a');
$source = $entity->language()->getId();
$create_translation_access = $handler->getTranslationAccess($entity, 'create');
$cacheability = $cacheability
->merge(CacheableMetadata::createFromObject($create_translation_access));
if ($source != $langcode && $create_translation_access->isAllowed()) {
if ($translatable) {
$links['add'] = [
'title' => $this->t('Add'),
'url' => $add_url,
];
}
elseif ($field_ui) {
$url = new Url('language.content_settings_page');
// Link directly to the fields tab to make it easier to find the
// setting to enable translation on fields.
$links['nofields'] = [
'title' => $this->t('No translatable fields'),
'url' => $url,
];
}
}
$status = $this->t('Not translated');
}
if ($show_source_column) {
$rows[] = [
$language_name,
$row_title,
$source_name,
$status,
$operations,
];
}
else {
$rows[] = [$language_name, $row_title, $status, $operations];
}
}
}
if ($show_source_column) {
$header = [
$this->t('Language'),
$this->t('Translation'),
$this->t('Source language'),
$this->t('Status'),
$this->t('Operations'),
];
}
else {
$header = [
$this->t('Language'),
$this->t('Translation'),
$this->t('Status'),
$this->t('Operations'),
];
}
$build['#title'] = $this->t('Translations of %label', ['%label' => $entity->label() ?? $entity->id()]);
// Add metadata to the build render array to let other modules know about
// which entity this is.
$build['#entity'] = $entity;
$cacheability
->addCacheTags($entity->getCacheTags())
->applyTo($build);
$build['content_translation_overview'] = [
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
];
return $build;
}
/**
* Builds an add translation page.
*
* @param \Drupal\Core\Language\LanguageInterface $source
* The language of the values being translated. Defaults to the entity
* language.
* @param \Drupal\Core\Language\LanguageInterface $target
* The language of the translated values. Defaults to the current content
* language.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match object from which to extract the entity type.
* @param string $entity_type_id
* (optional) The entity type ID.
*
* @return array
* A processed form array ready to be rendered.
*/
public function add(LanguageInterface $source, LanguageInterface $target, RouteMatchInterface $route_match, $entity_type_id = NULL) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $route_match->getParameter($entity_type_id);
// In case of a pending revision, make sure we load the latest
// translation-affecting revision for the source language, otherwise the
// initial form values may not be up-to-date.
if (!$entity->isDefaultRevision() && ContentTranslationManager::isPendingRevisionSupportEnabled($entity_type_id, $entity->bundle())) {
/** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
$storage = $this->entityTypeManager()->getStorage($entity->getEntityTypeId());
$revision_id = $storage->getLatestTranslationAffectedRevisionId($entity->id(), $source->getId());
if ($revision_id != $entity->getRevisionId()) {
$entity = $storage->loadRevision($revision_id);
}
}
// @todo Exploit the upcoming hook_entity_prepare() when available.
// See https://www.drupal.org/node/1810394.
$this->prepareTranslation($entity, $source, $target);
// @todo Provide a way to figure out the default form operation. Maybe like
// $operation = isset($info['default_operation']) ? $info['default_operation'] : 'default';
// See https://www.drupal.org/node/2006348.
// Use the add form handler, if available, otherwise default.
$operation = $entity->getEntityType()->hasHandlerClass('form', 'add') ? 'add' : 'default';
$form_state_additions = [];
$form_state_additions['langcode'] = $target->getId();
$form_state_additions['content_translation']['source'] = $source;
$form_state_additions['content_translation']['target'] = $target;
$form_state_additions['content_translation']['translation_form'] = !$entity->access('update');
return $this->entityFormBuilder()->getForm($entity, $operation, $form_state_additions);
}
/**
* Builds the edit translation page.
*
* @param \Drupal\Core\Language\LanguageInterface $language
* The language of the translated values. Defaults to the current content
* language.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The route match object from which to extract the entity type.
* @param string $entity_type_id
* (optional) The entity type ID.
*
* @return array
* A processed form array ready to be rendered.
*/
public function edit(LanguageInterface $language, RouteMatchInterface $route_match, $entity_type_id = NULL) {
$entity = $route_match->getParameter($entity_type_id);
// @todo Provide a way to figure out the default form operation. Maybe like
// $operation = isset($info['default_operation']) ? $info['default_operation'] : 'default';
// See https://www.drupal.org/node/2006348.
// Use the edit form handler, if available, otherwise default.
$operation = $entity->getEntityType()->hasHandlerClass('form', 'edit') ? 'edit' : 'default';
$form_state_additions = [];
$form_state_additions['langcode'] = $language->getId();
$form_state_additions['content_translation']['translation_form'] = TRUE;
return $this->entityFormBuilder()->getForm($entity, $operation, $form_state_additions);
}
}

View File

@@ -0,0 +1,355 @@
<?php
namespace Drupal\content_translation;
use Drupal\Core\Config\Entity\ThirdPartySettingsInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldTypePluginManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
/**
* Provides field translation synchronization capabilities.
*/
class FieldTranslationSynchronizer implements FieldTranslationSynchronizerInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The field type plugin manager.
*
* @var \Drupal\Core\Field\FieldTypePluginManagerInterface
*/
protected $fieldTypeManager;
/**
* Constructs a FieldTranslationSynchronizer object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_manager
* The field type plugin manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, FieldTypePluginManagerInterface $field_type_manager) {
$this->entityTypeManager = $entity_type_manager;
$this->fieldTypeManager = $field_type_manager;
}
/**
* {@inheritdoc}
*/
public function getFieldSynchronizedProperties(FieldDefinitionInterface $field_definition) {
$properties = [];
$settings = $this->getFieldSynchronizationSettings($field_definition);
foreach ($settings as $group => $translatable) {
if (!$translatable) {
$field_type_definition = $this->fieldTypeManager->getDefinition($field_definition->getType());
if (!empty($field_type_definition['column_groups'][$group]['columns'])) {
$properties = array_merge($properties, $field_type_definition['column_groups'][$group]['columns']);
}
}
}
return $properties;
}
/**
* Returns the synchronization settings for the specified field.
*
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* A field definition.
*
* @return string[]
* An array of synchronized field property names.
*/
protected function getFieldSynchronizationSettings(FieldDefinitionInterface $field_definition) {
if ($field_definition instanceof ThirdPartySettingsInterface && $field_definition->isTranslatable()) {
return $field_definition->getThirdPartySetting('content_translation', 'translation_sync', []);
}
return [];
}
/**
* {@inheritdoc}
*/
public function synchronizeFields(ContentEntityInterface $entity, $sync_langcode, $original_langcode = NULL) {
$translations = $entity->getTranslationLanguages();
// If we have no information about what to sync to, if we are creating a new
// entity, if we have no translations for the current entity and we are not
// creating one, then there is nothing to synchronize.
if (empty($sync_langcode) || $entity->isNew() || count($translations) < 2) {
return;
}
// If the entity language is being changed there is nothing to synchronize.
$entity_unchanged = $this->getOriginalEntity($entity);
if ($entity->getUntranslated()->language()->getId() != $entity_unchanged->getUntranslated()->language()->getId()) {
return;
}
if ($entity->isNewRevision()) {
if ($entity->isDefaultTranslationAffectedOnly()) {
// If changes to untranslatable fields are configured to affect only the
// default translation, we need to skip synchronization in pending
// revisions, otherwise multiple translations would be affected.
if (!$entity->isDefaultRevision()) {
return;
}
// When this mode is enabled, changes to synchronized properties are
// allowed only in the default translation, thus we need to make sure this
// is always used as source for the synchronization process.
else {
$sync_langcode = $entity->getUntranslated()->language()->getId();
}
}
elseif ($entity->isDefaultRevision()) {
// If a new default revision is being saved, but a newer default
// revision was created meanwhile, use any other translation as source
// for synchronization, since that will have been merged from the
// default revision. In this case the actual language does not matter as
// synchronized properties are the same for all the translations in the
// default revision.
/** @var \Drupal\Core\Entity\ContentEntityInterface $default_revision */
$default_revision = $this->entityTypeManager
->getStorage($entity->getEntityTypeId())
->load($entity->id());
if ($default_revision->getLoadedRevisionId() !== $entity->getLoadedRevisionId()) {
$other_langcodes = array_diff_key($default_revision->getTranslationLanguages(), [$sync_langcode => FALSE]);
if ($other_langcodes) {
$sync_langcode = key($other_langcodes);
}
}
}
}
/** @var \Drupal\Core\Field\FieldItemListInterface $items */
foreach ($entity as $field_name => $items) {
$field_definition = $items->getFieldDefinition();
$field_type_definition = $this->fieldTypeManager->getDefinition($field_definition->getType());
$column_groups = $field_type_definition['column_groups'];
// Sync if the field is translatable, not empty, and the synchronization
// setting is enabled.
if (($translation_sync = $this->getFieldSynchronizationSettings($field_definition)) && !$items->isEmpty()) {
// Retrieve all the untranslatable column groups and merge them into
// single list.
$groups = array_keys(array_diff($translation_sync, array_filter($translation_sync)));
// If a group was selected has the require_all_groups_for_translation
// flag set, there are no untranslatable columns. This is done because
// the UI adds JavaScript that disables the other checkboxes, so their
// values are not saved.
foreach (array_filter($translation_sync) as $group) {
if (!empty($column_groups[$group]['require_all_groups_for_translation'])) {
$groups = [];
break;
}
}
if (!empty($groups)) {
$columns = [];
foreach ($groups as $group) {
$info = $column_groups[$group];
// A missing 'columns' key indicates we have a single-column group.
$columns = array_merge($columns, $info['columns'] ?? [$group]);
}
if (!empty($columns)) {
$values = [];
foreach ($translations as $langcode => $language) {
$values[$langcode] = $entity->getTranslation($langcode)->get($field_name)->getValue();
}
// If a translation is being created, the original values should be
// used as the unchanged items. In fact there are no unchanged items
// to check against.
$langcode = $original_langcode ?: $sync_langcode;
$unchanged_items = $entity_unchanged->getTranslation($langcode)->get($field_name)->getValue();
$this->synchronizeItems($values, $unchanged_items, $sync_langcode, array_keys($translations), $columns);
foreach ($translations as $langcode => $language) {
$entity->getTranslation($langcode)->get($field_name)->setValue($values[$langcode]);
}
}
}
}
}
}
/**
* Returns the original unchanged entity to be used to detect changes.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity being changed.
*
* @return \Drupal\Core\Entity\ContentEntityInterface
* The unchanged entity.
*/
protected function getOriginalEntity(ContentEntityInterface $entity) {
if (!isset($entity->original)) {
/** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
$storage = $this->entityTypeManager->getStorage($entity->getEntityTypeId());
$original = $entity->isDefaultRevision() ? $storage->loadUnchanged($entity->id()) : $storage->loadRevision($entity->getLoadedRevisionId());
}
else {
$original = $entity->original;
}
return $original;
}
/**
* {@inheritdoc}
*/
public function synchronizeItems(array &$values, array $unchanged_items, $sync_langcode, array $translations, array $properties) {
$source_items = $values[$sync_langcode];
// Make sure we can detect any change in the source items.
$change_map = [];
// By picking the maximum size between updated and unchanged items, we make
// sure to process also removed items.
$total = max([count($source_items), count($unchanged_items)]);
// As a first step we build a map of the deltas corresponding to the column
// values to be synchronized. Recording both the old values and the new
// values will allow us to detect any change in the order of the new items
// for each column.
for ($delta = 0; $delta < $total; $delta++) {
foreach (['old' => $unchanged_items, 'new' => $source_items] as $key => $items) {
if ($item_id = $this->itemHash($items, $delta, $properties)) {
$change_map[$item_id][$key][] = $delta;
}
}
}
// Backup field values and the change map.
$original_field_values = $values;
$original_change_map = $change_map;
// Reset field values so that no spurious one is stored. Source values must
// be preserved in any case.
$values = [$sync_langcode => $source_items];
// Update field translations.
foreach ($translations as $langcode) {
// We need to synchronize only values different from the source ones.
if ($langcode != $sync_langcode) {
// Reinitialize the change map as it is emptied while processing each
// language.
$change_map = $original_change_map;
// By using the maximum cardinality we ensure to process removed items.
for ($delta = 0; $delta < $total; $delta++) {
// By inspecting the map we built before we can tell whether a value
// has been created or removed. A changed value will be interpreted as
// a new value, in fact it did not exist before.
$created = TRUE;
$removed = TRUE;
$old_delta = NULL;
$new_delta = NULL;
if ($item_id = $this->itemHash($source_items, $delta, $properties)) {
if (!empty($change_map[$item_id]['old'])) {
$old_delta = array_shift($change_map[$item_id]['old']);
}
if (!empty($change_map[$item_id]['new'])) {
$new_delta = array_shift($change_map[$item_id]['new']);
}
$created = $created && !isset($old_delta);
$removed = $removed && !isset($new_delta);
}
// If an item has been removed we do not store its translations.
if ($removed) {
continue;
}
// If a synchronized column has changed or has been created from
// scratch we need to replace the values for this language as a
// combination of the values that need to be synced from the source
// items and the other columns from the existing values. This only
// works if the delta exists in the language.
elseif ($created && !empty($original_field_values[$langcode][$delta])) {
$values[$langcode][$delta] = $this->createMergedItem($source_items[$delta], $original_field_values[$langcode][$delta], $properties);
}
// If the delta doesn't exist, copy from the source language.
elseif ($created) {
$values[$langcode][$delta] = $source_items[$delta];
}
// Otherwise the current item might have been reordered.
elseif (isset($old_delta) && isset($new_delta)) {
// If for any reason the old value is not defined for the current
// language we fall back to the new source value, this way we ensure
// the new values are at least propagated to all the translations.
// If the value has only been reordered we just move the old one in
// the new position.
$item = $original_field_values[$langcode][$old_delta] ?? $source_items[$new_delta];
// When saving a default revision starting from a pending revision,
// we may have desynchronized field values, so we make sure that
// untranslatable properties are synchronized, even if in any other
// situation this would not be necessary.
$values[$langcode][$new_delta] = $this->createMergedItem($source_items[$new_delta], $item, $properties);
}
}
}
}
}
/**
* Creates a merged item.
*
* @param array $source_item
* An item containing the untranslatable properties to be synchronized.
* @param array $target_item
* An item containing the translatable properties to be kept.
* @param string[] $properties
* An array of properties to be synchronized.
*
* @return array
* A merged item array.
*/
protected function createMergedItem(array $source_item, array $target_item, array $properties) {
$property_keys = array_flip($properties);
$item_properties_to_sync = array_intersect_key($source_item, $property_keys);
$item_properties_to_keep = array_diff_key($target_item, $property_keys);
return $item_properties_to_sync + $item_properties_to_keep;
}
/**
* Computes a hash code for the specified item.
*
* @param array $items
* An array of field items.
* @param int $delta
* The delta identifying the item to be processed.
* @param array $properties
* An array of column names to be synchronized.
*
* @return string
* A hash code that can be used to identify the item.
*/
protected function itemHash(array $items, $delta, array $properties) {
$values = [];
if (isset($items[$delta])) {
foreach ($properties as $property) {
if (!empty($items[$delta][$property])) {
$value = $items[$delta][$property];
// String and integer values are by far the most common item values,
// thus we special-case them to improve performance.
$values[] = is_string($value) || is_int($value) ? $value : hash('sha256', serialize($value));
}
else {
// Explicitly track also empty values.
$values[] = '';
}
}
}
return implode('.', $values);
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace Drupal\content_translation;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
/**
* Provides field translation synchronization capabilities.
*/
interface FieldTranslationSynchronizerInterface {
/**
* Performs field column synchronization on the given entity.
*
* Field column synchronization takes care of propagating any change in the
* field items order and in the column values themselves to all the available
* translations. This functionality is provided by defining a
* 'translation_sync' key for the 'content_translation' module's portion of
* the field definition's 'third_party_settings', holding an array of
* column names to be synchronized. The synchronized column values are shared
* across translations, while the rest varies per-language. This is useful for
* instance to translate the "alt" and "title" textual elements of an image
* field, while keeping the same image on every translation.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity whose values should be synchronized.
* @param string $sync_langcode
* The language of the translation whose values should be used as source for
* synchronization.
* @param string $original_langcode
* (optional) If a new translation is being created, this should be the
* language code of the original values. Defaults to NULL.
*/
public function synchronizeFields(ContentEntityInterface $entity, $sync_langcode, $original_langcode = NULL);
/**
* Synchronize the items of a single field.
*
* All the column values of the "active" language are compared to the
* unchanged values to detect any addition, removal or change in the items
* order. Subsequently the detected changes are performed on the field items
* in other available languages.
*
* @param array $field_values
* The field values to be synchronized.
* @param array $unchanged_items
* The unchanged items to be used to detect changes.
* @param string $sync_langcode
* The language code of the items to use as source values.
* @param array $translations
* An array of all the available language codes for the given field.
* @param array $properties
* An array of property names to be synchronized.
*/
public function synchronizeItems(array &$field_values, array $unchanged_items, $sync_langcode, array $translations, array $properties);
/**
* Returns the synchronized properties for the specified field definition.
*
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* A field definition.
*
* @return string[]
* An array of synchronized field property names.
*/
public function getFieldSynchronizedProperties(FieldDefinitionInterface $field_definition);
}

View File

@@ -0,0 +1,33 @@
<?php
namespace Drupal\content_translation\Form;
use Drupal\Core\Entity\ContentEntityDeleteForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
/**
* Delete translation form for content_translation module.
*
* @internal
*/
class ContentTranslationDeleteForm extends ContentEntityDeleteForm {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'content_translation_delete_confirm';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ?LanguageInterface $language = NULL) {
if ($language) {
$form_state->set('langcode', $language->getId());
}
return parent::buildForm($form, $form_state);
}
}

View File

@@ -0,0 +1,59 @@
<?php
namespace Drupal\content_translation\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\content_translation\ContentTranslationManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides dynamic contextual links for content translation.
*
* @see \Drupal\content_translation\Plugin\Menu\ContextualLink\ContentTranslationContextualLinks
*/
class ContentTranslationContextualLinks extends DeriverBase implements ContainerDeriverInterface {
use StringTranslationTrait;
/**
* The content translation manager.
*
* @var \Drupal\content_translation\ContentTranslationManagerInterface
*/
protected $contentTranslationManager;
/**
* Constructs a new ContentTranslationContextualLinks.
*
* @param \Drupal\content_translation\ContentTranslationManagerInterface $content_translation_manager
* The content translation manager.
*/
public function __construct(ContentTranslationManagerInterface $content_translation_manager) {
$this->contentTranslationManager = $content_translation_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static(
$container->get('content_translation.manager')
);
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
// Create contextual links for translatable entity types.
foreach ($this->contentTranslationManager->getSupportedEntityTypes() as $entity_type_id => $entity_type) {
$this->derivatives[$entity_type_id]['title'] = $this->t('Translate');
$this->derivatives[$entity_type_id]['route_name'] = "entity.$entity_type_id.content_translation_overview";
$this->derivatives[$entity_type_id]['group'] = $entity_type_id;
}
return parent::getDerivativeDefinitions($base_plugin_definition);
}
}

View File

@@ -0,0 +1,79 @@
<?php
namespace Drupal\content_translation\Plugin\Derivative;
use Drupal\content_translation\ContentTranslationManagerInterface;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
/**
* Provides dynamic local tasks for content translation.
*/
class ContentTranslationLocalTasks extends DeriverBase implements ContainerDeriverInterface {
use StringTranslationTrait;
/**
* The base plugin ID.
*
* @var string
*/
protected $basePluginId;
/**
* The content translation manager.
*
* @var \Drupal\content_translation\ContentTranslationManagerInterface
*/
protected $contentTranslationManager;
/**
* Constructs a new ContentTranslationLocalTasks.
*
* @param string $base_plugin_id
* The base plugin ID.
* @param \Drupal\content_translation\ContentTranslationManagerInterface $content_translation_manager
* The content translation manager.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The translation manager.
*/
public function __construct($base_plugin_id, ContentTranslationManagerInterface $content_translation_manager, TranslationInterface $string_translation) {
$this->basePluginId = $base_plugin_id;
$this->contentTranslationManager = $content_translation_manager;
$this->stringTranslation = $string_translation;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static(
$base_plugin_id,
$container->get('content_translation.manager'),
$container->get('string_translation')
);
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
// Create tabs for all possible entity types.
foreach ($this->contentTranslationManager->getSupportedEntityTypes() as $entity_type_id => $entity_type) {
// Find the route name for the translation overview.
$translation_route_name = "entity.$entity_type_id.content_translation_overview";
$base_route_name = "entity.$entity_type_id.canonical";
$this->derivatives[$translation_route_name] = [
'entity_type' => $entity_type_id,
'title' => $this->t('Translate'),
'route_name' => $translation_route_name,
'base_route' => $base_route_name,
] + $base_plugin_definition;
}
return parent::getDerivativeDefinitions($base_plugin_definition);
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Drupal\content_translation\Plugin\Validation\Constraint;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Validation\Attribute\Constraint;
use Symfony\Component\Validator\Constraint as SymfonyConstraint;
/**
* Validation constraint for the entity changed timestamp.
*
* @internal
*/
#[Constraint(
id: 'ContentTranslationSynchronizedFields',
label: new TranslatableMarkup('Content translation synchronized fields', [], ['context' => 'Validation']),
type: ['entity']
)]
class ContentTranslationSynchronizedFieldsConstraint extends SymfonyConstraint {
/**
* Message shown for non-translatable field changes in non-default revision.
*
* In this case "elements" refers to "field properties". It is what we are
* using in the UI elsewhere.
*/
public $defaultRevisionMessage = 'Non-translatable field elements can only be changed when updating the current revision.';
/**
* Message shown for non-translatable field changes in different language.
*
* In this case "elements" refers to "field properties". It is what we are
* using in the UI elsewhere.
*/
public $defaultTranslationMessage = 'Non-translatable field elements can only be changed when updating the original language.';
}

View File

@@ -0,0 +1,233 @@
<?php
namespace Drupal\content_translation\Plugin\Validation\Constraint;
use Drupal\content_translation\ContentTranslationManagerInterface;
use Drupal\content_translation\FieldTranslationSynchronizerInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Checks that synchronized fields are handled correctly in pending revisions.
*
* As for untranslatable fields, two modes are supported:
* - When changes to untranslatable fields are configured to affect all revision
* translations, synchronized field properties can be changed only in default
* revisions.
* - When changes to untranslatable fields affect are configured to affect only
* the revision's default translation, synchronized field properties can be
* changed only when editing the default translation. This may lead to
* temporarily desynchronized values, when saving a pending revision for the
* default translation that changes a synchronized property. These are
* actually synchronized when saving changes to the default translation as a
* new default revision.
*
* @see \Drupal\content_translation\Plugin\Validation\Constraint\ContentTranslationSynchronizedFieldsConstraint
* @see \Drupal\Core\Entity\Plugin\Validation\Constraint\EntityUntranslatableFieldsConstraintValidator
*
* @internal
*/
class ContentTranslationSynchronizedFieldsConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The content translation manager.
*
* @var \Drupal\content_translation\ContentTranslationManagerInterface
*/
protected $contentTranslationManager;
/**
* The field translation synchronizer.
*
* @var \Drupal\content_translation\FieldTranslationSynchronizerInterface
*/
protected $synchronizer;
/**
* ContentTranslationSynchronizedFieldsConstraintValidator constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\content_translation\ContentTranslationManagerInterface $content_translation_manager
* The content translation manager.
* @param \Drupal\content_translation\FieldTranslationSynchronizerInterface $synchronizer
* The field translation synchronizer.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, ContentTranslationManagerInterface $content_translation_manager, FieldTranslationSynchronizerInterface $synchronizer) {
$this->entityTypeManager = $entity_type_manager;
$this->contentTranslationManager = $content_translation_manager;
$this->synchronizer = $synchronizer;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('content_translation.manager'),
$container->get('content_translation.synchronizer')
);
}
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint) {
/** @var \Drupal\content_translation\Plugin\Validation\Constraint\ContentTranslationSynchronizedFieldsConstraint $constraint */
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $value;
if ($entity->isNew() || !$entity->getEntityType()->isRevisionable()) {
return;
}
// When changes to untranslatable fields are configured to affect all
// revision translations, we always allow changes in default revisions.
if ($entity->isDefaultRevision() && !$entity->isDefaultTranslationAffectedOnly()) {
return;
}
$entity_type_id = $entity->getEntityTypeId();
if (!$this->contentTranslationManager->isEnabled($entity_type_id, $entity->bundle())) {
return;
}
$synchronized_properties = $this->getSynchronizedPropertiesByField($entity->getFieldDefinitions());
if (!$synchronized_properties) {
return;
}
/** @var \Drupal\Core\Entity\ContentEntityInterface $original */
$original = $this->getOriginalEntity($entity);
$original_translation = $this->getOriginalTranslation($entity, $original);
if ($this->hasSynchronizedPropertyChanges($entity, $original_translation, $synchronized_properties)) {
if ($entity->isDefaultTranslationAffectedOnly()) {
foreach ($entity->getTranslationLanguages(FALSE) as $langcode => $language) {
if ($entity->getTranslation($langcode)->hasTranslationChanges()) {
$this->context->addViolation($constraint->defaultTranslationMessage);
break;
}
}
}
else {
$this->context->addViolation($constraint->defaultRevisionMessage);
}
}
}
/**
* Checks whether any synchronized property has changes.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity being validated.
* @param \Drupal\Core\Entity\ContentEntityInterface $original
* The original unchanged entity.
* @param string[][] $synchronized_properties
* An associative array of arrays of synchronized field properties keyed by
* field name.
*
* @return bool
* TRUE if changes in synchronized properties were detected, FALSE
* otherwise.
*/
protected function hasSynchronizedPropertyChanges(ContentEntityInterface $entity, ContentEntityInterface $original, array $synchronized_properties) {
foreach ($synchronized_properties as $field_name => $properties) {
foreach ($properties as $property) {
$items = $entity->get($field_name)->getValue();
$original_items = $original->get($field_name)->getValue();
if (count($items) !== count($original_items)) {
return TRUE;
}
foreach ($items as $delta => $item) {
// @todo This loose comparison is not fully reliable. Revisit this
// after https://www.drupal.org/project/drupal/issues/2941092.
if ($items[$delta][$property] != $original_items[$delta][$property]) {
return TRUE;
}
}
}
}
return FALSE;
}
/**
* Returns the original unchanged entity to be used to detect changes.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity being changed.
*
* @return \Drupal\Core\Entity\ContentEntityInterface
* The unchanged entity.
*/
protected function getOriginalEntity(ContentEntityInterface $entity) {
if (!isset($entity->original)) {
/** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
$storage = $this->entityTypeManager->getStorage($entity->getEntityTypeId());
$original = $entity->isDefaultRevision() ? $storage->loadUnchanged($entity->id()) : $storage->loadRevision($entity->getLoadedRevisionId());
}
else {
$original = $entity->original;
}
return $original;
}
/**
* Returns the original translation.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity being validated.
* @param \Drupal\Core\Entity\ContentEntityInterface $original
* The original entity.
*
* @return \Drupal\Core\Entity\ContentEntityInterface
* The original entity translation object.
*/
protected function getOriginalTranslation(ContentEntityInterface $entity, ContentEntityInterface $original) {
// If the language of the default translation is changing, the original
// translation will be the same as the original entity, but they won't
// necessarily have the same langcode.
if ($entity->isDefaultTranslation() && $original->language()->getId() !== $entity->language()->getId()) {
return $original;
}
$langcode = $entity->language()->getId();
if ($original->hasTranslation($langcode)) {
$original_langcode = $langcode;
}
else {
$metadata = $this->contentTranslationManager->getTranslationMetadata($entity);
$original_langcode = $metadata->getSource();
}
return $original->getTranslation($original_langcode);
}
/**
* Returns the synchronized properties for every specified field.
*
* @param \Drupal\Core\Field\FieldDefinitionInterface[] $field_definitions
* An array of field definitions.
*
* @return string[][]
* An associative array of arrays of field property names keyed by field
* name.
*/
public function getSynchronizedPropertiesByField(array $field_definitions) {
$synchronizer = $this->synchronizer;
$synchronized_properties = array_filter(array_map(
function (FieldDefinitionInterface $field_definition) use ($synchronizer) {
return $synchronizer->getFieldSynchronizedProperties($field_definition);
},
$field_definitions
));
return $synchronized_properties;
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace Drupal\content_translation\Plugin\migrate\source;
use Drupal\migrate\Plugin\MigrateIdMapInterface;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Row;
// cspell:ignore objectid
/**
* Gets an i18n translation from the source database.
*/
trait I18nQueryTrait {
/**
* The i18n string table name.
*
* @var string
*/
protected $i18nStringTable;
/**
* Gets the translation for the property not already in the row.
*
* For some i18n migrations there are two translation values, such as a
* translated title and a translated description, that need to be retrieved.
* Since these values are stored in separate rows of the i18nStringTable
* table we get them individually, one in the source plugin query() and the
* other in prepareRow(). The names of the properties varies, for example,
* in BoxTranslation they are 'body' and 'title' whereas in
* MenuLinkTranslation they are 'title' and 'description'. This will save both
* translations to the row.
*
* @param \Drupal\migrate\Row $row
* The current migration row which must include both a 'language' property
* and an 'objectid' property. The 'objectid' is the value for the
* 'objectid' field in the i18n_string table.
* @param string $property_not_in_row
* The name of the property to get the translation for.
* @param string $object_id_name
* The value of the objectid in the i18n table.
* @param \Drupal\migrate\Plugin\MigrateIdMapInterface $id_map
* The ID map.
*
* @return bool
* FALSE if the property has already been migrated.
*
* @throws \Drupal\migrate\MigrateException
*/
protected function getPropertyNotInRowTranslation(Row $row, $property_not_in_row, $object_id_name, MigrateIdMapInterface $id_map) {
$language = $row->getSourceProperty('language');
if (!$language) {
throw new MigrateException('No language found.');
}
$object_id = $row->getSourceProperty($object_id_name);
if (!$object_id) {
throw new MigrateException('No objectid found.');
}
// If this row has been migrated it is a duplicate so skip it.
if ($id_map->lookupDestinationIds([$object_id_name => $object_id, 'language' => $language])) {
return FALSE;
}
// Save the translation for the property already in the row.
$property_in_row = $row->getSourceProperty('property');
$row->setSourceProperty($property_in_row . '_translated', $row->getSourceProperty('translation'));
// Get the translation, if one exists, for the property not already in the
// row.
$query = $this->select($this->i18nStringTable, 'i18n')
->fields('i18n', ['lid'])
->condition('i18n.property', $property_not_in_row)
->condition('i18n.objectid', $object_id);
$query->leftJoin('locales_target', 'lt', '[i18n].[lid] = [lt].[lid]');
$query->condition('lt.language', $language);
$query->addField('lt', 'translation');
$results = $query->execute()->fetchAssoc();
if (!$results) {
$row->setSourceProperty($property_not_in_row . '_translated', NULL);
}
else {
$row->setSourceProperty($property_not_in_row . '_translated', $results['translation']);
}
return TRUE;
}
}

View File

@@ -0,0 +1,203 @@
<?php
namespace Drupal\content_translation\Plugin\migrate\source\d7;
use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;
/**
* Drupal 7 Entity Translation settings (variables) from database.
*
* For available configuration keys, refer to the parent classes.
*
* @see \Drupal\migrate\Plugin\migrate\source\SqlBase
* @see \Drupal\migrate\Plugin\migrate\source\SourcePluginBase
*
* @MigrateSource(
* id = "d7_entity_translation_settings",
* source_module = "entity_translation"
* )
*/
class EntityTranslationSettings extends DrupalSqlBase {
/**
* {@inheritdoc}
*/
public function query() {
// Query all meaningful variables for entity translation.
$query = $this->select('variable', 'v')
->fields('v', ['name', 'value']);
$condition = $query->orConditionGroup()
// The 'entity_translation_entity_types' variable tells us which entity
// type uses entity translation.
->condition('name', 'entity_translation_entity_types')
// The 'entity_translation_taxonomy' variable tells us which taxonomy
// vocabulary uses entity_translation.
->condition('name', 'entity_translation_taxonomy')
// The 'entity_translation_settings_%' variables give us the entity
// translation settings for each entity type and each bundle.
->condition('name', 'entity_translation_settings_%', 'LIKE')
// The 'language_content_type_%' variables tells us which node type and
// which comment type uses entity translation.
->condition('name', 'language_content_type_%', 'LIKE');
$query->condition($condition);
return $query;
}
/**
* {@inheritdoc}
*/
protected function initializeIterator() {
$results = array_map('unserialize', $this->prepareQuery()->execute()->fetchAllKeyed());
$rows = [];
// Find out which entity type uses entity translation by looking at the
// 'entity_translation_entity_types' variable.
$entity_types = array_filter($results['entity_translation_entity_types']);
// If no entity type uses entity translation, there's nothing to do.
if (empty($entity_types)) {
return new \ArrayIterator($rows);
}
// Find out which node type uses entity translation by looking at the
// 'language_content_type_%' variables.
$node_types = [];
foreach ($results as $name => $value) {
if (preg_match('/^language_content_type_(.+)$/', $name, $matches) && (int) $value === 4) {
$node_types[] = $matches[1];
}
}
// Find out which vocabulary uses entity translation by looking at the
// 'entity_translation_taxonomy' variable.
$vocabularies = [];
if (isset($results['entity_translation_taxonomy']) && is_array($results['entity_translation_taxonomy'])) {
$vocabularies = array_keys(array_filter($results['entity_translation_taxonomy']));
}
if (in_array('node', $entity_types, TRUE) && !empty($node_types)) {
// For each node type that uses entity translation, check if a
// settings variable exists for that node type, otherwise use default
// values.
foreach ($node_types as $node_type) {
$settings = $results['entity_translation_settings_node__' . $node_type] ?? [];
$rows[] = [
'id' => 'node.' . $node_type,
'target_entity_type_id' => 'node',
'target_bundle' => $node_type,
'default_langcode' => $settings['default_language'] ?? 'und',
// The Drupal 7 'hide_language_selector' configuration has become
// 'language_alterable' in Drupal 8 so we need to negate the value we
// receive from the source. The Drupal 7 'hide_language_selector'
// default value for the node entity type was FALSE so in Drupal 8 it
// should be set to TRUE, unlike the other entity types for which
// it's the opposite.
'language_alterable' => isset($settings['hide_language_selector']) ? (bool) !$settings['hide_language_selector'] : TRUE,
'untranslatable_fields_hide' => isset($settings['shared_fields_original_only']) ? (bool) $settings['shared_fields_original_only'] : FALSE,
];
}
}
if (in_array('comment', $entity_types, TRUE) && !empty($node_types)) {
// A comment type uses entity translation if the associated node type
// uses it. So, for each node type that uses entity translation, check
// if a settings variable exists for that comment type, otherwise use
// default values.
foreach ($node_types as $node_type) {
$settings = $results['entity_translation_settings_comment__comment_node_' . $node_type] ?? [];
// Forum uses a hardcoded comment type name, so make sure we use it
// when we're dealing with forum comment type.
$bundle = $node_type == 'forum' ? 'comment_forum' : 'comment_node_' . $node_type;
$rows[] = [
'id' => 'comment.' . $bundle,
'target_entity_type_id' => 'comment',
'target_bundle' => $bundle,
'default_langcode' => $settings['default_language'] ?? 'xx-et-current',
// The Drupal 7 'hide_language_selector' configuration has become
// 'language_alterable' in Drupal 8 so we need to negate the value we
// receive from the source. The Drupal 7 'hide_language_selector'
// default value for the comment entity type was TRUE so in Drupal 8
// it should be set to FALSE.
'language_alterable' => isset($settings['hide_language_selector']) ? (bool) !$settings['hide_language_selector'] : FALSE,
'untranslatable_fields_hide' => isset($settings['shared_fields_original_only']) ? (bool) $settings['shared_fields_original_only'] : FALSE,
];
}
}
if (in_array('taxonomy_term', $entity_types, TRUE) && !empty($vocabularies)) {
// For each vocabulary that uses entity translation, check if a
// settings variable exists for that vocabulary, otherwise use default
// values.
foreach ($vocabularies as $vocabulary) {
$settings = $results['entity_translation_settings_taxonomy_term__' . $vocabulary] ?? [];
$rows[] = [
'id' => 'taxonomy_term.' . $vocabulary,
'target_entity_type_id' => 'taxonomy_term',
'target_bundle' => $vocabulary,
'default_langcode' => $settings['default_language'] ?? 'xx-et-default',
// The Drupal 7 'hide_language_selector' configuration has become
// 'language_alterable' in Drupal 8 so we need to negate the value we
// receive from the source. The Drupal 7 'hide_language_selector'
// default value for the taxonomy_term entity type was TRUE so in
// Drupal 8 it should be set to FALSE.
'language_alterable' => isset($settings['hide_language_selector']) ? (bool) !$settings['hide_language_selector'] : FALSE,
'untranslatable_fields_hide' => isset($settings['shared_fields_original_only']) ? (bool) $settings['shared_fields_original_only'] : FALSE,
];
}
}
if (in_array('user', $entity_types, TRUE)) {
// User entity type is not bundleable. Check if a settings variable
// exists, otherwise use default values.
$settings = $results['entity_translation_settings_user__user'] ?? [];
$rows[] = [
'id' => 'user.user',
'target_entity_type_id' => 'user',
'target_bundle' => 'user',
'default_langcode' => $settings['default_language'] ?? 'xx-et-default',
// The Drupal 7 'hide_language_selector' configuration has become
// 'language_alterable' in Drupal 8 so we need to negate the value we
// receive from the source. The Drupal 7 'hide_language_selector'
// default value for the user entity type was TRUE so in Drupal 8 it
// should be set to FALSE.
'language_alterable' => isset($settings['hide_language_selector']) ? (bool) !$settings['hide_language_selector'] : FALSE,
'untranslatable_fields_hide' => isset($settings['shared_fields_original_only']) ? (bool) $settings['shared_fields_original_only'] : FALSE,
];
}
return new \ArrayIterator($rows);
}
/**
* {@inheritdoc}
*/
public function fields() {
return [
'id' => $this->t('The configuration ID'),
'target_entity_type_id' => $this->t('The target entity type ID'),
'target_bundle' => $this->t('The target bundle'),
'default_langcode' => $this->t('The default language'),
'language_alterable' => $this->t('Whether to show language selector on create and edit pages'),
'untranslatable_fields_hide' => $this->t('Whether to hide non translatable fields on translation forms'),
];
}
/**
* {@inheritdoc}
*/
public function getIds() {
$ids['id']['type'] = 'string';
return $ids;
}
/**
* {@inheritdoc}
*/
protected function doCount() {
// Since the number of variables we fetch with query() does not match the
// actual number of rows generated by initializeIterator(), we need to
// override count() to return the correct count.
return (int) $this->initializeIterator()->count();
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace Drupal\content_translation\Plugin\views\field;
use Drupal\views\Attribute\ViewsField;
use Drupal\views\Plugin\views\field\EntityLink;
/**
* Provides a translation link for an entity.
*
* @ingroup views_field_handlers
*/
#[ViewsField("content_translation_link")]
class TranslationLink extends EntityLink {
/**
* {@inheritdoc}
*/
protected function getEntityLinkTemplate() {
return 'drupal:content-translation-overview';
}
/**
* {@inheritdoc}
*/
protected function getDefaultLabel() {
return $this->t('Translate');
}
}

View File

@@ -0,0 +1,184 @@
<?php
namespace Drupal\content_translation\Routing;
use Drupal\content_translation\ContentTranslationManager;
use Drupal\content_translation\ContentTranslationManagerInterface;
use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* Subscriber for entity translation routes.
*/
class ContentTranslationRouteSubscriber extends RouteSubscriberBase {
/**
* The content translation manager.
*
* @var \Drupal\content_translation\ContentTranslationManagerInterface
*/
protected $contentTranslationManager;
/**
* Constructs a ContentTranslationRouteSubscriber object.
*
* @param \Drupal\content_translation\ContentTranslationManagerInterface $content_translation_manager
* The content translation manager.
*/
public function __construct(ContentTranslationManagerInterface $content_translation_manager) {
$this->contentTranslationManager = $content_translation_manager;
}
/**
* {@inheritdoc}
*/
protected function alterRoutes(RouteCollection $collection) {
foreach ($this->contentTranslationManager->getSupportedEntityTypes() as $entity_type_id => $entity_type) {
// Inherit admin route status from edit route, if exists.
$is_admin = FALSE;
$route_name = "entity.$entity_type_id.edit_form";
if ($edit_route = $collection->get($route_name)) {
$is_admin = (bool) $edit_route->getOption('_admin_route');
}
$load_latest_revision = ContentTranslationManager::isPendingRevisionSupportEnabled($entity_type_id);
if ($entity_type->hasLinkTemplate('drupal:content-translation-overview')) {
$route = new Route(
$entity_type->getLinkTemplate('drupal:content-translation-overview'),
[
'_controller' => '\Drupal\content_translation\Controller\ContentTranslationController::overview',
'entity_type_id' => $entity_type_id,
],
[
'_entity_access' => $entity_type_id . '.view',
'_access_content_translation_overview' => $entity_type_id,
],
[
'parameters' => [
$entity_type_id => [
'type' => 'entity:' . $entity_type_id,
'load_latest_revision' => $load_latest_revision,
],
],
'_admin_route' => $is_admin,
]
);
$route_name = "entity.$entity_type_id.content_translation_overview";
$collection->add($route_name, $route);
}
if ($entity_type->hasLinkTemplate('drupal:content-translation-add')) {
$route = new Route(
$entity_type->getLinkTemplate('drupal:content-translation-add'),
[
'_controller' => '\Drupal\content_translation\Controller\ContentTranslationController::add',
'source' => NULL,
'target' => NULL,
'_title' => 'Add',
'entity_type_id' => $entity_type_id,
],
[
'_entity_access' => $entity_type_id . '.view',
'_access_content_translation_manage' => 'create',
],
[
'parameters' => [
'source' => [
'type' => 'language',
],
'target' => [
'type' => 'language',
],
$entity_type_id => [
'type' => 'entity:' . $entity_type_id,
'load_latest_revision' => $load_latest_revision,
],
],
'_admin_route' => $is_admin,
]
);
$collection->add("entity.$entity_type_id.content_translation_add", $route);
}
if ($entity_type->hasLinkTemplate('drupal:content-translation-edit')) {
$route = new Route(
$entity_type->getLinkTemplate('drupal:content-translation-edit'),
[
'_controller' => '\Drupal\content_translation\Controller\ContentTranslationController::edit',
'language' => NULL,
'_title' => 'Edit',
'entity_type_id' => $entity_type_id,
],
[
'_access_content_translation_manage' => 'update',
],
[
'parameters' => [
'language' => [
'type' => 'language',
],
$entity_type_id => [
'type' => 'entity:' . $entity_type_id,
'load_latest_revision' => $load_latest_revision,
],
],
'_admin_route' => $is_admin,
]
);
$collection->add("entity.$entity_type_id.content_translation_edit", $route);
}
if ($entity_type->hasLinkTemplate('drupal:content-translation-delete')) {
$route = new Route(
$entity_type->getLinkTemplate('drupal:content-translation-delete'),
[
'_entity_form' => $entity_type_id . '.content_translation_deletion',
'language' => NULL,
'_title' => 'Delete',
'entity_type_id' => $entity_type_id,
],
[
'_access_content_translation_manage' => 'delete',
],
[
'parameters' => [
'language' => [
'type' => 'language',
],
$entity_type_id => [
'type' => 'entity:' . $entity_type_id,
'load_latest_revision' => $load_latest_revision,
],
],
'_admin_route' => $is_admin,
]
);
$collection->add("entity.$entity_type_id.content_translation_delete", $route);
}
// Add our custom translation deletion access checker.
if ($load_latest_revision) {
$entity_delete_route = $collection->get("entity.$entity_type_id.delete_form");
if ($entity_delete_route) {
$entity_delete_route->addRequirements(['_access_content_translation_delete' => "$entity_type_id.delete"]);
}
}
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events = parent::getSubscribedEvents();
// Should run after AdminRouteSubscriber so the routes can inherit admin
// status of the edit routes on entities. Therefore priority -210.
$events[RoutingEvents::ALTER] = ['onAlterRoutes', -210];
return $events;
}
}