ContentTranslationHandler.php 18.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\Entity\EntityInterface;
11
use Drupal\Core\Entity\EntityTypeInterface;
12
use Drupal\Core\Language\LanguageInterface;
13
use Drupal\Core\Render\Element;
14 15

/**
16
 * Base class for content translation handlers.
17 18
 *
 * @ingroup entity_api
19
 */
20
class ContentTranslationHandler implements ContentTranslationHandlerInterface {
21 22 23 24 25 26

  /**
   * The type of the entity being translated.
   *
   * @var string
   */
27
  protected $entityTypeId;
28 29

  /**
30
   * Information about the entity type.
31
   *
32
   * @var \Drupal\Core\Entity\EntityTypeInterface
33
   */
34
  protected $entityType;
35 36

  /**
37
   * Initializes an instance of the content translation controller.
38
   *
39
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
40 41
   *   The info array of the given entity type.
   */
42
  public function __construct(EntityTypeInterface $entity_type) {
43 44
    $this->entityTypeId = $entity_type->id();
    $this->entityType = $entity_type;
45 46 47
  }

  /**
48
   * {@inheritdoc}
49 50
   */
  public function retranslate(EntityInterface $entity, $langcode = NULL) {
51
    $updated_langcode = !empty($langcode) ? $langcode : $entity->language()->id;
52 53
    $translations = $entity->getTranslationLanguages();
    foreach ($translations as $langcode => $language) {
54
      $entity->translation[$langcode]['outdated'] = $langcode != $updated_langcode;
55 56 57 58
    }
  }

  /**
59
   * {@inheritdoc}
60
   */
61 62 63
  public function getTranslationAccess(EntityInterface $entity, $op) {
    // @todo Move this logic into a translation access controller checking also
    //   the translation language and the given account.
64
    $entity_type = $entity->getEntityType();
65 66 67
    $translate_permission = TRUE;
    // If no permission granularity is defined this entity type does not need an
    // explicit translate permission.
68 69 70
    $current_user = \Drupal::currentUser();
    if (!$current_user->hasPermission('translate any entity') && $permission_granularity = $entity_type->getPermissionGranularity()) {
      $translate_permission = $current_user->hasPermission($permission_granularity == 'bundle' ? "translate {$entity->bundle()} {$entity->getEntityTypeId()}" : "translate {$entity->getEntityTypeId()}");
71
    }
72
    return $translate_permission && $current_user->hasPermission("$op content translations");
73 74 75
  }

  /**
76
   * {@inheritdoc}
77 78
   */
  public function getSourceLangcode(array $form_state) {
79
    return isset($form_state['content_translation']['source']) ? $form_state['content_translation']['source']->id : FALSE;
80 81 82
  }

  /**
83
   * {@inheritdoc}
84 85
   */
  public function entityFormAlter(array &$form, array &$form_state, EntityInterface $entity) {
86
    $form_controller = content_translation_form_controller($form_state);
87
    $form_langcode = $form_controller->getFormLangcode($form_state);
88
    $entity_langcode = $entity->getUntranslated()->language()->id;
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
    $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]);
    }
    $is_translation = !$form_controller->isDefaultFormLangcode($form_state);
    $has_translations = count($translations) > 1;

    // Adjust page title to specify the current language being edited, if we
    // have at least one translation.
    $languages = language_list();
    if (isset($languages[$form_langcode]) && ($has_translations || $new_translation)) {
      $title = $this->entityFormTitle($entity);
      // When editing the original values display just the entity label.
106
      if ($form_langcode != $entity_langcode) {
107 108 109
        $t_args = array('%language' => $languages[$form_langcode]->name, '%title' => $entity->label());
        $title = empty($source_langcode) ? $title . ' [' . t('%language translation', $t_args) . ']' : t('Create %language translation of %title', $t_args);
      }
110
      $form['#title'] = $title;
111 112 113 114 115 116
    }

    // 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(
117
        '#type' => 'details',
118 119 120 121 122
        '#title' => t('Source language: @language', array('@language' => $languages[$source_langcode]->name)),
        '#tree' => TRUE,
        '#weight' => -100,
        '#multilingual' => TRUE,
        'source' => array(
123 124
          '#title' => t('Select source language'),
          '#title_display' => 'invisible',
125 126 127 128 129 130 131 132 133 134
          '#type' => 'select',
          '#default_value' => $source_langcode,
          '#options' => array(),
        ),
        'submit' => array(
          '#type' => 'submit',
          '#value' => t('Change'),
          '#submit' => array(array($this, 'entityFormSourceChange')),
        ),
      );
