3 namespace Drupal\content_translation;
5 use Drupal\Core\Access\AccessResult;
6 use Drupal\Core\DependencyInjection\DependencySerializationTrait;
7 use Drupal\Core\Entity\EntityChangedInterface;
8 use Drupal\Core\Entity\EntityHandlerInterface;
9 use Drupal\Core\Entity\EntityInterface;
10 use Drupal\Core\Entity\EntityManagerInterface;
11 use Drupal\Core\Entity\EntityTypeInterface;
12 use Drupal\Core\Field\BaseFieldDefinition;
13 use Drupal\Core\Form\FormStateInterface;
14 use Drupal\Core\Language\LanguageInterface;
15 use Drupal\Core\Language\LanguageManagerInterface;
16 use Drupal\Core\Render\Element;
17 use Drupal\Core\Session\AccountInterface;
18 use Drupal\user\Entity\User;
19 use Drupal\user\EntityOwnerInterface;
20 use Symfony\Component\DependencyInjection\ContainerInterface;
23 * Base class for content translation handlers.
27 class ContentTranslationHandler implements ContentTranslationHandlerInterface, EntityHandlerInterface {
28 use DependencySerializationTrait;
31 * The type of the entity being translated.
35 protected $entityTypeId;
38 * Information about the entity type.
40 * @var \Drupal\Core\Entity\EntityTypeInterface
42 protected $entityType;
45 * The language manager.
47 * @var \Drupal\Core\Language\LanguageManagerInterface
49 protected $languageManager;
52 * The content translation manager.
54 * @var \Drupal\content_translation\ContentTranslationManagerInterface
61 * @var \Drupal\Core\Session\AccountInterface
63 protected $currentUser;
66 * The array of installed field storage definitions for the entity type, keyed
69 * @var \Drupal\Core\Field\FieldStorageDefinitionInterface[]
71 protected $fieldStorageDefinitions;
74 * Initializes an instance of the content translation controller.
76 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
77 * The info array of the given entity type.
78 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
79 * The language manager.
80 * @param \Drupal\content_translation\ContentTranslationManagerInterface $manager
81 * The content translation manager service.
82 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
84 * @param \Drupal\Core\Session\AccountInterface $current_user
87 public function __construct(EntityTypeInterface $entity_type, LanguageManagerInterface $language_manager, ContentTranslationManagerInterface $manager, EntityManagerInterface $entity_manager, AccountInterface $current_user) {
88 $this->entityTypeId = $entity_type->id();
89 $this->entityType = $entity_type;
90 $this->languageManager = $language_manager;
91 $this->manager = $manager;
92 $this->currentUser = $current_user;
93 $this->fieldStorageDefinitions = $entity_manager->getLastInstalledFieldStorageDefinitions($this->entityTypeId);
99 public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
102 $container->get('language_manager'),
103 $container->get('content_translation.manager'),
104 $container->get('entity.manager'),
105 $container->get('current_user')
112 public function getFieldDefinitions() {
115 $definitions['content_translation_source'] = BaseFieldDefinition::create('language')
116 ->setLabel(t('Translation source'))
117 ->setDescription(t('The source language from which this translation was created.'))
118 ->setDefaultValue(LanguageInterface::LANGCODE_NOT_SPECIFIED)
119 ->setInitialValue(LanguageInterface::LANGCODE_NOT_SPECIFIED)
120 ->setRevisionable(TRUE)
121 ->setTranslatable(TRUE);
123 $definitions['content_translation_outdated'] = BaseFieldDefinition::create('boolean')
124 ->setLabel(t('Translation outdated'))
125 ->setDescription(t('A boolean indicating whether this translation needs to be updated.'))
126 ->setDefaultValue(FALSE)
127 ->setInitialValue(FALSE)
128 ->setRevisionable(TRUE)
129 ->setTranslatable(TRUE);
131 if (!$this->hasAuthor()) {
132 $definitions['content_translation_uid'] = BaseFieldDefinition::create('entity_reference')
133 ->setLabel(t('Translation author'))
134 ->setDescription(t('The author of this translation.'))
135 ->setSetting('target_type', 'user')
136 ->setSetting('handler', 'default')
137 ->setRevisionable(TRUE)
138 ->setDefaultValueCallback(get_class($this) . '::getDefaultOwnerId')
139 ->setTranslatable(TRUE);
142 if (!$this->hasPublishedStatus()) {
143 $definitions['content_translation_status'] = BaseFieldDefinition::create('boolean')
144 ->setLabel(t('Translation status'))
145 ->setDescription(t('A boolean indicating whether the translation is visible to non-translators.'))
146 ->setDefaultValue(TRUE)
147 ->setInitialValue(TRUE)
148 ->setRevisionable(TRUE)
149 ->setTranslatable(TRUE);
152 if (!$this->hasCreatedTime()) {
153 $definitions['content_translation_created'] = BaseFieldDefinition::create('created')
154 ->setLabel(t('Translation created time'))
155 ->setDescription(t('The Unix timestamp when the translation was created.'))
156 ->setRevisionable(TRUE)
157 ->setTranslatable(TRUE);
160 if (!$this->hasChangedTime()) {
161 $definitions['content_translation_changed'] = BaseFieldDefinition::create('changed')
162 ->setLabel(t('Translation changed time'))
163 ->setDescription(t('The Unix timestamp when the translation was most recently saved.'))
164 ->setRevisionable(TRUE)
165 ->setTranslatable(TRUE);
172 * Checks whether the entity type supports author natively.
175 * TRUE if metadata is natively supported, FALSE otherwise.
177 protected function hasAuthor() {
178 // Check for field named uid, but only in case the entity implements the
179 // EntityOwnerInterface. This helps to exclude cases, where the uid is
180 // defined as field name, but is not meant to be an owner field; for
181 // instance, the User entity.
182 return $this->entityType->entityClassImplements(EntityOwnerInterface::class) && $this->checkFieldStorageDefinitionTranslatability('uid');
186 * Checks whether the entity type supports published status natively.
189 * TRUE if metadata is natively supported, FALSE otherwise.
191 protected function hasPublishedStatus() {
192 return $this->checkFieldStorageDefinitionTranslatability('status');
196 * Checks whether the entity type supports modification time natively.
199 * TRUE if metadata is natively supported, FALSE otherwise.
201 protected function hasChangedTime() {
202 return $this->entityType->entityClassImplements(EntityChangedInterface::class) && $this->checkFieldStorageDefinitionTranslatability('changed');
206 * Checks whether the entity type supports creation time natively.
209 * TRUE if metadata is natively supported, FALSE otherwise.
211 protected function hasCreatedTime() {
212 return $this->checkFieldStorageDefinitionTranslatability('created');
216 * Checks the field storage definition for translatability support.
218 * Checks whether the given field is defined in the field storage definitions
219 * and if its definition specifies it as translatable.
221 * @param string $field_name
222 * The name of the field.
225 * TRUE if translatable field storage definition exists, FALSE otherwise.
227 protected function checkFieldStorageDefinitionTranslatability($field_name) {
228 return array_key_exists($field_name, $this->fieldStorageDefinitions) && $this->fieldStorageDefinitions[$field_name]->isTranslatable();
234 public function retranslate(EntityInterface $entity, $langcode = NULL) {
235 $updated_langcode = !empty($langcode) ? $langcode : $entity->language()->getId();
236 foreach ($entity->getTranslationLanguages() as $langcode => $language) {
237 $this->manager->getTranslationMetadata($entity->getTranslation($langcode))
238 ->setOutdated($langcode != $updated_langcode);
245 public function getTranslationAccess(EntityInterface $entity, $op) {
246 // @todo Move this logic into a translation access control handler checking also
247 // the translation language and the given account.
248 $entity_type = $entity->getEntityType();
249 $translate_permission = TRUE;
250 // If no permission granularity is defined this entity type does not need an
251 // explicit translate permission.
252 if (!$this->currentUser->hasPermission('translate any entity') && $permission_granularity = $entity_type->getPermissionGranularity()) {
253 $translate_permission = $this->currentUser->hasPermission($permission_granularity == 'bundle' ? "translate {$entity->bundle()} {$entity->getEntityTypeId()}" : "translate {$entity->getEntityTypeId()}");
255 return AccessResult::allowedIf($translate_permission && $this->currentUser->hasPermission("$op content translations"))->cachePerPermissions();
261 public function getSourceLangcode(FormStateInterface $form_state) {
262 if ($source = $form_state->get(['content_translation', 'source'])) {
263 return $source->getId();
271 public function entityFormAlter(array &$form, FormStateInterface $form_state, EntityInterface $entity) {
272 $form_object = $form_state->getFormObject();
273 $form_langcode = $form_object->getFormLangcode($form_state);
274 $entity_langcode = $entity->getUntranslated()->language()->getId();
275 $source_langcode = $this->getSourceLangcode($form_state);
277 $new_translation = !empty($source_langcode);
278 $translations = $entity->getTranslationLanguages();
279 if ($new_translation) {
280 // Make sure a new translation does not appear as existing yet.
281 unset($translations[$form_langcode]);
283 $is_translation = !$form_object->isDefaultFormLangcode($form_state);
284 $has_translations = count($translations) > 1;
286 // Adjust page title to specify the current language being edited, if we
287 // have at least one translation.
288 $languages = $this->languageManager->getLanguages();
289 if (isset($languages[$form_langcode]) && ($has_translations || $new_translation)) {
290 $title = $this->entityFormTitle($entity);
291 // When editing the original values display just the entity label.
292 if ($is_translation) {
293 $t_args = ['%language' => $languages[$form_langcode]->getName(), '%title' => $entity->label(), '@title' => $title];
294 $title = empty($source_langcode) ? t('@title [%language translation]', $t_args) : t('Create %language translation of %title', $t_args);
296 $form['#title'] = $title;
299 // Display source language selector only if we are creating a new
300 // translation and there are at least two translations available.
301 if ($has_translations && $new_translation) {
302 $form['source_langcode'] = [
303 '#type' => 'details',
304 '#title' => t('Source language: @language', ['@language' => $languages[$source_langcode]->getName()]),
307 '#multilingual' => TRUE,
309 '#title' => t('Select source language'),
310 '#title_display' => 'invisible',
312 '#default_value' => $source_langcode,
317 '#value' => t('Change'),
318 '#submit' => [[$this, 'entityFormSourceChange']],
321 foreach ($this->languageManager->getLanguages() as $language) {
322 if (isset($translations[$language->getId()])) {
323 $form['source_langcode']['source']['#options'][$language->getId()] = $language->getName();
328 // Locate the language widget.
329 $langcode_key = $this->entityType->getKey('langcode');
330 if (isset($form[$langcode_key])) {
331 $language_widget = &$form[$langcode_key];
334 // If we are editing the source entity, limit the list of languages so that
335 // it is not possible to switch to a language for which a translation
336 // already exists. Note that this will only work if the widget is structured
337 // like \Drupal\Core\Field\Plugin\Field\FieldWidget\LanguageSelectWidget.
338 if (isset($language_widget['widget'][0]['value']) && !$is_translation && $has_translations) {
339 $language_select = &$language_widget['widget'][0]['value'];
340 if ($language_select['#type'] == 'language_select') {
342 foreach ($this->languageManager->getLanguages() as $language) {
343 // Show the current language, and the languages for which no
344 // translation already exists.
345 if (empty($translations[$language->getId()]) || $language->getId() == $entity_langcode) {
346 $options[$language->getId()] = $language->getName();
349 $language_select['#options'] = $options;
352 if ($is_translation) {
353 if (isset($language_widget)) {
354 $language_widget['widget']['#access'] = FALSE;
357 // Replace the delete button with the delete translation one.
358 if (!$new_translation) {
360 foreach (['delete', 'submit'] as $key) {
361 if (isset($form['actions'][$key]['weight'])) {
362 $weight = $form['actions'][$key]['weight'];
366 $access = $this->getTranslationAccess($entity, 'delete')->isAllowed() || ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form'));
367 $form['actions']['delete_translation'] = [
369 '#value' => t('Delete translation'),
370 '#weight' => $weight,
371 '#submit' => [[$this, 'entityFormDeleteTranslation']],
372 '#access' => $access,
376 // Always remove the delete button on translation forms.
377 unset($form['actions']['delete']);
380 // We need to display the translation tab only when there is at least one
381 // translation available or a new one is about to be created.
382 if ($new_translation || $has_translations) {
383 $form['content_translation'] = [
384 '#type' => 'details',
385 '#title' => t('Translation'),
388 '#access' => $this->getTranslationAccess($entity, $source_langcode ? 'create' : 'update')->isAllowed(),
389 '#multilingual' => TRUE,
392 if (isset($form['advanced'])) {
393 $form['content_translation'] += [
394 '#group' => 'advanced',
397 'class' => ['entity-translation-options'],
402 // A new translation is enabled by default.
403 $metadata = $this->manager->getTranslationMetadata($entity);
404 $status = $new_translation || $metadata->isPublished();
405 // If there is only one published translation we cannot unpublish it,
406 // since there would be nothing left to display.
410 foreach ($entity->getTranslationLanguages() as $langcode => $language) {
411 $published += $this->manager->getTranslationMetadata($entity->getTranslation($langcode))
414 $enabled = $published > 1;
416 $description = $enabled ?
417 t('An unpublished translation will not be visible without translation permissions.') :
418 t('Only this translation is published. You must publish at least one more translation to unpublish this one.');
420 $form['content_translation']['status'] = [
421 '#type' => 'checkbox',
422 '#title' => t('This translation is published'),
423 '#default_value' => $status,
424 '#description' => $description,
425 '#disabled' => !$enabled,
428 $translate = !$new_translation && $metadata->isOutdated();
430 $form['content_translation']['retranslate'] = [
431 '#type' => 'checkbox',
432 '#title' => t('Flag other translations as outdated'),
433 '#default_value' => FALSE,
434 '#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.'),
438 $form['content_translation']['outdated'] = [
439 '#type' => 'checkbox',
440 '#title' => t('This translation needs to be updated'),
441 '#default_value' => $translate,
442 '#description' => t('When this option is checked, this translation needs to be updated. Uncheck when the translation is up to date again.'),
444 $form['content_translation']['#open'] = TRUE;
447 // Default to the anonymous user.
449 if ($new_translation) {
450 $uid = $this->currentUser->id();
452 elseif (($account = $metadata->getAuthor()) && $account->id()) {
453 $uid = $account->id();
455 $form['content_translation']['uid'] = [
456 '#type' => 'entity_autocomplete',
457 '#title' => t('Authored by'),
458 '#target_type' => 'user',
459 '#default_value' => User::load($uid),
460 // Validation is done by static::entityFormValidate().
461 '#validate_reference' => FALSE,
463 '#description' => t('Leave blank for %anonymous.', ['%anonymous' => \Drupal::config('user.settings')->get('anonymous')]),
466 $date = $new_translation ? REQUEST_TIME : $metadata->getCreatedTime();
467 $form['content_translation']['created'] = [
468 '#type' => 'textfield',
469 '#title' => t('Authored on'),
471 '#description' => t('Format: %time. The date format is YYYY-MM-DD and %timezone is the time zone offset from UTC. Leave blank to use the time of form submission.', ['%time' => format_date(REQUEST_TIME, 'custom', 'Y-m-d H:i:s O'), '%timezone' => format_date(REQUEST_TIME, 'custom', 'O')]),
472 '#default_value' => $new_translation || !$date ? '' : format_date($date, 'custom', 'Y-m-d H:i:s O'),
475 if (isset($language_widget)) {
476 $language_widget['#multilingual'] = TRUE;
479 $form['#process'][] = [$this, 'entityFormSharedElements'];
482 // Process the submitted values before they are stored.
483 $form['#entity_builders'][] = [$this, 'entityFormEntityBuild'];
485 // Handle entity validation.
486 $form['#validate'][] = [$this, 'entityFormValidate'];
488 // Handle entity deletion.
489 if (isset($form['actions']['delete'])) {
490 $form['actions']['delete']['#submit'][] = [$this, 'entityFormDelete'];
493 // Handle entity form submission before the entity has been saved.
494 foreach (Element::children($form['actions']) as $action) {
495 if (isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] == 'submit') {
496 array_unshift($form['actions'][$action]['#submit'], [$this, 'entityFormSubmit']);
502 * Process callback: determines which elements get clue in the form.
504 * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
506 public function entityFormSharedElements($element, FormStateInterface $form_state, $form) {
507 static $ignored_types;
509 // @todo Find a more reliable way to determine if a form element concerns a
510 // multilingual value.
511 if (!isset($ignored_types)) {
512 $ignored_types = array_flip(['actions', 'value', 'hidden', 'vertical_tabs', 'token', 'details']);
515 foreach (Element::children($element) as $key) {
516 if (!isset($element[$key]['#type'])) {
517 $this->entityFormSharedElements($element[$key], $form_state, $form);
520 // Ignore non-widget form elements.
521 if (isset($ignored_types[$element[$key]['#type']])) {
524 // Elements are considered to be non multilingual by default.
525 if (empty($element[$key]['#multilingual'])) {
526 // If we are displaying a multilingual entity form we need to provide
527 // translatability clues, otherwise the shared form elements should be
529 if (!$form_state->get(['content_translation', 'translation_form'])) {
530 $this->addTranslatabilityClue($element[$key]);
533 $element[$key]['#access'] = FALSE;
543 * Adds a clue about the form element translatability.
545 * If the given element does not have a #title attribute, the function is
546 * recursively applied to child elements.
548 * @param array $element
549 * A form element array.
551 protected function addTranslatabilityClue(&$element) {
552 static $suffix, $fapi_title_elements;
554 // Elements which can have a #title attribute according to FAPI Reference.
555 if (!isset($suffix)) {
556 $suffix = ' <span class="translation-entity-all-languages">(' . t('all languages') . ')</span>';
557 $fapi_title_elements = array_flip(['checkbox', 'checkboxes', 'date', 'details', 'fieldset', 'file', 'item', 'password', 'password_confirm', 'radio', 'radios', 'select', 'text_format', 'textarea', 'textfield', 'weight']);
560 // Update #title attribute for all elements that are allowed to have a
561 // #title attribute according to the Form API Reference. The reason for this
562 // check is because some elements have a #title attribute even though it is
563 // not rendered; for instance, field containers.
564 if (isset($element['#type']) && isset($fapi_title_elements[$element['#type']]) && isset($element['#title'])) {
565 $element['#title'] .= $suffix;
567 // If the current element does not have a (valid) title, try child elements.
568 elseif ($children = Element::children($element)) {
569 foreach ($children as $delta) {
570 $this->addTranslatabilityClue($element[$delta], $suffix);
573 // If there are no children, fall back to the current #title attribute if it
575 elseif (isset($element['#title'])) {
576 $element['#title'] .= $suffix;
581 * Entity builder method.
583 * @param string $entity_type
584 * The type of the entity.
585 * @param \Drupal\Core\Entity\EntityInterface $entity
586 * The entity whose form is being built.
588 * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
590 public function entityFormEntityBuild($entity_type, EntityInterface $entity, array $form, FormStateInterface $form_state) {
591 $form_object = $form_state->getFormObject();
592 $form_langcode = $form_object->getFormLangcode($form_state);
593 $values = &$form_state->getValue('content_translation', []);
595 $metadata = $this->manager->getTranslationMetadata($entity);
596 $metadata->setAuthor(!empty($values['uid']) ? User::load($values['uid']) : User::load(0));
597 $metadata->setPublished(!empty($values['status']));
598 $metadata->setCreatedTime(!empty($values['created']) ? strtotime($values['created']) : REQUEST_TIME);
600 $source_langcode = $this->getSourceLangcode($form_state);
601 if ($source_langcode) {
602 $metadata->setSource($source_langcode);
605 $metadata->setOutdated(!empty($values['outdated']));
606 if (!empty($values['retranslate'])) {
607 $this->retranslate($entity, $form_langcode);
612 * Form validation handler for ContentTranslationHandler::entityFormAlter().
614 * Validates the submitted content translation metadata.
616 public function entityFormValidate($form, FormStateInterface $form_state) {
617 if (!$form_state->isValueEmpty('content_translation')) {
618 $translation = $form_state->getValue('content_translation');
619 // Validate the "authored by" field.
620 if (!empty($translation['uid']) && !($account = User::load($translation['uid']))) {
621 $form_state->setErrorByName('content_translation][uid', t('The translation authoring username %name does not exist.', ['%name' => $account->getUsername()]));
623 // Validate the "authored on" field.
624 if (!empty($translation['created']) && strtotime($translation['created']) === FALSE) {
625 $form_state->setErrorByName('content_translation][created', t('You have to specify a valid translation authoring date.'));
631 * Form submission handler for ContentTranslationHandler::entityFormAlter().
633 * Updates metadata fields, which should be updated only after the validation
634 * has run and before the entity is saved.
636 public function entityFormSubmit($form, FormStateInterface $form_state) {
637 /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
638 $form_object = $form_state->getFormObject();
639 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
640 $entity = $form_object->getEntity();
642 // ContentEntityForm::submit will update the changed timestamp on submit
643 // after the entity has been validated, so that it does not break the
644 // EntityChanged constraint validator. The content translation metadata
645 // field for the changed timestamp does not have such a constraint defined
646 // at the moment, but it is correct to update it's value in a submission
647 // handler as well and have the same logic like in the Form API.
648 if ($entity->hasField('content_translation_changed')) {
649 $metadata = $this->manager->getTranslationMetadata($entity);
650 $metadata->setChangedTime(REQUEST_TIME);
655 * Form submission handler for ContentTranslationHandler::entityFormAlter().
657 * Takes care of the source language change.
659 public function entityFormSourceChange($form, FormStateInterface $form_state) {
660 $form_object = $form_state->getFormObject();
661 $entity = $form_object->getEntity();
662 $source = $form_state->getValue(['source_langcode', 'source']);
664 $entity_type_id = $entity->getEntityTypeId();
665 $form_state->setRedirect("entity.$entity_type_id.content_translation_add", [
666 $entity_type_id => $entity->id(),
668 'target' => $form_object->getFormLangcode($form_state),
670 $languages = $this->languageManager->getLanguages();
671 drupal_set_message(t('Source language set to: %language', ['%language' => $languages[$source]->getName()]));
675 * Form submission handler for ContentTranslationHandler::entityFormAlter().
677 * Takes care of entity deletion.
679 public function entityFormDelete($form, FormStateInterface $form_state) {
680 $form_object = $form_state->getFormObject()->getEntity();
681 $entity = $form_object->getEntity();
682 if (count($entity->getTranslationLanguages()) > 1) {
683 drupal_set_message(t('This will delete all the translations of %label.', ['%label' => $entity->label()]), 'warning');
688 * Form submission handler for ContentTranslationHandler::entityFormAlter().
690 * Takes care of content translation deletion.
692 public function entityFormDeleteTranslation($form, FormStateInterface $form_state) {
693 /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
694 $form_object = $form_state->getFormObject();
695 /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
696 $entity = $form_object->getEntity();
697 $entity_type_id = $entity->getEntityTypeId();
698 if ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form')) {
699 $form_state->setRedirectUrl($entity->urlInfo('delete-form'));
702 $form_state->setRedirect("entity.$entity_type_id.content_translation_delete", [
703 $entity_type_id => $entity->id(),
704 'language' => $form_object->getFormLangcode($form_state),
710 * Returns the title to be used for the entity form page.
712 * @param \Drupal\Core\Entity\EntityInterface $entity
713 * The entity whose form is being altered.
715 * @return string|null
716 * The label of the entity, or NULL if there is no label defined.
718 protected function entityFormTitle(EntityInterface $entity) {
719 return $entity->label();
723 * Default value callback for the owner base field definition.
728 public static function getDefaultOwnerId() {
729 return \Drupal::currentUser()->id();