0fef1bed47faabed957c4da3a6a409cbe902266b
[yaffs-website] / web / core / modules / content_translation / src / ContentTranslationHandler.php
1 <?php
2
3 namespace Drupal\content_translation;
4
5 use Drupal\Core\Access\AccessResult;
6 use Drupal\Core\DependencyInjection\DependencySerializationTrait;
7 use Drupal\Core\Entity\EntityChangedInterface;
8 use Drupal\Core\Entity\EntityChangesDetectionTrait;
9 use Drupal\Core\Entity\EntityHandlerInterface;
10 use Drupal\Core\Entity\EntityInterface;
11 use Drupal\Core\Entity\EntityManagerInterface;
12 use Drupal\Core\Entity\EntityTypeInterface;
13 use Drupal\Core\Field\BaseFieldDefinition;
14 use Drupal\Core\Form\FormStateInterface;
15 use Drupal\Core\Language\LanguageInterface;
16 use Drupal\Core\Language\LanguageManagerInterface;
17 use Drupal\Core\Messenger\MessengerInterface;
18 use Drupal\Core\Render\Element;
19 use Drupal\Core\Session\AccountInterface;
20 use Drupal\Core\StringTranslation\StringTranslationTrait;
21 use Drupal\user\Entity\User;
22 use Drupal\user\EntityOwnerInterface;
23 use Symfony\Component\DependencyInjection\ContainerInterface;
24
25 /**
26  * Base class for content translation handlers.
27  *
28  * @ingroup entity_api
29  */
30 class ContentTranslationHandler implements ContentTranslationHandlerInterface, EntityHandlerInterface {
31
32   use EntityChangesDetectionTrait;
33   use DependencySerializationTrait;
34   use StringTranslationTrait;
35
36   /**
37    * The type of the entity being translated.
38    *
39    * @var string
40    */
41   protected $entityTypeId;
42
43   /**
44    * Information about the entity type.
45    *
46    * @var \Drupal\Core\Entity\EntityTypeInterface
47    */
48   protected $entityType;
49
50   /**
51    * The language manager.
52    *
53    * @var \Drupal\Core\Language\LanguageManagerInterface
54    */
55   protected $languageManager;
56
57   /**
58    * The content translation manager.
59    *
60    * @var \Drupal\content_translation\ContentTranslationManagerInterface
61    */
62   protected $manager;
63
64   /**
65    * The entity type manager.
66    *
67    * @var \Drupal\Core\Entity\EntityTypeManagerInterface
68    */
69   protected $entityTypeManager;
70
71   /**
72    * The current user.
73    *
74    * @var \Drupal\Core\Session\AccountInterface
75    */
76   protected $currentUser;
77
78   /**
79    * The array of installed field storage definitions for the entity type, keyed
80    * by field name.
81    *
82    * @var \Drupal\Core\Field\FieldStorageDefinitionInterface[]
83    */
84   protected $fieldStorageDefinitions;
85
86   /**
87    * The messenger service.
88    *
89    * @var \Drupal\Core\Messenger\MessengerInterface
90    */
91   protected $messenger;
92
93   /**
94    * Initializes an instance of the content translation controller.
95    *
96    * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
97    *   The info array of the given entity type.
98    * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
99    *   The language manager.
100    * @param \Drupal\content_translation\ContentTranslationManagerInterface $manager
101    *   The content translation manager service.
102    * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
103    *   The entity manager.
104    * @param \Drupal\Core\Session\AccountInterface $current_user
105    *   The current user.
106    * @param \Drupal\Core\Messenger\MessengerInterface $messenger
107    *   The messenger service.
108    */
109   public function __construct(EntityTypeInterface $entity_type, LanguageManagerInterface $language_manager, ContentTranslationManagerInterface $manager, EntityManagerInterface $entity_manager, AccountInterface $current_user, MessengerInterface $messenger) {
110     $this->entityTypeId = $entity_type->id();
111     $this->entityType = $entity_type;
112     $this->languageManager = $language_manager;
113     $this->manager = $manager;
114     $this->entityTypeManager = $entity_manager;
115     $this->currentUser = $current_user;
116     $this->fieldStorageDefinitions = $entity_manager->getLastInstalledFieldStorageDefinitions($this->entityTypeId);
117     $this->messenger = $messenger;
118   }
119
120   /**
121    * {@inheritdoc}
122    */
123   public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
124     return new static(
125       $entity_type,
126       $container->get('language_manager'),
127       $container->get('content_translation.manager'),
128       $container->get('entity.manager'),
129       $container->get('current_user'),
130       $container->get('messenger')
131     );
132   }
133
134   /**
135    * {@inheritdoc}
136    */
137   public function getFieldDefinitions() {
138     $definitions = [];
139
140     $definitions['content_translation_source'] = BaseFieldDefinition::create('language')
141       ->setLabel(t('Translation source'))
142       ->setDescription(t('The source language from which this translation was created.'))
143       ->setDefaultValue(LanguageInterface::LANGCODE_NOT_SPECIFIED)
144       ->setInitialValue(LanguageInterface::LANGCODE_NOT_SPECIFIED)
145       ->setRevisionable(TRUE)
146       ->setTranslatable(TRUE);
147
148     $definitions['content_translation_outdated'] = BaseFieldDefinition::create('boolean')
149       ->setLabel(t('Translation outdated'))
150       ->setDescription(t('A boolean indicating whether this translation needs to be updated.'))
151       ->setDefaultValue(FALSE)
152       ->setInitialValue(FALSE)
153       ->setRevisionable(TRUE)
154       ->setTranslatable(TRUE);
155
156     if (!$this->hasAuthor()) {
157       $definitions['content_translation_uid'] = BaseFieldDefinition::create('entity_reference')
158         ->setLabel(t('Translation author'))
159         ->setDescription(t('The author of this translation.'))
160         ->setSetting('target_type', 'user')
161         ->setSetting('handler', 'default')
162         ->setRevisionable(TRUE)
163         ->setDefaultValueCallback(get_class($this) . '::getDefaultOwnerId')
164         ->setTranslatable(TRUE);
165     }
166
167     if (!$this->hasPublishedStatus()) {
168       $definitions['content_translation_status'] = BaseFieldDefinition::create('boolean')
169         ->setLabel(t('Translation status'))
170         ->setDescription(t('A boolean indicating whether the translation is visible to non-translators.'))
171         ->setDefaultValue(TRUE)
172         ->setInitialValue(TRUE)
173         ->setRevisionable(TRUE)
174         ->setTranslatable(TRUE);
175     }
176
177     if (!$this->hasCreatedTime()) {
178       $definitions['content_translation_created'] = BaseFieldDefinition::create('created')
179         ->setLabel(t('Translation created time'))
180         ->setDescription(t('The Unix timestamp when the translation was created.'))
181         ->setRevisionable(TRUE)
182         ->setTranslatable(TRUE);
183     }
184
185     if (!$this->hasChangedTime()) {
186       $definitions['content_translation_changed'] = BaseFieldDefinition::create('changed')
187         ->setLabel(t('Translation changed time'))
188         ->setDescription(t('The Unix timestamp when the translation was most recently saved.'))
189         ->setRevisionable(TRUE)
190         ->setTranslatable(TRUE);
191     }
192
193     return $definitions;
194   }
195
196   /**
197    * Checks whether the entity type supports author natively.
198    *
199    * @return bool
200    *   TRUE if metadata is natively supported, FALSE otherwise.
201    */
202   protected function hasAuthor() {
203     // Check for field named uid, but only in case the entity implements the
204     // EntityOwnerInterface. This helps to exclude cases, where the uid is
205     // defined as field name, but is not meant to be an owner field; for
206     // instance, the User entity.
207     return $this->entityType->entityClassImplements(EntityOwnerInterface::class) && $this->checkFieldStorageDefinitionTranslatability('uid');
208   }
209
210   /**
211    * Checks whether the entity type supports published status natively.
212    *
213    * @return bool
214    *   TRUE if metadata is natively supported, FALSE otherwise.
215    */
216   protected function hasPublishedStatus() {
217     return $this->checkFieldStorageDefinitionTranslatability('status');
218   }
219
220   /**
221    * Checks whether the entity type supports modification time natively.
222    *
223    * @return bool
224    *   TRUE if metadata is natively supported, FALSE otherwise.
225    */
226   protected function hasChangedTime() {
227     return $this->entityType->entityClassImplements(EntityChangedInterface::class) && $this->checkFieldStorageDefinitionTranslatability('changed');
228   }
229
230   /**
231    * Checks whether the entity type supports creation time natively.
232    *
233    * @return bool
234    *   TRUE if metadata is natively supported, FALSE otherwise.
235    */
236   protected function hasCreatedTime() {
237     return $this->checkFieldStorageDefinitionTranslatability('created');
238   }
239
240   /**
241    * Checks the field storage definition for translatability support.
242    *
243    * Checks whether the given field is defined in the field storage definitions
244    * and if its definition specifies it as translatable.
245    *
246    * @param string $field_name
247    *   The name of the field.
248    *
249    * @return bool
250    *   TRUE if translatable field storage definition exists, FALSE otherwise.
251    */
252   protected function checkFieldStorageDefinitionTranslatability($field_name) {
253     return array_key_exists($field_name, $this->fieldStorageDefinitions) && $this->fieldStorageDefinitions[$field_name]->isTranslatable();
254   }
255
256   /**
257    * {@inheritdoc}
258    */
259   public function retranslate(EntityInterface $entity, $langcode = NULL) {
260     $updated_langcode = !empty($langcode) ? $langcode : $entity->language()->getId();
261     foreach ($entity->getTranslationLanguages() as $langcode => $language) {
262       $this->manager->getTranslationMetadata($entity->getTranslation($langcode))
263         ->setOutdated($langcode != $updated_langcode);
264     }
265   }
266
267   /**
268    * {@inheritdoc}
269    */
270   public function getTranslationAccess(EntityInterface $entity, $op) {
271     // @todo Move this logic into a translation access control handler checking also
272     //   the translation language and the given account.
273     $entity_type = $entity->getEntityType();
274     $translate_permission = TRUE;
275     // If no permission granularity is defined this entity type does not need an
276     // explicit translate permission.
277     if (!$this->currentUser->hasPermission('translate any entity') && $permission_granularity = $entity_type->getPermissionGranularity()) {
278       $translate_permission = $this->currentUser->hasPermission($permission_granularity == 'bundle' ? "translate {$entity->bundle()} {$entity->getEntityTypeId()}" : "translate {$entity->getEntityTypeId()}");
279     }
280     return AccessResult::allowedIf($translate_permission && $this->currentUser->hasPermission("$op content translations"))->cachePerPermissions();
281   }
282
283   /**
284    * {@inheritdoc}
285    */
286   public function getSourceLangcode(FormStateInterface $form_state) {
287     if ($source = $form_state->get(['content_translation', 'source'])) {
288       return $source->getId();
289     }
290     return FALSE;
291   }
292
293   /**
294    * {@inheritdoc}
295    */
296   public function entityFormAlter(array &$form, FormStateInterface $form_state, EntityInterface $entity) {
297     /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
298
299     $form_object = $form_state->getFormObject();
300     $form_langcode = $form_object->getFormLangcode($form_state);
301     $entity_langcode = $entity->getUntranslated()->language()->getId();
302     $source_langcode = $this->getSourceLangcode($form_state);
303
304     $new_translation = !empty($source_langcode);
305     $translations = $entity->getTranslationLanguages();
306     if ($new_translation) {
307       // Make sure a new translation does not appear as existing yet.
308       unset($translations[$form_langcode]);
309     }
310     $is_translation = !$form_object->isDefaultFormLangcode($form_state);
311     $has_translations = count($translations) > 1;
312
313     // Adjust page title to specify the current language being edited, if we
314     // have at least one translation.
315     $languages = $this->languageManager->getLanguages();
316     if (isset($languages[$form_langcode]) && ($has_translations || $new_translation)) {
317       $title = $this->entityFormTitle($entity);
318       // When editing the original values display just the entity label.
319       if ($is_translation) {
320         $t_args = ['%language' => $languages[$form_langcode]->getName(), '%title' => $entity->label(), '@title' => $title];
321         $title = empty($source_langcode) ? t('@title [%language translation]', $t_args) : t('Create %language translation of %title', $t_args);
322       }
323       $form['#title'] = $title;
324     }
325
326     // Display source language selector only if we are creating a new
327     // translation and there are at least two translations available.
328     if ($has_translations && $new_translation) {
329       $form['source_langcode'] = [
330         '#type' => 'details',
331         '#title' => t('Source language: @language', ['@language' => $languages[$source_langcode]->getName()]),
332         '#tree' => TRUE,
333         '#weight' => -100,
334         '#multilingual' => TRUE,
335         'source' => [
336           '#title' => t('Select source language'),
337           '#title_display' => 'invisible',
338           '#type' => 'select',
339           '#default_value' => $source_langcode,
340           '#options' => [],
341         ],
342         'submit' => [
343           '#type' => 'submit',
344           '#value' => t('Change'),
345           '#submit' => [[$this, 'entityFormSourceChange']],
346         ],
347       ];
348       foreach ($this->languageManager->getLanguages() as $language) {
349         if (isset($translations[$language->getId()])) {
350           $form['source_langcode']['source']['#options'][$language->getId()] = $language->getName();
351         }
352       }
353     }
354
355     // Locate the language widget.
356     $langcode_key = $this->entityType->getKey('langcode');
357     if (isset($form[$langcode_key])) {
358       $language_widget = &$form[$langcode_key];
359     }
360
361     // If we are editing the source entity, limit the list of languages so that
362     // it is not possible to switch to a language for which a translation
363     // already exists. Note that this will only work if the widget is structured
364     // like \Drupal\Core\Field\Plugin\Field\FieldWidget\LanguageSelectWidget.
365     if (isset($language_widget['widget'][0]['value']) && !$is_translation && $has_translations) {
366       $language_select = &$language_widget['widget'][0]['value'];
367       if ($language_select['#type'] == 'language_select') {
368         $options = [];
369         foreach ($this->languageManager->getLanguages() as $language) {
370           // Show the current language, and the languages for which no
371           // translation already exists.
372           if (empty($translations[$language->getId()]) || $language->getId() == $entity_langcode) {
373             $options[$language->getId()] = $language->getName();
374           }
375         }
376         $language_select['#options'] = $options;
377       }
378     }
379     if ($is_translation) {
380       if (isset($language_widget)) {
381         $language_widget['widget']['#access'] = FALSE;
382       }
383
384       // Replace the delete button with the delete translation one.
385       if (!$new_translation) {
386         $weight = 100;
387         foreach (['delete', 'submit'] as $key) {
388           if (isset($form['actions'][$key]['weight'])) {
389             $weight = $form['actions'][$key]['weight'];
390             break;
391           }
392         }
393         /** @var \Drupal\Core\Access\AccessResultInterface $delete_access */
394         $delete_access = \Drupal::service('content_translation.delete_access')->checkAccess($entity);
395         $access = $delete_access->isAllowed() && (
396           $this->getTranslationAccess($entity, 'delete')->isAllowed() ||
397           ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form'))
398         );
399         $form['actions']['delete_translation'] = [
400           '#type' => 'submit',
401           '#value' => t('Delete translation'),
402           '#weight' => $weight,
403           '#submit' => [[$this, 'entityFormDeleteTranslation']],
404           '#access' => $access,
405         ];
406       }
407
408       // Always remove the delete button on translation forms.
409       unset($form['actions']['delete']);
410     }
411
412     // We need to display the translation tab only when there is at least one
413     // translation available or a new one is about to be created.
414     if ($new_translation || $has_translations) {
415       $form['content_translation'] = [
416         '#type' => 'details',
417         '#title' => t('Translation'),
418         '#tree' => TRUE,
419         '#weight' => 10,
420         '#access' => $this->getTranslationAccess($entity, $source_langcode ? 'create' : 'update')->isAllowed(),
421         '#multilingual' => TRUE,
422       ];
423
424       if (isset($form['advanced'])) {
425         $form['content_translation'] += [
426           '#group' => 'advanced',
427           '#weight' => 100,
428           '#attributes' => [
429             'class' => ['entity-translation-options'],
430           ],
431         ];
432       }
433
434       // A new translation is enabled by default.
435       $metadata = $this->manager->getTranslationMetadata($entity);
436       $status = $new_translation || $metadata->isPublished();
437       // If there is only one published translation we cannot unpublish it,
438       // since there would be nothing left to display.
439       $enabled = TRUE;
440       if ($status) {
441         $published = 0;
442         foreach ($entity->getTranslationLanguages() as $langcode => $language) {
443           $published += $this->manager->getTranslationMetadata($entity->getTranslation($langcode))
444             ->isPublished();
445         }
446         $enabled = $published > 1;
447       }
448       $description = $enabled ?
449         t('An unpublished translation will not be visible without translation permissions.') :
450         t('Only this translation is published. You must publish at least one more translation to unpublish this one.');
451
452       $form['content_translation']['status'] = [
453         '#type' => 'checkbox',
454         '#title' => t('This translation is published'),
455         '#default_value' => $status,
456         '#description' => $description,
457         '#disabled' => !$enabled,
458       ];
459
460       $translate = !$new_translation && $metadata->isOutdated();
461       $outdated_access = !ContentTranslationManager::isPendingRevisionSupportEnabled($entity->getEntityTypeId(), $entity->bundle());
462       if (!$outdated_access) {
463         $form['content_translation']['outdated'] = [
464           '#markup' => $this->t('Translations cannot be flagged as outdated when content is moderated.'),
465         ];
466       }
467       elseif (!$translate) {
468         $form['content_translation']['retranslate'] = [
469           '#type' => 'checkbox',
470           '#title' => t('Flag other translations as outdated'),
471           '#default_value' => FALSE,
472           '#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.'),
473           '#access' => $outdated_access,
474         ];
475       }
476       else {
477         $form['content_translation']['outdated'] = [
478           '#type' => 'checkbox',
479           '#title' => t('This translation needs to be updated'),
480           '#default_value' => $translate,
481           '#description' => t('When this option is checked, this translation needs to be updated. Uncheck when the translation is up to date again.'),
482           '#access' => $outdated_access,
483         ];
484         $form['content_translation']['#open'] = TRUE;
485       }
486
487       // Default to the anonymous user.
488       $uid = 0;
489       if ($new_translation) {
490         $uid = $this->currentUser->id();
491       }
492       elseif (($account = $metadata->getAuthor()) && $account->id()) {
493         $uid = $account->id();
494       }
495       $form['content_translation']['uid'] = [
496         '#type' => 'entity_autocomplete',
497         '#title' => t('Authored by'),
498         '#target_type' => 'user',
499         '#default_value' => User::load($uid),
500         // Validation is done by static::entityFormValidate().
501         '#validate_reference' => FALSE,
502         '#maxlength' => 60,
503         '#description' => t('Leave blank for %anonymous.', ['%anonymous' => \Drupal::config('user.settings')->get('anonymous')]),
504       ];
505
506       $date = $new_translation ? REQUEST_TIME : $metadata->getCreatedTime();
507       $form['content_translation']['created'] = [
508         '#type' => 'textfield',
509         '#title' => t('Authored on'),
510         '#maxlength' => 25,
511         '#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')]),
512         '#default_value' => $new_translation || !$date ? '' : format_date($date, 'custom', 'Y-m-d H:i:s O'),
513       ];
514
515       $form['#process'][] = [$this, 'entityFormSharedElements'];
516     }
517
518     // Process the submitted values before they are stored.
519     $form['#entity_builders'][] = [$this, 'entityFormEntityBuild'];
520
521     // Handle entity validation.
522     $form['#validate'][] = [$this, 'entityFormValidate'];
523
524     // Handle entity deletion.
525     if (isset($form['actions']['delete'])) {
526       $form['actions']['delete']['#submit'][] = [$this, 'entityFormDelete'];
527     }
528
529     // Handle entity form submission before the entity has been saved.
530     foreach (Element::children($form['actions']) as $action) {
531       if (isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] == 'submit') {
532         array_unshift($form['actions'][$action]['#submit'], [$this, 'entityFormSubmit']);
533       }
534     }
535   }
536
537   /**
538    * Process callback: determines which elements get clue in the form.
539    *
540    * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
541    */
542   public function entityFormSharedElements($element, FormStateInterface $form_state, $form) {
543     static $ignored_types;
544
545     // @todo Find a more reliable way to determine if a form element concerns a
546     //   multilingual value.
547     if (!isset($ignored_types)) {
548       $ignored_types = array_flip(['actions', 'value', 'hidden', 'vertical_tabs', 'token', 'details']);
549     }
550
551     /** @var \Drupal\Core\Entity\ContentEntityForm $form_object */
552     $form_object = $form_state->getFormObject();
553     /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
554     $entity = $form_object->getEntity();
555     $display_translatability_clue = !$entity->isDefaultTranslationAffectedOnly();
556     $hide_untranslatable_fields = $entity->isDefaultTranslationAffectedOnly() && !$entity->isDefaultTranslation();
557     $translation_form = $form_state->get(['content_translation', 'translation_form']);
558     $display_warning = FALSE;
559
560     // We use field definitions to identify untranslatable field widgets to be
561     // hidden. Fields that are not involved in translation changes checks should
562     // not be affected by this logic (the "revision_log" field, for instance).
563     $field_definitions = array_diff_key($entity->getFieldDefinitions(), array_flip($this->getFieldsToSkipFromTranslationChangesCheck($entity)));
564
565     foreach (Element::children($element) as $key) {
566       if (!isset($element[$key]['#type'])) {
567         $this->entityFormSharedElements($element[$key], $form_state, $form);
568       }
569       else {
570         // Ignore non-widget form elements.
571         if (isset($ignored_types[$element[$key]['#type']])) {
572           continue;
573         }
574         // Elements are considered to be non multilingual by default.
575         if (empty($element[$key]['#multilingual'])) {
576           // If we are displaying a multilingual entity form we need to provide
577           // translatability clues, otherwise the non-multilingual form elements
578           // should be hidden.
579           if (!$translation_form) {
580             if ($display_translatability_clue) {
581               $this->addTranslatabilityClue($element[$key]);
582             }
583             // Hide widgets for untranslatable fields.
584             if ($hide_untranslatable_fields && isset($field_definitions[$key])) {
585               $element[$key]['#access'] = FALSE;
586               $display_warning = TRUE;
587             }
588           }
589           else {
590             $element[$key]['#access'] = FALSE;
591           }
592         }
593       }
594     }
595
596     if ($display_warning && !$form_state->isSubmitted() && !$form_state->isRebuilding()) {
597       $url = $entity->getUntranslated()->toUrl('edit-form')->toString();
598       $this->messenger->addWarning($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]));
599     }
600
601     return $element;
602   }
603
604   /**
605    * Adds a clue about the form element translatability.
606    *
607    * If the given element does not have a #title attribute, the function is
608    * recursively applied to child elements.
609    *
610    * @param array $element
611    *   A form element array.
612    */
613   protected function addTranslatabilityClue(&$element) {
614     static $suffix, $fapi_title_elements;
615
616     // Elements which can have a #title attribute according to FAPI Reference.
617     if (!isset($suffix)) {
618       $suffix = ' <span class="translation-entity-all-languages">(' . t('all languages') . ')</span>';
619       $fapi_title_elements = array_flip(['checkbox', 'checkboxes', 'date', 'details', 'fieldset', 'file', 'item', 'password', 'password_confirm', 'radio', 'radios', 'select', 'text_format', 'textarea', 'textfield', 'weight']);
620     }
621
622     // Update #title attribute for all elements that are allowed to have a
623     // #title attribute according to the Form API Reference. The reason for this
624     // check is because some elements have a #title attribute even though it is
625     // not rendered; for instance, field containers.
626     if (isset($element['#type']) && isset($fapi_title_elements[$element['#type']]) && isset($element['#title'])) {
627       $element['#title'] .= $suffix;
628     }
629     // If the current element does not have a (valid) title, try child elements.
630     elseif ($children = Element::children($element)) {
631       foreach ($children as $delta) {
632         $this->addTranslatabilityClue($element[$delta], $suffix);
633       }
634     }
635     // If there are no children, fall back to the current #title attribute if it
636     // exists.
637     elseif (isset($element['#title'])) {
638       $element['#title'] .= $suffix;
639     }
640   }
641
642   /**
643    * Entity builder method.
644    *
645    * @param string $entity_type
646    *   The type of the entity.
647    * @param \Drupal\Core\Entity\EntityInterface $entity
648    *   The entity whose form is being built.
649    *
650    * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
651    */
652   public function entityFormEntityBuild($entity_type, EntityInterface $entity, array $form, FormStateInterface $form_state) {
653     $form_object = $form_state->getFormObject();
654     $form_langcode = $form_object->getFormLangcode($form_state);
655     $values = &$form_state->getValue('content_translation', []);
656
657     $metadata = $this->manager->getTranslationMetadata($entity);
658     $metadata->setAuthor(!empty($values['uid']) ? User::load($values['uid']) : User::load(0));
659     $metadata->setPublished(!empty($values['status']));
660     $metadata->setCreatedTime(!empty($values['created']) ? strtotime($values['created']) : REQUEST_TIME);
661
662     $source_langcode = $this->getSourceLangcode($form_state);
663     if ($source_langcode) {
664       $metadata->setSource($source_langcode);
665     }
666
667     $metadata->setOutdated(!empty($values['outdated']));
668     if (!empty($values['retranslate'])) {
669       $this->retranslate($entity, $form_langcode);
670     }
671   }
672
673   /**
674    * Form validation handler for ContentTranslationHandler::entityFormAlter().
675    *
676    * Validates the submitted content translation metadata.
677    */
678   public function entityFormValidate($form, FormStateInterface $form_state) {
679     if (!$form_state->isValueEmpty('content_translation')) {
680       $translation = $form_state->getValue('content_translation');
681       // Validate the "authored by" field.
682       if (!empty($translation['uid']) && !($account = User::load($translation['uid']))) {
683         $form_state->setErrorByName('content_translation][uid', t('The translation authoring username %name does not exist.', ['%name' => $account->getUsername()]));
684       }
685       // Validate the "authored on" field.
686       if (!empty($translation['created']) && strtotime($translation['created']) === FALSE) {
687         $form_state->setErrorByName('content_translation][created', t('You have to specify a valid translation authoring date.'));
688       }
689     }
690   }
691
692   /**
693    * Form submission handler for ContentTranslationHandler::entityFormAlter().
694    *
695    * Updates metadata fields, which should be updated only after the validation
696    * has run and before the entity is saved.
697    */
698   public function entityFormSubmit($form, FormStateInterface $form_state) {
699     /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
700     $form_object = $form_state->getFormObject();
701     /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
702     $entity = $form_object->getEntity();
703
704     // ContentEntityForm::submit will update the changed timestamp on submit
705     // after the entity has been validated, so that it does not break the
706     // EntityChanged constraint validator. The content translation metadata
707     // field for the changed timestamp  does not have such a constraint defined
708     // at the moment, but it is correct to update its value in a submission
709     // handler as well and have the same logic like in the Form API.
710     if ($entity->hasField('content_translation_changed')) {
711       $metadata = $this->manager->getTranslationMetadata($entity);
712       $metadata->setChangedTime(REQUEST_TIME);
713     }
714   }
715
716   /**
717    * Form submission handler for ContentTranslationHandler::entityFormAlter().
718    *
719    * Takes care of the source language change.
720    */
721   public function entityFormSourceChange($form, FormStateInterface $form_state) {
722     $form_object = $form_state->getFormObject();
723     $entity = $form_object->getEntity();
724     $source = $form_state->getValue(['source_langcode', 'source']);
725
726     $entity_type_id = $entity->getEntityTypeId();
727     $form_state->setRedirect("entity.$entity_type_id.content_translation_add", [
728       $entity_type_id => $entity->id(),
729       'source' => $source,
730       'target' => $form_object->getFormLangcode($form_state),
731     ]);
732     $languages = $this->languageManager->getLanguages();
733     $this->messenger->addStatus(t('Source language set to: %language', ['%language' => $languages[$source]->getName()]));
734   }
735
736   /**
737    * Form submission handler for ContentTranslationHandler::entityFormAlter().
738    *
739    * Takes care of entity deletion.
740    */
741   public function entityFormDelete($form, FormStateInterface $form_state) {
742     $form_object = $form_state->getFormObject();
743     $entity = $form_object->getEntity();
744     if (count($entity->getTranslationLanguages()) > 1) {
745       $this->messenger->addWarning(t('This will delete all the translations of %label.', ['%label' => $entity->label()]));
746     }
747   }
748
749   /**
750    * Form submission handler for ContentTranslationHandler::entityFormAlter().
751    *
752    * Takes care of content translation deletion.
753    */
754   public function entityFormDeleteTranslation($form, FormStateInterface $form_state) {
755     /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
756     $form_object = $form_state->getFormObject();
757     /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
758     $entity = $form_object->getEntity();
759     $entity_type_id = $entity->getEntityTypeId();
760     if ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form')) {
761       $form_state->setRedirectUrl($entity->urlInfo('delete-form'));
762     }
763     else {
764       $form_state->setRedirect("entity.$entity_type_id.content_translation_delete", [
765         $entity_type_id => $entity->id(),
766         'language' => $form_object->getFormLangcode($form_state),
767       ]);
768     }
769   }
770
771   /**
772    * Returns the title to be used for the entity form page.
773    *
774    * @param \Drupal\Core\Entity\EntityInterface $entity
775    *   The entity whose form is being altered.
776    *
777    * @return string|null
778    *   The label of the entity, or NULL if there is no label defined.
779    */
780   protected function entityFormTitle(EntityInterface $entity) {
781     return $entity->label();
782   }
783
784   /**
785    * Default value callback for the owner base field definition.
786    *
787    * @return int
788    *   The user ID.
789    */
790   public static function getDefaultOwnerId() {
791     return \Drupal::currentUser()->id();
792   }
793
794 }