bcf66bd53b0fbebe421b481c25a7a72a6b22fade
[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       if (isset($language_widget)) {
516         $language_widget['#multilingual'] = TRUE;
517       }
518
519       $form['#process'][] = [$this, 'entityFormSharedElements'];
520     }
521
522     // Process the submitted values before they are stored.
523     $form['#entity_builders'][] = [$this, 'entityFormEntityBuild'];
524
525     // Handle entity validation.
526     $form['#validate'][] = [$this, 'entityFormValidate'];
527
528     // Handle entity deletion.
529     if (isset($form['actions']['delete'])) {
530       $form['actions']['delete']['#submit'][] = [$this, 'entityFormDelete'];
531     }
532
533     // Handle entity form submission before the entity has been saved.
534     foreach (Element::children($form['actions']) as $action) {
535       if (isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] == 'submit') {
536         array_unshift($form['actions'][$action]['#submit'], [$this, 'entityFormSubmit']);
537       }
538     }
539   }
540
541   /**
542    * Process callback: determines which elements get clue in the form.
543    *
544    * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
545    */
546   public function entityFormSharedElements($element, FormStateInterface $form_state, $form) {
547     static $ignored_types;
548
549     // @todo Find a more reliable way to determine if a form element concerns a
550     //   multilingual value.
551     if (!isset($ignored_types)) {
552       $ignored_types = array_flip(['actions', 'value', 'hidden', 'vertical_tabs', 'token', 'details']);
553     }
554
555     /** @var \Drupal\Core\Entity\ContentEntityForm $form_object */
556     $form_object = $form_state->getFormObject();
557     /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
558     $entity = $form_object->getEntity();
559     $display_translatability_clue = !$entity->isDefaultTranslationAffectedOnly();
560     $hide_untranslatable_fields = $entity->isDefaultTranslationAffectedOnly() && !$entity->isDefaultTranslation();
561     $translation_form = $form_state->get(['content_translation', 'translation_form']);
562     $display_warning = FALSE;
563
564     // We use field definitions to identify untranslatable field widgets to be
565     // hidden. Fields that are not involved in translation changes checks should
566     // not be affected by this logic (the "revision_log" field, for instance).
567     $field_definitions = array_diff_key($entity->getFieldDefinitions(), array_flip($this->getFieldsToSkipFromTranslationChangesCheck($entity)));
568
569     foreach (Element::children($element) as $key) {
570       if (!isset($element[$key]['#type'])) {
571         $this->entityFormSharedElements($element[$key], $form_state, $form);
572       }
573       else {
574         // Ignore non-widget form elements.
575         if (isset($ignored_types[$element[$key]['#type']])) {
576           continue;
577         }
578         // Elements are considered to be non multilingual by default.
579         if (empty($element[$key]['#multilingual'])) {
580           // If we are displaying a multilingual entity form we need to provide
581           // translatability clues, otherwise the non-multilingual form elements
582           // should be hidden.
583           if (!$translation_form) {
584             if ($display_translatability_clue) {
585               $this->addTranslatabilityClue($element[$key]);
586             }
587             // Hide widgets for untranslatable fields.
588             if ($hide_untranslatable_fields && isset($field_definitions[$key])) {
589               $element[$key]['#access'] = FALSE;
590               $display_warning = TRUE;
591             }
592           }
593           else {
594             $element[$key]['#access'] = FALSE;
595           }
596         }
597       }
598     }
599
600     if ($display_warning && !$form_state->isSubmitted() && !$form_state->isRebuilding()) {
601       $url = $entity->getUntranslated()->toUrl('edit-form')->toString();
602       $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]));
603     }
604
605     return $element;
606   }
607
608   /**
609    * Adds a clue about the form element translatability.
610    *
611    * If the given element does not have a #title attribute, the function is
612    * recursively applied to child elements.
613    *
614    * @param array $element
615    *   A form element array.
616    */
617   protected function addTranslatabilityClue(&$element) {
618     static $suffix, $fapi_title_elements;
619
620     // Elements which can have a #title attribute according to FAPI Reference.
621     if (!isset($suffix)) {
622       $suffix = ' <span class="translation-entity-all-languages">(' . t('all languages') . ')</span>';
623       $fapi_title_elements = array_flip(['checkbox', 'checkboxes', 'date', 'details', 'fieldset', 'file', 'item', 'password', 'password_confirm', 'radio', 'radios', 'select', 'text_format', 'textarea', 'textfield', 'weight']);
624     }
625
626     // Update #title attribute for all elements that are allowed to have a
627     // #title attribute according to the Form API Reference. The reason for this
628     // check is because some elements have a #title attribute even though it is
629     // not rendered; for instance, field containers.
630     if (isset($element['#type']) && isset($fapi_title_elements[$element['#type']]) && isset($element['#title'])) {
631       $element['#title'] .= $suffix;
632     }
633     // If the current element does not have a (valid) title, try child elements.
634     elseif ($children = Element::children($element)) {
635       foreach ($children as $delta) {
636         $this->addTranslatabilityClue($element[$delta], $suffix);
637       }
638     }
639     // If there are no children, fall back to the current #title attribute if it
640     // exists.
641     elseif (isset($element['#title'])) {
642       $element['#title'] .= $suffix;
643     }
644   }
645
646   /**
647    * Entity builder method.
648    *
649    * @param string $entity_type
650    *   The type of the entity.
651    * @param \Drupal\Core\Entity\EntityInterface $entity
652    *   The entity whose form is being built.
653    *
654    * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
655    */
656   public function entityFormEntityBuild($entity_type, EntityInterface $entity, array $form, FormStateInterface $form_state) {
657     $form_object = $form_state->getFormObject();
658     $form_langcode = $form_object->getFormLangcode($form_state);
659     $values = &$form_state->getValue('content_translation', []);
660
661     $metadata = $this->manager->getTranslationMetadata($entity);
662     $metadata->setAuthor(!empty($values['uid']) ? User::load($values['uid']) : User::load(0));
663     $metadata->setPublished(!empty($values['status']));
664     $metadata->setCreatedTime(!empty($values['created']) ? strtotime($values['created']) : REQUEST_TIME);
665
666     $source_langcode = $this->getSourceLangcode($form_state);
667     if ($source_langcode) {
668       $metadata->setSource($source_langcode);
669     }
670
671     $metadata->setOutdated(!empty($values['outdated']));
672     if (!empty($values['retranslate'])) {
673       $this->retranslate($entity, $form_langcode);
674     }
675   }
676
677   /**
678    * Form validation handler for ContentTranslationHandler::entityFormAlter().
679    *
680    * Validates the submitted content translation metadata.
681    */
682   public function entityFormValidate($form, FormStateInterface $form_state) {
683     if (!$form_state->isValueEmpty('content_translation')) {
684       $translation = $form_state->getValue('content_translation');
685       // Validate the "authored by" field.
686       if (!empty($translation['uid']) && !($account = User::load($translation['uid']))) {
687         $form_state->setErrorByName('content_translation][uid', t('The translation authoring username %name does not exist.', ['%name' => $account->getUsername()]));
688       }
689       // Validate the "authored on" field.
690       if (!empty($translation['created']) && strtotime($translation['created']) === FALSE) {
691         $form_state->setErrorByName('content_translation][created', t('You have to specify a valid translation authoring date.'));
692       }
693     }
694   }
695
696   /**
697    * Form submission handler for ContentTranslationHandler::entityFormAlter().
698    *
699    * Updates metadata fields, which should be updated only after the validation
700    * has run and before the entity is saved.
701    */
702   public function entityFormSubmit($form, FormStateInterface $form_state) {
703     /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
704     $form_object = $form_state->getFormObject();
705     /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
706     $entity = $form_object->getEntity();
707
708     // ContentEntityForm::submit will update the changed timestamp on submit
709     // after the entity has been validated, so that it does not break the
710     // EntityChanged constraint validator. The content translation metadata
711     // field for the changed timestamp  does not have such a constraint defined
712     // at the moment, but it is correct to update its value in a submission
713     // handler as well and have the same logic like in the Form API.
714     if ($entity->hasField('content_translation_changed')) {
715       $metadata = $this->manager->getTranslationMetadata($entity);
716       $metadata->setChangedTime(REQUEST_TIME);
717     }
718   }
719
720   /**
721    * Form submission handler for ContentTranslationHandler::entityFormAlter().
722    *
723    * Takes care of the source language change.
724    */
725   public function entityFormSourceChange($form, FormStateInterface $form_state) {
726     $form_object = $form_state->getFormObject();
727     $entity = $form_object->getEntity();
728     $source = $form_state->getValue(['source_langcode', 'source']);
729
730     $entity_type_id = $entity->getEntityTypeId();
731     $form_state->setRedirect("entity.$entity_type_id.content_translation_add", [
732       $entity_type_id => $entity->id(),
733       'source' => $source,
734       'target' => $form_object->getFormLangcode($form_state),
735     ]);
736     $languages = $this->languageManager->getLanguages();
737     drupal_set_message(t('Source language set to: %language', ['%language' => $languages[$source]->getName()]));
738   }
739
740   /**
741    * Form submission handler for ContentTranslationHandler::entityFormAlter().
742    *
743    * Takes care of entity deletion.
744    */
745   public function entityFormDelete($form, FormStateInterface $form_state) {
746     $form_object = $form_state->getFormObject()->getEntity();
747     $entity = $form_object->getEntity();
748     if (count($entity->getTranslationLanguages()) > 1) {
749       drupal_set_message(t('This will delete all the translations of %label.', ['%label' => $entity->label()]), 'warning');
750     }
751   }
752
753   /**
754    * Form submission handler for ContentTranslationHandler::entityFormAlter().
755    *
756    * Takes care of content translation deletion.
757    */
758   public function entityFormDeleteTranslation($form, FormStateInterface $form_state) {
759     /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
760     $form_object = $form_state->getFormObject();
761     /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
762     $entity = $form_object->getEntity();
763     $entity_type_id = $entity->getEntityTypeId();
764     if ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form')) {
765       $form_state->setRedirectUrl($entity->urlInfo('delete-form'));
766     }
767     else {
768       $form_state->setRedirect("entity.$entity_type_id.content_translation_delete", [
769         $entity_type_id => $entity->id(),
770         'language' => $form_object->getFormLangcode($form_state),
771       ]);
772     }
773   }
774
775   /**
776    * Returns the title to be used for the entity form page.
777    *
778    * @param \Drupal\Core\Entity\EntityInterface $entity
779    *   The entity whose form is being altered.
780    *
781    * @return string|null
782    *   The label of the entity, or NULL if there is no label defined.
783    */
784   protected function entityFormTitle(EntityInterface $entity) {
785     return $entity->label();
786   }
787
788   /**
789    * Default value callback for the owner base field definition.
790    *
791    * @return int
792    *   The user ID.
793    */
794   public static function getDefaultOwnerId() {
795     return \Drupal::currentUser()->id();
796   }
797
798 }