ContentTranslationHandler.php 27.9 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\content_translation\ContentTranslationHandler.
6 7
 */

8
namespace Drupal\content_translation;
9

10
use Drupal\Core\Access\AccessResult;
11
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
12
use Drupal\Core\Entity\EntityHandlerInterface;
13
use Drupal\Core\Entity\EntityInterface;
14
use Drupal\Core\Entity\EntityManagerInterface;
15
use Drupal\Core\Entity\EntityTypeInterface;
16
use Drupal\Core\Field\BaseFieldDefinition;
17
use Drupal\Core\Form\FormStateInterface;
18
use Drupal\Core\Language\LanguageInterface;
19
use Drupal\Core\Language\LanguageManagerInterface;
20
use Drupal\Core\Render\Element;
21
use Drupal\Core\Session\AccountInterface;
22
use Drupal\user\Entity\User;
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
  use DependencySerializationTrait;
32 33 34 35 36 37

  /**
   * The type of the entity being translated.
   *
   * @var string
   */
38
  protected $entityTypeId;
39 40

  /**
41
   * Information about the entity type.
42
   *
43
   * @var \Drupal\Core\Entity\EntityTypeInterface
44
   */
45
  protected $entityType;
46

47 48 49 50 51 52 53 54
  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
55 56 57
   * The content translation manager.
   *
   * @var \Drupal\content_translation\ContentTranslationManagerInterface
58
   */
59
  protected $manager;
60

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The array of installed field storage definitions for the entity type, keyed
   * by field name.
   *
   * @var \Drupal\Core\Field\FieldStorageDefinitionInterface[]
   */
  protected $fieldStorageDefinitions;

76
  /**
77
   * Initializes an instance of the content translation controller.
78
   *
79
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
80
   *   The info array of the given entity type.
81 82
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
83 84
   * @param \Drupal\content_translation\ContentTranslationManagerInterface $manager
   *   The content translation manager service.
85 86 87 88
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
89
   */