135
      foreach (language_list(LanguageInterface::STATE_CONFIGURABLE) as $language) {
136 137
        if (isset($translations[$language->id])) {
          $form['source_langcode']['source']['#options'][$language->id] = $language->name;
138 139 140 141 142 143 144 145 146 147
        }
      }
    }

    // Disable languages for existing translations, so it is not possible to
    // switch this node to some language which is already in the translation
    // set.
    $language_widget = isset($form['langcode']) && $form['langcode']['#type'] == 'language_select';
    if ($language_widget && $has_translations) {
      $form['langcode']['#options'] = array();
148
      foreach (language_list(LanguageInterface::STATE_CONFIGURABLE) as $language) {
149 150
        if (empty($translations[$language->id]) || $language->id == $entity_langcode) {
          $form['langcode']['#options'][$language->id] = $language->name;
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        }
      }
    }

    if ($is_translation) {
      if ($language_widget) {
        $form['langcode']['#access'] = FALSE;
      }

      // 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;
          }
        }
        $form['actions']['delete_translation'] = array(
          '#type' => 'submit',
          '#value' => t('Delete translation'),
          '#weight' => $weight,
          '#submit' => array(array($this, 'entityFormDeleteTranslation')),
174
          '#access' => $this->getTranslationAccess($entity, 'delete'),
175 176 177 178 179 180 181 182 183 184
        );
      }

      // 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) {
185
      $form['content_translation'] = array(
186
        '#type' => 'details',
187 188 189
        '#title' => t('Translation'),
        '#tree' => TRUE,
        '#weight' => 10,
190
        '#access' => $this->getTranslationAccess($entity, $source_langcode ? 'create' : 'update'),
191 192 193
        '#multilingual' => TRUE,
      );

194 195 196 197 198 199 200 201 202
      // A new translation is enabled by default.
      $status = $new_translation || $entity->translation[$form_langcode]['status'];
      // If there is only one published translation we cannot unpublish it,
      // since there would be nothing left to display.
      $enabled = TRUE;
      if ($status) {
        // A new translation is not available in the translation metadata, hence
        // it should count as one more.
        $published = $new_translation;
203
        foreach ($entity->translation as $translation) {
204 205 206 207 208 209 210 211
          $published += $translation['status'];
        }
        $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.');

212
      $form['content_translation']['status'] = array(
213 214 215 216 217 218 219 220
        '#type' => 'checkbox',
        '#title' => t('This translation is published'),
        '#default_value' => $status,
        '#description' => $description,
        '#disabled' => !$enabled,
      );

      $translate = !$new_translation && $entity->translation[$form_langcode]['outdated'];
221
      if (!$translate) {
222
        $form['content_translation']['retranslate'] = array(
223 224 225 226 227 228 229
          '#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 {
230
        $form['content_translation']['outdated'] = array(
231 232 233 234 235 236 237
          '#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.'),
        );
      }

238 239 240
      // Default to the anonymous user.
      $name = '';
      if ($new_translation) {
241
        $name = \Drupal::currentUser()->getUsername();
242 243 244 245
      }
      elseif ($entity->translation[$form_langcode]['uid']) {
        $name = user_load($entity->translation[$form_langcode]['uid'])->getUsername();
      }
246
      $form['content_translation']['name'] = array(
247 248 249
        '#type' => 'textfield',
        '#title' => t('Authored by'),
        '#maxlength' => 60,
250
        '#autocomplete_route_name' => 'user.autocomplete',
251
        '#default_value' => $name,
252
        '#description' => t('Leave blank for %anonymous.', array('%anonymous' => \Drupal::config('user.settings')->get('anonymous'))),
253 254 255
      );

      $date = $new_translation ? REQUEST_TIME : $entity->translation[$form_langcode]['created'];
256
      $form['content_translation']['created'] = array(
257 258 259 260 261 262 263
        '#type' => 'textfield',
        '#title' => t('Authored on'),
        '#maxlength' => 25,
        '#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($date, 'custom', 'Y-m-d H:i:s O'), '%timezone' => format_date($date, 'custom', 'O'))),
        '#default_value' => $new_translation ? '' : format_date($date, 'custom', 'Y-m-d H:i:s O'),
      );

264
      if ($language_widget) {
265
        $form['langcode']['#multilingual'] = TRUE;
266 267 268 269 270 271 272 273
      }

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

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

274 275 276 277 278
    // Handle entity validation.
    if (isset($form['actions']['submit'])) {
      $form['actions']['submit']['#validate'][] = array($this, 'entityFormValidate');
    }

279 280 281 282 283 284 285
    // Handle entity deletion.
    if (isset($form['actions']['delete'])) {
      $form['actions']['delete']['#submit'][] = array($this, 'entityFormDelete');
    }
  }

  /**
286
   * Process callback: determines which elements get clue in the form.
287
   *
288
   * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
289
   */
290
  public function entityFormSharedElements($element, $form_state, $form) {
291 292 293 294 295
    static $ignored_types;

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

299
    foreach (Element::children($element) as $key) {
300
      if (!isset($element[$key]['#type'])) {
301
        $this->entityFormSharedElements($element[$key], $form_state, $form);
302 303 304 305 306 307 308 309
      }
      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'])) {
310 311 312
          // If we are displaying a multilingual entity form we need to provide
          // translatability clues, otherwise the shared form elements should be
          // hidden.
313
          if (empty($form_state['content_translation']['translation_form'])) {
314 315 316 317 318
            $this->addTranslatabilityClue($element[$key]);
          }
          else {
            $element[$key]['#access'] = FALSE;
          }
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
        }
      }
    }

    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>';