90
  public function __construct(EntityTypeInterface $entity_type, LanguageManagerInterface $language_manager, ContentTranslationManagerInterface $manager, EntityManagerInterface $entity_manager, AccountInterface $current_user) {
91 92
    $this->entityTypeId = $entity_type->id();
    $this->entityType = $entity_type;
93
    $this->languageManager = $language_manager;
94
    $this->manager = $manager;
95 96
    $this->currentUser = $current_user;
    $this->fieldStorageDefinitions = $entity_manager->getLastInstalledFieldStorageDefinitions($this->entityTypeId);
97 98 99 100 101 102 103 104 105
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static(
      $entity_type,
      $container->get('language_manager'),
106 107 108
      $container->get('content_translation.manager'),
      $container->get('entity.manager'),
      $container->get('current_user')
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFieldDefinitions() {
    $definitions = array();

    $definitions['content_translation_source'] = BaseFieldDefinition::create('language')
      ->setLabel(t('Translation source'))
      ->setDescription(t('The source language from which this translation was created.'))
      ->setDefaultValue(LanguageInterface::LANGCODE_NOT_SPECIFIED)
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);

    $definitions['content_translation_outdated'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Translation outdated'))
      ->setDescription(t('A boolean indicating whether this translation needs to be updated.'))
      ->setDefaultValue(FALSE)
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);

    if (!$this->hasAuthor()) {
      $definitions['content_translation_uid'] = BaseFieldDefinition::create('entity_reference')
        ->setLabel(t('Translation author'))
        ->setDescription(t('The author of this translation.'))
        ->setSetting('target_type', 'user')
        ->setSetting('handler', 'default')
        ->setRevisionable(TRUE)
139
        ->setDefaultValueCallback(get_class($this) . '::getDefaultOwnerId')
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
        ->setTranslatable(TRUE);
    }

    if (!$this->hasPublishedStatus()) {
      $definitions['content_translation_status'] = BaseFieldDefinition::create('boolean')
        ->setLabel(t('Translation status'))
        ->setDescription(t('A boolean indicating whether the translation is visible to non-translators.'))
        ->setDefaultValue(TRUE)
        ->setRevisionable(TRUE)
        ->setTranslatable(TRUE);
    }

    if (!$this->hasCreatedTime()) {
      $definitions['content_translation_created'] = BaseFieldDefinition::create('created')
        ->setLabel(t('Translation created time'))
        ->setDescription(t('The Unix timestamp when the translation was created.'))
        ->setRevisionable(TRUE)
        ->setTranslatable(TRUE);
    }

    if (!$this->hasChangedTime()) {
      $definitions['content_translation_changed'] = BaseFieldDefinition::create('changed')
        ->setLabel(t('Translation changed time'))
        ->setDescription(t('The Unix timestamp when the translation was most recently saved.'))
        ->setRevisionable(TRUE)
        ->setTranslatable(TRUE);
    }

    return $definitions;
  }

  /**
   * Checks whether the entity type supports author natively.
   *
   * @return bool
   *   TRUE if metadata is natively supported, FALSE otherwise.
   */
  protected function hasAuthor() {
178 179 180 181 182
    // Check for field named uid, but only in case the entity implements the
    // EntityOwnerInterface. This helps to exclude cases, where the uid is
    // defined as field name, but is not meant to be an owner field e.g. the
    // User entity.
    return $this->entityType->isSubclassOf('\Drupal\user\EntityOwnerInterface') && $this->checkFieldStorageDefinitionTranslatability('uid');
183 184 185 186 187 188 189 190 191
  }

  /**
   * Checks whether the entity type supports published status natively.
   *
   * @return bool
   *   TRUE if metadata is natively supported, FALSE otherwise.
   */
  protected function hasPublishedStatus() {
192
    return $this->checkFieldStorageDefinitionTranslatability('status');
193 194 195 196 197 198 199 200 201
  }

  /**
   * Checks whether the entity type supports modification time natively.
   *
   * @return bool
   *   TRUE if metadata is natively supported, FALSE otherwise.
   */
  protected function hasChangedTime() {
202
    return $this->entityType->isSubclassOf('Drupal\Core\Entity\EntityChangedInterface') && $this->checkFieldStorageDefinitionTranslatability('changed');
203 204 205 206 207 208 209 210 211
  }

  /**
   * Checks whether the entity type supports creation time natively.
   *
   * @return bool
   *   TRUE if metadata is natively supported, FALSE otherwise.
   */
  protected function hasCreatedTime() {
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    return $this->checkFieldStorageDefinitionTranslatability('created');
  }

  /**
   * Checks the field storage definition for translatability support.
   *
   * Checks whether the given field is defined in the field storage definitions
   * and if its definition specifies it as translatable.
   *
   * @param string $field_name
   *   The name of the field.
   *
   * @return bool
   *   TRUE if translatable field storage definition exists, FALSE otherwise.
   */
  protected function checkFieldStorageDefinitionTranslatability($field_name) {
    return array_key_exists($field_name, $this->fieldStorageDefinitions) && $this->fieldStorageDefinitions[$field_name]->isTranslatable();
229 230 231
  }

  /**
232
   * {@inheritdoc}
233 234
   */
  public function retranslate(EntityInterface $entity, $langcode = NULL) {
235
    $updated_langcode = !empty($langcode) ? $langcode : $entity->language()->getId();
236 237 238
    foreach ($entity->getTranslationLanguages() as $langcode => $language) {
      $this->manager->getTranslationMetadata($entity->getTranslation($langcode))
        ->setOutdated($langcode != $updated_langcode);
239 240 241 242
    }
  }

  /**
243
   * {@inheritdoc}
244
   */
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 250 251
    $translate_permission = TRUE;
    // If no permission granularity is defined this entity type does not need an
    // explicit translate permission.
252 253
    if (!$this->currentUser->hasPermission('translate any entity') && $permission_granularity = $entity_type->getPermissionGranularity()) {
      $translate_permission = $this->currentUser->hasPermission($permission_granularity == 'bundle' ? "translate {$entity->bundle()} {$entity->getEntityTypeId()}" : "translate {$entity->getEntityTypeId()}");
254
    }
255
    return AccessResult::allowedIf($translate_permission && $this->currentUser->hasPermission("$op content translations"))->cachePerPermissions();
256 257 258
  }

  /**
259
   * {@inheritdoc}
260
   */
261
  public function getSourceLangcode(FormStateInterface $form_state) {
262
    if ($source = $form_state->get(['content_translation', 'source'])) {
263
      return $source->getId();
264 265
    }
    return FALSE;
266 267 268
  }

  /**
269
   * {@inheritdoc}
270
   */
271
  public function entityFormAlter(array &$form, FormStateInterface $form_state, EntityInterface $entity) {
272 273
    $form_object = $form_state->getFormObject();
    $form_langcode = $form_object->getFormLangcode($form_state);
274
    $entity_langcode = $entity->getUntranslated()->language()->getId();
275 276 277 278 279 280 281 282
    $source_langcode = $this->getSourceLangcode($form_state);

    $new_translation = !empty($source_langcode);
    $translations = $entity->getTranslationLanguages();
    if ($new_translation) {
      // Make sure a new translation does not appear as existing yet.
      unset($translations[$form_langcode]);
    }
283
    $is_translation = !$form_object->isDefaultFormLangcode($form_state);
284 285 286 287
    $has_translations = count($translations) > 1;

    // Adjust page title to specify the current language being edited, if we
    // have at least one translation.
288
    $languages = $this->languageManager->getLanguages();
289 290 291
    if (isset($languages[$form_langcode]) && ($has_translations || $new_translation)) {
      $title = $this->entityFormTitle($entity);
      // When editing the original values display just the entity label.
292
      if ($form_langcode != $entity_langcode) {
293 294
        $t_args = array('%language' => $languages[$form_langcode]->getName(), '%title' => $entity->label(), '@title' => $title);
        $title = empty($source_langcode) ? t('@title [%language translation]', $t_args) : t('Create %language translation of %title', $t_args);
295
      }
296
      $form['#title'] = $title;
297 298 299 300 301 302
    }

    // Display source language selector only if we are creating a new
    // translation and there are at least two translations available.
    if ($has_translations && $new_translation) {
      $form['source_langcode'] = array(
303
        '#type' => 'details',
304
        '#title' => t('Source language: @language', array('@language' => $languages[$source_langcode]->getName())),
305 306 307 308
        '#tree' => TRUE,
        '#weight' => -100,
        '#multilingual' => TRUE,
        'source' => array(
309 310
          '#title' => t('Select source language'),
          '#title_display' => 'invisible',
311 312 313 314 315 316 317 318 319 320
          '#type' => 'select',
          '#default_value' => $source_langcode,
          '#options' => array(),
        ),
        'submit' => array(
          '#type' => 'submit',
          '#value' => t('Change'),
          '#submit' => array(array($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();
324 325 326 327
        }
      }
    }

328
    // Locate the language widget.
329 330 331
    $langcode_key = $this->entityType->getKey('langcode');
    if (isset($form[$langcode_key])) {
      $language_widget = &$form[$langcode_key];
332 333 334 335 336 337 338 339 340 341
    }

    // If we are editing the source entity, limit the list of languages so that
    // it is not possible to switch to a language for which a translation
    // already exists. Note that this will only work if the widget is structured
    // like \Drupal\Core\Field\Plugin\Field\FieldWidget\LanguageSelectWidget.
    if (isset($language_widget['widget'][0]['value']) && !$is_translation && $has_translations) {
      $language_select = &$language_widget['widget'][0]['value'];
      if ($language_select['#type'] == 'language_select') {
        $options = array();
342
        foreach ($this->languageManager->getLanguages() as $language) {
343 344 345 346 347
          // Show the current language, and the languages for which no
          // translation already exists.
          if (empty($translations[$language->getId()]) || $language->getId() == $entity_langcode) {
            $options[$language->getId()] = $language->getName();
          }
348
        }
349
        $language_select['#options'] = $options;
350 351 352
      }
    }
    if ($is_translation) {
353 354
      if (isset($language_widget)) {
        $language_widget['widget']['#access'] = FALSE;
355 356 357 358 359 360 361 362 363 364 365
      }

      // Replace the delete button with the delete translation one.
      if (!$new_translation) {
        $weight = 100;
        foreach (array('delete', 'submit') as $key) {
          if (isset($form['actions'][$key]['weight'])) {
            $weight = $form['actions'][$key]['weight'];
            break;
          }
        }
366
        $access = $this->getTranslationAccess($entity, 'delete')->isAllowed() || ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form'));
367 368 369 370 371
        $form['actions']['delete_translation'] = array(
          '#type' => 'submit',
          '#value' => t('Delete translation'),
          '#weight' => $weight,
          '#submit' => array(array($this, 'entityFormDeleteTranslation')),
372
          '#access' => $access,
373 374 375 376 377 378 379 380 381 382
        );
      }

      // Always remove the delete button on translation forms.
      unset($form['actions']['delete']);
    }

    // We need to display the translation tab only when there is at least one
    // translation available or a new one is about to be created.
    if ($new_translation || $has_translations) {
383
      $form['content_translation'] = array(
384
        '#type' => 'details',
385 386 387
        '#title' => t('Translation'),
        '#tree' => TRUE,
        '#weight' => 10,
388
        '#access' => $this->getTranslationAccess($entity, $source_langcode ? 'create' : 'update')->isAllowed(),
389 390 391
        '#multilingual' => TRUE,
      );

392
      // A new translation is enabled by default.
393 394
      $metadata = $this->manager->getTranslationMetadata($entity);
      $status = $new_translation || $metadata->isPublished();
395 396 397 398
      // If there is only one published translation we cannot unpublish it,
      // since there would be nothing left to display.
      $enabled = TRUE;
      if ($status) {
399 400 401 402
        $published = 0;
        foreach ($entity->getTranslationLanguages() as $langcode => $language) {
          $published += $this->manager->getTranslationMetadata($entity->getTranslation($langcode))
            ->isPublished();
403 404 405 406 407 408 409
        }
        $enabled = $published > 1;
      }
      $description = $enabled ?
        t('An unpublished translation will not be visible without translation permissions.') :
        t('Only this translation is published. You must publish at least one more translation to unpublish this one.');

410
      $form['content_translation']['status'] = array(
411 412 413 414 415 416 417
        '#type' => 'checkbox',
        '#title' => t('This translation is published'),
        '#default_value' => $status,
        '#description' => $description,
        '#disabled' => !$enabled,
      );

418
      $translate = !$new_translation && $metadata->isOutdated();
419
      if (!$translate) {
420
        $form['content_translation']['retranslate'] = array(
421 422 423 424 425 426 427
          '#type' => 'checkbox',
          '#title' => t('Flag other translations as outdated'),
          '#default_value' => FALSE,
          '#description' => t('If you made a significant change, which means the other translations should be updated, you can flag all translations of this content as outdated. This will not change any other property of them, like whether they are published or not.'),
        );
      }
      else {
428
        $form['content_translation']['outdated'] = array(
429 430 431 432 433
          '#type' => 'checkbox',
          '#title' => t('This translation needs to be updated'),
          '#default_value' => $translate,
          '#description' => t('When this option is checked, this translation needs to be updated. Uncheck when the translation is up to date again.'),
        );
434
        $form['content_translation']['#open'] = TRUE;
435 436
      }

437
      // Default to the anonymous user.
438
      $uid = 0;
439
      if ($new_translation) {
440
        $uid = $this->currentUser->id();
441
      }
442
      elseif (($account = $metadata->getAuthor()) && $account->id()) {
443
        $uid = $account->id();
444
      }
445 446
      $form['content_translation']['uid'] = array(
        '#type' => 'entity_autocomplete',
447
        '#title' => t('Authored by'),
448 449 450 451
        '#target_type' => 'user',
        '#default_value' => User::load($uid),
        // Validation is done by static::entityFormValidate().
        '#validate_reference' => FALSE,
452
        '#maxlength' => 60,
453
        '#description' => t('Leave blank for %anonymous.', array('%anonymous' => \Drupal::config('user.settings')->get('anonymous'))),
454 455
      );

456
      $date = $new_translation ? REQUEST_TIME : $metadata->getCreatedTime();
457
      $form['content_translation']['created'] = array(
458 459 460
        '#type' => 'textfield',
        '#title' => t('Authored on'),
        '#maxlength' => 25,
461 462
        '#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.', array('%time' => format_date(REQUEST_TIME, 'custom', 'Y-m-d H:i:s O'), '%timezone' => format_date(REQUEST_TIME, 'custom', 'O'))),
        '#default_value' => $new_translation || !$date ? '' : format_date($date, 'custom', 'Y-m-d H:i:s O'),
463 464
      );

465 466
      if (isset($language_widget)) {
        $language_widget['#multilingual'] = TRUE;
467 468 469 470 471 472 473 474
      }

      $form['#process'][] = array($this, 'entityFormSharedElements');
    }

    // Process the submitted values before they are stored.
    $form['#entity_builders'][] = array($this, 'entityFormEntityBuild');

475
    // Handle entity validation.
476
    $form['#validate'][] = array($this, 'entityFormValidate');
477

478 479 480 481
    // Handle entity deletion.
    if (isset($form['actions']['delete'])) {
      $form['actions']['delete']['#submit'][] = array($this, 'entityFormDelete');
    }
482 483 484 485 486 487 488

    // Handle entity form submission before the entity has been saved.
    foreach (Element::children($form['actions']) as $action) {
      if (isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] == 'submit') {
        array_unshift($form['actions'][$action]['#submit'], [$this, 'entityFormSubmit']);
      }
    }
489 490 491
  }

  /**
492
   * Process callback: determines which elements get clue in the form.
493
   *
494
   * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
495
   */