341
      $fapi_title_elements = array_flip(array('checkbox', 'checkboxes', 'date', 'details', 'fieldset', 'file', 'item', 'password', 'password_confirm', 'radio', 'radios', 'select', 'text_format', 'textarea', 'textfield', 'weight'));
342 343 344 345 346 347 348 349 350 351
    }

    // 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.
352
    elseif ($children = Element::children($element)) {
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
      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.
   *
372
   * @see \Drupal\content_translation\ContentTranslationHandler::entityFormAlter()
373 374
   */
  public function entityFormEntityBuild($entity_type, EntityInterface $entity, array $form, array &$form_state) {
375
    $form_controller = content_translation_form_controller($form_state);
376 377
    $form_langcode = $form_controller->getFormLangcode($form_state);

378 379
    if (!isset($entity->translation[$form_langcode])) {
      $entity->translation[$form_langcode] = array();
380
    }
381
    $values = isset($form_state['values']['content_translation']) ? $form_state['values']['content_translation'] : array();
382
    $translation = &$entity->translation[$form_langcode];
383

384 385
    // @todo Use the entity setter when all entities support multilingual
    // properties.
386
    $translation['uid'] = !empty($values['name']) && ($account = user_load_by_name($values['name'])) ? $account->id() : 0;
387 388 389
    $translation['status'] = !empty($values['status']);
    $translation['created'] = !empty($values['created']) ? strtotime($values['created']) : REQUEST_TIME;
    $translation['changed'] = REQUEST_TIME;
390

391 392 393 394 395 396
    $source_langcode = $this->getSourceLangcode($form_state);
    if ($source_langcode) {
      $translation['source'] = $source_langcode;
    }

    $translation['outdated'] = !empty($values['outdated']);
397 398 399
    if (!empty($values['retranslate'])) {
      $this->retranslate($entity, $form_langcode);
    }
400 401

    // Set contextual information that can be reused during the storage phase.
402 403
    // @todo Remove this once translation metadata are converted to regular
    //   fields.
404
    $attributes = \Drupal::request()->attributes;
405
    $attributes->set('source_langcode', $source_langcode);
406 407
  }

408
  /**
409
   * Form validation handler for ContentTranslationHandler::entityFormAlter().
410
   *
411
   * Validates the submitted content translation metadata.
412 413
   */
  function entityFormValidate($form, &$form_state) {
414 415
    if (!empty($form_state['values']['content_translation'])) {
      $translation = $form_state['values']['content_translation'];
416 417
      // Validate the "authored by" field.
      if (!empty($translation['name']) && !($account = user_load_by_name($translation['name']))) {
418
        form_set_error('content_translation][name', $form_state, t('The translation authoring username %name does not exist.', array('%name' => $translation['name'])));
419 420 421
      }
      // Validate the "authored on" field.
      if (!empty($translation['created']) && strtotime($translation['created']) === FALSE) {
422
        form_set_error('content_translation][created', $form_state, t('You have to specify a valid translation authoring date.'));
423 424 425 426
      }
    }
  }

427
  /**
428
   * Form submission handler for ContentTranslationHandler::entityFormAlter().
429 430 431 432
   *
   * Takes care of the source language change.
   */
  public function entityFormSourceChange($form, &$form_state) {
433
    $form_controller = content_translation_form_controller($form_state);
434
    $entity = $form_controller->getEntity();
435
    $source = $form_state['values']['source_langcode']['source'];
436

437 438
    $path = $entity->getSystemPath('drupal:content-translation-overview');
    $form_state['redirect'] = $path . '/add/' . $source . '/' . $form_controller->getFormLangcode($form_state);
439 440 441 442 443
    $languages = language_list();
    drupal_set_message(t('Source language set to: %language', array('%language' => $languages[$source]->name)));
  }

  /**
444
   * Form submission handler for ContentTranslationHandler::entityFormAlter().
445 446 447 448
   *
   * Takes care of entity deletion.
   */
  function entityFormDelete($form, &$form_state) {
449
    $form_controller = content_translation_form_controller($form_state);
450
    $entity = $form_controller->getEntity();
451 452 453 454 455 456
    if (count($entity->getTranslationLanguages()) > 1) {
      drupal_set_message(t('This will delete all the translations of %label.', array('%label' => $entity->label())), 'warning');
    }
  }

  /**
457
   * Form submission handler for ContentTranslationHandler::entityFormAlter().
458
   *
459
   * Takes care of content translation deletion.
460 461
   */
  function entityFormDeleteTranslation($form, &$form_state) {
462
    $form_controller = content_translation_form_controller($form_state);
463
    $entity = $form_controller->getEntity();
464
    $path = $entity->getSystemPath('drupal:content-translation-overview');
465
    $form_langcode = $form_controller->getFormLangcode($form_state);
466
    $form_state['redirect'] = $path . '/delete/' . $form_langcode;
467 468 469 470 471 472 473 474 475 476 477 478 479
  }

  /**
   * 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();
  }

}