496
  public function entityFormSharedElements($element, FormStateInterface $form_state, $form) {
497 498 499 500 501
    static $ignored_types;

    // @todo Find a more reliable way to determine if a form element concerns a
    //   multilingual value.
    if (!isset($ignored_types)) {
502
      $ignored_types = array_flip(array('actions', 'value', 'hidden', 'vertical_tabs', 'token', 'details'));
503 504
    }

505
    foreach (Element::children($element) as $key) {
506
      if (!isset($element[$key]['#type'])) {
507
        $this->entityFormSharedElements($element[$key], $form_state, $form);
508 509 510 511 512 513 514 515
      }
      else {
        // Ignore non-widget form elements.
        if (isset($ignored_types[$element[$key]['#type']])) {
          continue;
        }
        // Elements are considered to be non multilingual by default.
        if (empty($element[$key]['#multilingual'])) {
516 517 518
          // If we are displaying a multilingual entity form we need to provide
          // translatability clues, otherwise the shared form elements should be
          // hidden.
519
          if (!$form_state->get(['content_translation', 'translation_form'])) {
520 521 522 523 524
            $this->addTranslatabilityClue($element[$key]);
          }
          else {
            $element[$key]['#access'] = FALSE;
          }
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
        }
      }
    }

    return $element;
  }

  /**
   * Adds a clue about the form element translatability.
   *
   * If the given element does not have a #title attribute, the function is
   * recursively applied to child elements.
   *
   * @param array $element
   *   A form element array.
   */
  protected function addTranslatabilityClue(&$element) {
    static $suffix, $fapi_title_elements;

    // Elements which can have a #title attribute according to FAPI Reference.
    if (!isset($suffix)) {
      $suffix = ' <span class="translation-entity-all-languages">(' . t('all languages') . ')</span>';
547
      $fapi_title_elements = array_flip(array('checkbox', 'checkboxes', 'date', 'details', 'fieldset', 'file', 'item', 'password', 'password_confirm', 'radio', 'radios', 'select', 'text_format', 'textarea', 'textfield', 'weight'));
548 549 550 551 552 553 554 555 556 557
    }

    // Update #title attribute for all elements that are allowed to have a
    // #title attribute according to the Form API Reference. The reason for this
    // check is because some elements have a #title attribute even though it is
    // not rendered, e.g. field containers.
    if (isset($element['#type']) && isset($fapi_title_elements[$element['#type']]) && isset($element['#title'])) {
      $element['#title'] .= $suffix;
    }
    // If the current element does not have a (valid) title, try child elements.
558
    elseif ($children = Element::children($element)) {
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
      foreach ($children as $delta) {
        $this->addTranslatabilityClue($element[$delta], $suffix);
      }
    }
    // If there are no children, fall back to the current #title attribute if it
    // exists.
    elseif (isset($element['#title'])) {
      $element['#title'] .= $suffix;
    }
  }

  /**
   * Entity builder method.
   *
   * @param string $entity_type
   *   The type of the entity.
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity whose form is being built.
   *
578
   * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
579
   */
580
  public function entityFormEntityBuild($entity_type, EntityInterface $entity, array $form, FormStateInterface $form_state) {
581 582
    $form_object = $form_state->getFormObject();
    $form_langcode = $form_object->getFormLangcode($form_state);
583
    $values = &$form_state->getValue('content_translation', array());
584

585
    $metadata = $this->manager->getTranslationMetadata($entity);
586
    $metadata->setAuthor(!empty($values['uid']) ? User::load($values['uid']) : User::load(0));
587 588
    $metadata->setPublished(!empty($values['status']));
    $metadata->setCreatedTime(!empty($values['created']) ? strtotime($values['created']) : REQUEST_TIME);
589

590 591
    $source_langcode = $this->getSourceLangcode($form_state);
    if ($source_langcode) {
592
      $metadata->setSource($source_langcode);
593 594
    }

595
    $metadata->setOutdated(!empty($values['outdated']));
596 597 598 599 600
    if (!empty($values['retranslate'])) {
      $this->retranslate($entity, $form_langcode);
    }
  }

601
  /**
602
   * Form validation handler for ContentTranslationHandler::entityFormAlter().
603
   *
604
   * Validates the submitted content translation metadata.
605
   */
606
  function entityFormValidate($form, FormStateInterface $form_state) {
607 608
    if (!$form_state->isValueEmpty('content_translation')) {
      $translation = $form_state->getValue('content_translation');
609
      // Validate the "authored by" field.
610 611
      if (!empty($translation['uid']) && !($account = User::load($translation['uid']))) {
        $form_state->setErrorByName('content_translation][uid', t('The translation authoring username %name does not exist.', array('%name' => $account->getUsername())));
612 613 614
      }
      // Validate the "authored on" field.
      if (!empty($translation['created']) && strtotime($translation['created']) === FALSE) {
615
        $form_state->setErrorByName('content_translation][created', t('You have to specify a valid translation authoring date.'));
616 617 618 619
      }
    }
  }

620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
  /**
   * Form submission handler for ContentTranslationHandler::entityFormAlter().
   *
   * Updates metadata fields, which should be updated only after the validation
   * has run and before the entity is saved.
   */
  function entityFormSubmit($form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
    $form_object = $form_state->getFormObject();
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $form_object->getEntity();

    // ContentEntityForm::submit will update the changed timestamp on submit
    // after the entity has been validated, so that it does not break the
    // EntityChanged constraint validator. The content translation metadata
    // field for the changed timestamp  does not have such a constraint defined
    // at the moment, but it is correct to update it's value in a submission
    // handler as well and have the same logic like in the Form API.
    if ($entity->hasField('content_translation_changed')) {
      $metadata = $this->manager->getTranslationMetadata($entity);
      $metadata->setChangedTime(REQUEST_TIME);
    }
  }

644
  /**
645
   * Form submission handler for ContentTranslationHandler::entityFormAlter().
646 647 648
   *
   * Takes care of the source language change.
   */
649
  public function entityFormSourceChange($form, FormStateInterface $form_state) {
650 651
    $form_object = $form_state->getFormObject();
    $entity = $form_object->getEntity();
652
    $source = $form_state->getValue(array('source_langcode', 'source'));
653

654
    $entity_type_id = $entity->getEntityTypeId();
655
    $form_state->setRedirect("entity.$entity_type_id.content_translation_add", array(
656 657
      $entity_type_id => $entity->id(),
      'source' => $source,
658
      'target' => $form_object->getFormLangcode($form_state),
659
    ));
660
    $languages = $this->languageManager->getLanguages();
661
    drupal_set_message(t('Source language set to: %language', array('%language' => $languages[$source]->getName())));
662 663 664
  }

  /**
665
   * Form submission handler for ContentTranslationHandler::entityFormAlter().
666 667 668
   *
   * Takes care of entity deletion.
   */
669
  function entityFormDelete($form, FormStateInterface $form_state) {
670 671
    $form_object = $form_state->getFormObject()->getEntity();
    $entity = $form_object->getEntity();
672 673 674 675 676 677
    if (count($entity->getTranslationLanguages()) > 1) {
      drupal_set_message(t('This will delete all the translations of %label.', array('%label' => $entity->label())), 'warning');
    }
  }

  /**
678
   * Form submission handler for ContentTranslationHandler::entityFormAlter().
679
   *
680
   * Takes care of content translation deletion.
681
   */
682
  function entityFormDeleteTranslation($form, FormStateInterface $form_state) {
683
    /** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
684
    $form_object = $form_state->getFormObject();
685
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
686
    $entity = $form_object->getEntity();
687
    $entity_type_id = $entity->getEntityTypeId();
688 689 690 691
    if ($entity->access('delete') && $this->entityType->hasLinkTemplate('delete-form')) {
      $form_state->setRedirectUrl($entity->urlInfo('delete-form'));
    }
    else {
692
      $form_state->setRedirect("entity.$entity_type_id.content_translation_delete", [
693 694 695 696
        $entity_type_id => $entity->id(),
        'language' => $form_object->getFormLangcode($form_state),
      ]);
    }
697 698 699 700 701 702 703 704 705 706 707 708
  }

  /**
   * Returns the title to be used for the entity form page.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity whose form is being altered.
   */
  protected function entityFormTitle(EntityInterface $entity) {
    return $entity->label();
  }

709 710 711 712 713 714 715 716 717
  /**
   * Default value callback for the owner base field definition.
   *
   * @return int
   *   The user ID.
   */
  public static function getDefaultOwnerId() {
    return \Drupal::currentUser()->id();
  }
718
}