content_translation.module 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. <?php
  2. /**
  3. * @file
  4. * Allows entities to be translated into different languages.
  5. */
  6. use Drupal\content_translation\BundleTranslationSettingsInterface;
  7. use Drupal\content_translation\ContentTranslationManager;
  8. use Drupal\Core\Access\AccessResult;
  9. use Drupal\Core\Entity\ContentEntityFormInterface;
  10. use Drupal\Core\Entity\ContentEntityInterface;
  11. use Drupal\Core\Entity\EntityInterface;
  12. use Drupal\Core\Entity\EntityTypeInterface;
  13. use Drupal\Core\Form\FormStateInterface;
  14. use Drupal\Core\Language\LanguageInterface;
  15. use Drupal\Core\Routing\RouteMatchInterface;
  16. use Drupal\Core\StringTranslation\TranslatableMarkup;
  17. /**
  18. * Implements hook_help().
  19. */
  20. function content_translation_help($route_name, RouteMatchInterface $route_match) {
  21. switch ($route_name) {
  22. case 'help.page.content_translation':
  23. $output = '';
  24. $output .= '<h3>' . t('About') . '</h3>';
  25. $output .= '<p>' . t('The Content Translation module allows you to translate content, comments, custom blocks, taxonomy terms, users and other <a href=":field_help" title="Field module help, with background on content entities">content entities</a>. Together with the modules <a href=":language">Language</a>, <a href=":config-trans">Configuration Translation</a>, and <a href=":locale">Interface Translation</a>, it allows you to build multilingual websites. For more information, see the <a href=":translation-entity">online documentation for the Content Translation module</a>.', [':locale' => (\Drupal::moduleHandler()->moduleExists('locale')) ? \Drupal::url('help.page', ['name' => 'locale']) : '#', ':config-trans' => (\Drupal::moduleHandler()->moduleExists('config_translation')) ? \Drupal::url('help.page', ['name' => 'config_translation']) : '#', ':language' => \Drupal::url('help.page', ['name' => 'language']), ':translation-entity' => 'https://www.drupal.org/documentation/modules/translation', ':field_help' => \Drupal::url('help.page', ['name' => 'field'])]) . '</p>';
  26. $output .= '<h3>' . t('Uses') . '</h3>';
  27. $output .= '<dl>';
  28. $output .= '<dt>' . t('Enabling translation') . '</dt>';
  29. $output .= '<dd>' . t('In order to translate content, the website must have at least two <a href=":url">languages</a>. When that is the case, you can enable translation for the desired content entities on the <a href=":translation-entity">Content language</a> page. When enabling translation you can choose the default language for content and decide whether to show the language selection field on the content editing forms.', [':url' => \Drupal::url('entity.configurable_language.collection'), ':translation-entity' => \Drupal::url('language.content_settings_page'), ':language-help' => \Drupal::url('help.page', ['name' => 'language'])]) . '</dd>';
  30. $output .= '<dt>' . t('Enabling field translation') . '</dt>';
  31. $output .= '<dd>' . t('You can define which fields of a content entity can be translated. For example, you might want to translate the title and body field while leaving the image field untranslated. If you exclude a field from being translated, it will still show up in the content editing form, but any changes made to that field will be applied to <em>all</em> translations of that content.') . '</dd>';
  32. $output .= '<dt>' . t('Translating content') . '</dt>';
  33. $output .= '<dd>' . t('If translation is enabled you can translate a content entity via the Translate tab (or Translate link). The Translations page of a content entity gives an overview of the translation status for the current content and lets you add, edit, and delete its translations. This process is similar for every translatable content entity on your site.') . '</dd>';
  34. $output .= '<dt>' . t('Changing the source language for a translation') . '</dt>';
  35. $output .= '<dd>' . t('When you add a new translation, the original text you are translating is displayed in the edit form as the <em>source</em>. If at least one translation of the original content already exists when you add a new translation, you can choose either the original content (default) or one of the other translations as the source, using the select list in the Source language section. After saving the translation, the chosen source language is then listed on the Translate tab of the content.') . '</dd>';
  36. $output .= '<dt>' . t('Setting status of translations') . '</dt>';
  37. $output .= '<dd>' . t('If you edit a translation in one language you may want to set the status of the other translations as <em>out-of-date</em>. You can set this status by selecting the <em>Flag other translations as outdated</em> checkbox in the Translation section of the content editing form. The status will be visible on the Translations page.') . '</dd>';
  38. $output .= '</dl>';
  39. return $output;
  40. case 'language.content_settings_page':
  41. $output = '';
  42. if (!\Drupal::languageManager()->isMultilingual()) {
  43. $output .= '<p>' . t('Before you can translate content, there must be at least two languages added on the <a href=":url">languages administration</a> page.', [':url' => \Drupal::url('entity.configurable_language.collection')]) . '</p>';
  44. }
  45. return $output;
  46. }
  47. }
  48. /**
  49. * Implements hook_module_implements_alter().
  50. */
  51. function content_translation_module_implements_alter(&$implementations, $hook) {
  52. switch ($hook) {
  53. // Move our hook_entity_type_alter() implementation to the end of the list.
  54. case 'entity_type_alter':
  55. $group = $implementations['content_translation'];
  56. unset($implementations['content_translation']);
  57. $implementations['content_translation'] = $group;
  58. break;
  59. // Move our hook_entity_bundle_info_alter() implementation to the top of the
  60. // list, so that any other hook implementation can rely on bundles being
  61. // correctly marked as translatable.
  62. case 'entity_bundle_info_alter':
  63. $group = $implementations['content_translation'];
  64. $implementations = ['content_translation' => $group] + $implementations;
  65. break;
  66. }
  67. }
  68. /**
  69. * Implements hook_language_type_info_alter().
  70. */
  71. function content_translation_language_types_info_alter(array &$language_types) {
  72. // Make content language negotiation configurable by removing the 'locked'
  73. // flag.
  74. $language_types[LanguageInterface::TYPE_CONTENT]['locked'] = FALSE;
  75. unset($language_types[LanguageInterface::TYPE_CONTENT]['fixed']);
  76. }
  77. /**
  78. * Implements hook_entity_type_alter().
  79. *
  80. * The content translation UI relies on the entity info to provide its features.
  81. * See the documentation of hook_entity_type_build() in the Entity API
  82. * documentation for more details on all the entity info keys that may be
  83. * defined.
  84. *
  85. * To make Content Translation automatically support an entity type some keys
  86. * may need to be defined, but none of them is required unless the entity path
  87. * is different from the usual /ENTITY_TYPE/{ENTITY_TYPE} pattern (for instance
  88. * "/taxonomy/term/{taxonomy_term}"). Here are a list of those optional keys:
  89. * - canonical: This key (in the 'links' entity info property) must be defined
  90. * if the entity path is different from /ENTITY_TYPE/{ENTITY_TYPE}
  91. * - translation: This key (in the 'handlers' entity annotation property)
  92. * specifies the translation handler for the entity type. If an entity type is
  93. * translatable and no translation handler is defined,
  94. * \Drupal\content_translation\ContentTranslationHandler will be assumed.
  95. * Every translation handler must implement
  96. * \Drupal\content_translation\ContentTranslationHandlerInterface.
  97. * - content_translation_ui_skip: By default, entity types that do not have a
  98. * canonical link template cannot be enabled for translation. Setting this key
  99. * to TRUE overrides that. When that key is set, the Content Translation
  100. * module will not provide any UI for translating the entity type, and the
  101. * entity type should implement its own UI. For instance, this is useful for
  102. * entity types that are embedded into others for editing (which would not
  103. * need a canonical link, but could still support translation).
  104. * - content_translation_metadata: To implement its business logic the content
  105. * translation UI relies on various metadata items describing the translation
  106. * state. The default implementation is provided by
  107. * \Drupal\content_translation\ContentTranslationMetadataWrapper, which is
  108. * relying on one field for each metadata item (field definitions are provided
  109. * by the translation handler). Entity types needing to customize this
  110. * behavior can specify an alternative class through the
  111. * 'content_translation_metadata' key in the entity type definition. Every
  112. * content translation metadata wrapper needs to implement
  113. * \Drupal\content_translation\ContentTranslationMetadataWrapperInterface.
  114. *
  115. * If the entity paths match the default pattern above and there is no need for
  116. * an entity-specific translation handler, Content Translation will provide
  117. * built-in support for the entity. However enabling translation for each
  118. * translatable bundle will be required.
  119. *
  120. * @see \Drupal\Core\Entity\Annotation\EntityType
  121. */
  122. function content_translation_entity_type_alter(array &$entity_types) {
  123. // Provide defaults for translation info.
  124. /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  125. foreach ($entity_types as $entity_type) {
  126. if ($entity_type->isTranslatable()) {
  127. if (!$entity_type->hasHandlerClass('translation')) {
  128. $entity_type->setHandlerClass('translation', 'Drupal\content_translation\ContentTranslationHandler');
  129. }
  130. if (!$entity_type->get('content_translation_metadata')) {
  131. $entity_type->set('content_translation_metadata', 'Drupal\content_translation\ContentTranslationMetadataWrapper');
  132. }
  133. if (!$entity_type->getFormClass('content_translation_deletion')) {
  134. $entity_type->setFormClass('content_translation_deletion', '\Drupal\content_translation\Form\ContentTranslationDeleteForm');
  135. }
  136. $translation = $entity_type->get('translation');
  137. if (!$translation || !isset($translation['content_translation'])) {
  138. $translation['content_translation'] = [];
  139. }
  140. if ($entity_type->hasLinkTemplate('canonical')) {
  141. // Provide default route names for the translation paths.
  142. if (!$entity_type->hasLinkTemplate('drupal:content-translation-overview')) {
  143. $translations_path = $entity_type->getLinkTemplate('canonical') . '/translations';
  144. $entity_type->setLinkTemplate('drupal:content-translation-overview', $translations_path);
  145. $entity_type->setLinkTemplate('drupal:content-translation-add', $translations_path . '/add/{source}/{target}');
  146. $entity_type->setLinkTemplate('drupal:content-translation-edit', $translations_path . '/edit/{language}');
  147. $entity_type->setLinkTemplate('drupal:content-translation-delete', $translations_path . '/delete/{language}');
  148. }
  149. // @todo Remove this as soon as menu access checks rely on the
  150. // controller. See https://www.drupal.org/node/2155787.
  151. $translation['content_translation'] += [
  152. 'access_callback' => 'content_translation_translate_access',
  153. ];
  154. }
  155. $entity_type->set('translation', $translation);
  156. }
  157. $entity_type->addConstraint('ContentTranslationSynchronizedFields');
  158. }
  159. }
  160. /**
  161. * Implements hook_entity_bundle_info_alter().
  162. */
  163. function content_translation_entity_bundle_info_alter(&$bundles) {
  164. /** @var \Drupal\content_translation\ContentTranslationManagerInterface $content_translation_manager */
  165. $content_translation_manager = \Drupal::service('content_translation.manager');
  166. foreach ($bundles as $entity_type_id => &$info) {
  167. foreach ($info as $bundle => &$bundle_info) {
  168. $bundle_info['translatable'] = $content_translation_manager->isEnabled($entity_type_id, $bundle);
  169. if ($bundle_info['translatable'] && $content_translation_manager instanceof BundleTranslationSettingsInterface) {
  170. $settings = $content_translation_manager->getBundleTranslationSettings($entity_type_id, $bundle);
  171. // If pending revision support is enabled for this bundle, we need to
  172. // hide untranslatable field widgets, otherwise changes in pending
  173. // revisions might be overridden by changes in later default revisions.
  174. $bundle_info['untranslatable_fields.default_translation_affected'] =
  175. !empty($settings['untranslatable_fields_hide']) || ContentTranslationManager::isPendingRevisionSupportEnabled($entity_type_id, $bundle);
  176. }
  177. }
  178. }
  179. }
  180. /**
  181. * Implements hook_entity_base_field_info().
  182. */
  183. function content_translation_entity_base_field_info(EntityTypeInterface $entity_type) {
  184. /** @var \Drupal\content_translation\ContentTranslationManagerInterface $manager */
  185. $manager = \Drupal::service('content_translation.manager');
  186. $entity_type_id = $entity_type->id();
  187. if ($manager->isSupported($entity_type_id)) {
  188. $definitions = $manager->getTranslationHandler($entity_type_id)->getFieldDefinitions();
  189. $installed_storage_definitions = \Drupal::entityManager()->getLastInstalledFieldStorageDefinitions($entity_type_id);
  190. // We return metadata storage fields whenever content translation is enabled
  191. // or it was enabled before, so that we keep translation metadata around
  192. // when translation is disabled.
  193. // @todo Re-evaluate this approach and consider removing field storage
  194. // definitions and the related field data if the entity type has no bundle
  195. // enabled for translation.
  196. // @see https://www.drupal.org/node/2907777
  197. if ($manager->isEnabled($entity_type_id) || array_intersect_key($definitions, $installed_storage_definitions)) {
  198. return $definitions;
  199. }
  200. }
  201. }
  202. /**
  203. * Implements hook_field_info_alter().
  204. *
  205. * Content translation extends the @FieldType annotation with following key:
  206. * - column_groups: contains information about the field type properties
  207. * which columns should be synchronized across different translations and
  208. * which are translatable. This is useful for instance to translate the
  209. * "alt" and "title" textual elements of an image field, while keeping the
  210. * same image on every translation. Each group has the following keys:
  211. * - title: Title of the column group.
  212. * - translatable: (optional) If the column group should be translatable by
  213. * default, defaults to FALSE.
  214. * - columns: (optional) A list of columns of this group. Defaults to the
  215. * name of he group as the single column.
  216. * - require_all_groups_for_translation: (optional) Set to TRUE to enforce
  217. * that making this column group translatable requires all others to be
  218. * translatable too.
  219. *
  220. * @see Drupal\image\Plugin\Field\FieldType\ImageItem
  221. */
  222. function content_translation_field_info_alter(&$info) {
  223. foreach ($info as $key => $settings) {
  224. // Supply the column_groups key if it's not there.
  225. if (empty($settings['column_groups'])) {
  226. $info[$key]['column_groups'] = [];
  227. }
  228. }
  229. }
  230. /**
  231. * Implements hook_entity_operation().
  232. */
  233. function content_translation_entity_operation(EntityInterface $entity) {
  234. $operations = [];
  235. if ($entity->hasLinkTemplate('drupal:content-translation-overview') && content_translation_translate_access($entity)->isAllowed()) {
  236. $operations['translate'] = [
  237. 'title' => t('Translate'),
  238. 'url' => $entity->urlInfo('drupal:content-translation-overview'),
  239. 'weight' => 50,
  240. ];
  241. }
  242. return $operations;
  243. }
  244. /**
  245. * Implements hook_views_data_alter().
  246. */
  247. function content_translation_views_data_alter(array &$data) {
  248. // Add the content translation entity link definition to Views data for entity
  249. // types having translation enabled.
  250. $entity_types = \Drupal::entityManager()->getDefinitions();
  251. /** @var \Drupal\content_translation\ContentTranslationManagerInterface $manager */
  252. $manager = \Drupal::service('content_translation.manager');
  253. foreach ($entity_types as $entity_type_id => $entity_type) {
  254. $base_table = $entity_type->getBaseTable();
  255. if (isset($data[$base_table]) && $entity_type->hasLinkTemplate('drupal:content-translation-overview') && $manager->isEnabled($entity_type_id)) {
  256. $t_arguments = ['@entity_type_label' => $entity_type->getLabel()];
  257. $data[$base_table]['translation_link'] = [
  258. 'field' => [
  259. 'title' => t('Link to translate @entity_type_label', $t_arguments),
  260. 'help' => t('Provide a translation link to the @entity_type_label.', $t_arguments),
  261. 'id' => 'content_translation_link',
  262. ],
  263. ];
  264. }
  265. }
  266. }
  267. /**
  268. * Implements hook_menu_links_discovered_alter().
  269. */
  270. function content_translation_menu_links_discovered_alter(array &$links) {
  271. // Clarify where translation settings are located.
  272. $links['language.content_settings_page']['title'] = new TranslatableMarkup('Content language and translation');
  273. $links['language.content_settings_page']['description'] = new TranslatableMarkup('Configure language and translation support for content.');
  274. }
  275. /**
  276. * Access callback for the translation overview page.
  277. *
  278. * @param \Drupal\Core\Entity\EntityInterface $entity
  279. * The entity whose translation overview should be displayed.
  280. *
  281. * @return \Drupal\Core\Access\AccessResultInterface
  282. * The access result.
  283. */
  284. function content_translation_translate_access(EntityInterface $entity) {
  285. $account = \Drupal::currentUser();
  286. $condition = $entity instanceof ContentEntityInterface && $entity->access('view') &&
  287. !$entity->getUntranslated()->language()->isLocked() && \Drupal::languageManager()->isMultilingual() && $entity->isTranslatable() &&
  288. ($account->hasPermission('create content translations') || $account->hasPermission('update content translations') || $account->hasPermission('delete content translations'));
  289. return AccessResult::allowedIf($condition)->cachePerPermissions()->addCacheableDependency($entity);
  290. }
  291. /**
  292. * Implements hook_form_alter().
  293. */
  294. function content_translation_form_alter(array &$form, FormStateInterface $form_state) {
  295. $form_object = $form_state->getFormObject();
  296. if (!($form_object instanceof ContentEntityFormInterface)) {
  297. return;
  298. }
  299. $entity = $form_object->getEntity();
  300. $op = $form_object->getOperation();
  301. // Let the content translation handler alter the content entity form. This can
  302. // be the 'add' or 'edit' form. It also tries a 'default' form in case neither
  303. // of the aforementioned forms are defined.
  304. if ($entity instanceof ContentEntityInterface && $entity->isTranslatable() && count($entity->getTranslationLanguages()) > 1 && in_array($op, ['edit', 'add', 'default'], TRUE)) {
  305. $controller = \Drupal::entityManager()->getHandler($entity->getEntityTypeId(), 'translation');
  306. $controller->entityFormAlter($form, $form_state, $entity);
  307. // @todo Move the following lines to the code generating the property form
  308. // elements once we have an official #multilingual FAPI key.
  309. $translations = $entity->getTranslationLanguages();
  310. $form_langcode = $form_object->getFormLangcode($form_state);
  311. // Handle fields shared between translations when there is at least one
  312. // translation available or a new one is being created.
  313. if (!$entity->isNew() && (!isset($translations[$form_langcode]) || count($translations) > 1)) {
  314. $langcode_key = $entity->getEntityType()->getKey('langcode');
  315. foreach ($entity->getFieldDefinitions() as $field_name => $definition) {
  316. if (isset($form[$field_name]) && $field_name != $langcode_key) {
  317. $form[$field_name]['#multilingual'] = $definition->isTranslatable();
  318. }
  319. }
  320. }
  321. // The footer region, if defined, may contain multilingual widgets so we
  322. // need to always display it.
  323. if (isset($form['footer'])) {
  324. $form['footer']['#multilingual'] = TRUE;
  325. }
  326. }
  327. }
  328. /**
  329. * Implements hook_language_fallback_candidates_OPERATION_alter().
  330. *
  331. * Performs language fallback for inaccessible translations.
  332. */
  333. function content_translation_language_fallback_candidates_entity_view_alter(&$candidates, $context) {
  334. /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
  335. $entity = $context['data'];
  336. $entity_type_id = $entity->getEntityTypeId();
  337. /** @var \Drupal\content_translation\ContentTranslationManagerInterface $manager */
  338. $manager = \Drupal::service('content_translation.manager');
  339. if ($manager->isEnabled($entity_type_id, $entity->bundle())) {
  340. $entity_type = $entity->getEntityType();
  341. $permission = $entity_type->getPermissionGranularity() == 'bundle' ? $permission = "translate {$entity->bundle()} $entity_type_id" : "translate $entity_type_id";
  342. $current_user = \Drupal::currentuser();
  343. if (!$current_user->hasPermission('translate any entity') && !$current_user->hasPermission($permission)) {
  344. foreach ($entity->getTranslationLanguages() as $langcode => $language) {
  345. $metadata = $manager->getTranslationMetadata($entity->getTranslation($langcode));
  346. if (!$metadata->isPublished()) {
  347. unset($candidates[$langcode]);
  348. }
  349. }
  350. }
  351. }
  352. }
  353. /**
  354. * Implements hook_entity_extra_field_info().
  355. */
  356. function content_translation_entity_extra_field_info() {
  357. $extra = [];
  358. $bundle_info_service = \Drupal::service('entity_type.bundle.info');
  359. foreach (\Drupal::entityManager()->getDefinitions() as $entity_type => $info) {
  360. foreach ($bundle_info_service->getBundleInfo($entity_type) as $bundle => $bundle_info) {
  361. if (\Drupal::service('content_translation.manager')->isEnabled($entity_type, $bundle)) {
  362. $extra[$entity_type][$bundle]['form']['translation'] = [
  363. 'label' => t('Translation'),
  364. 'description' => t('Translation settings'),
  365. 'weight' => 10,
  366. ];
  367. }
  368. }
  369. }
  370. return $extra;
  371. }
  372. /**
  373. * Implements hook_form_FORM_ID_alter() for 'field_config_edit_form'.
  374. */
  375. function content_translation_form_field_config_edit_form_alter(array &$form, FormStateInterface $form_state) {
  376. $field = $form_state->getFormObject()->getEntity();
  377. $bundle_is_translatable = \Drupal::service('content_translation.manager')->isEnabled($field->getTargetEntityTypeId(), $field->getTargetBundle());
  378. $form['translatable'] = [
  379. '#type' => 'checkbox',
  380. '#title' => t('Users may translate this field'),
  381. '#default_value' => $field->isTranslatable(),
  382. '#weight' => -1,
  383. '#disabled' => !$bundle_is_translatable,
  384. '#access' => $field->getFieldStorageDefinition()->isTranslatable(),
  385. ];
  386. // Provide helpful pointers for administrators.
  387. if (\Drupal::currentUser()->hasPermission('administer content translation') && !$bundle_is_translatable) {
  388. $toggle_url = \Drupal::url('language.content_settings_page', [], [
  389. 'query' => \Drupal::destination()->getAsArray(),
  390. ]);
  391. $form['translatable']['#description'] = t('To configure translation for this field, <a href=":language-settings-url">enable language support</a> for this type.', [
  392. ':language-settings-url' => $toggle_url,
  393. ]);
  394. }
  395. if ($field->isTranslatable()) {
  396. module_load_include('inc', 'content_translation', 'content_translation.admin');
  397. $element = content_translation_field_sync_widget($field);
  398. if ($element) {
  399. $form['third_party_settings']['content_translation']['translation_sync'] = $element;
  400. $form['third_party_settings']['content_translation']['translation_sync']['#weight'] = -10;
  401. }
  402. }
  403. }
  404. /**
  405. * Implements hook_entity_presave().
  406. */
  407. function content_translation_entity_presave(EntityInterface $entity) {
  408. if ($entity instanceof ContentEntityInterface && $entity->isTranslatable() && !$entity->isNew()) {
  409. /** @var \Drupal\content_translation\ContentTranslationManagerInterface $manager */
  410. $manager = \Drupal::service('content_translation.manager');
  411. if (!$manager->isEnabled($entity->getEntityTypeId(), $entity->bundle())) {
  412. return;
  413. }
  414. // If we are creating a new translation we need to use the source language
  415. // as original language, since source values are the only ones available to
  416. // compare against.
  417. if (!isset($entity->original)) {
  418. $entity->original = \Drupal::entityTypeManager()
  419. ->getStorage($entity->entityType())->loadUnchanged($entity->id());
  420. }
  421. $langcode = $entity->language()->getId();
  422. $source_langcode = !$entity->original->hasTranslation($langcode) ? $manager->getTranslationMetadata($entity)->getSource() : NULL;
  423. \Drupal::service('content_translation.synchronizer')->synchronizeFields($entity, $langcode, $source_langcode);
  424. }
  425. }
  426. /**
  427. * Implements hook_element_info_alter().
  428. */
  429. function content_translation_element_info_alter(&$type) {
  430. if (isset($type['language_configuration'])) {
  431. $type['language_configuration']['#process'][] = 'content_translation_language_configuration_element_process';
  432. }
  433. }
  434. /**
  435. * Returns a widget to enable content translation per entity bundle.
  436. *
  437. * Backward compatibility layer to support entities not using the language
  438. * configuration form element.
  439. *
  440. * @todo Remove once all core entities have language configuration.
  441. *
  442. * @param string $entity_type
  443. * The type of the entity being configured for translation.
  444. * @param string $bundle
  445. * The bundle of the entity being configured for translation.
  446. * @param array $form
  447. * The configuration form array.
  448. * @param \Drupal\Core\Form\FormStateInterface $form_state
  449. * The current state of the form.
  450. */
  451. function content_translation_enable_widget($entity_type, $bundle, array &$form, FormStateInterface $form_state) {
  452. $key = $form_state->get(['content_translation', 'key']);
  453. $context = $form_state->get(['language', $key]) ?: [];
  454. $context += ['entity_type' => $entity_type, 'bundle' => $bundle];
  455. $form_state->set(['language', $key], $context);
  456. $element = content_translation_language_configuration_element_process(['#name' => $key], $form_state, $form);
  457. unset($element['content_translation']['#element_validate']);
  458. return $element;
  459. }
  460. /**
  461. * Process callback: Expands the language_configuration form element.
  462. *
  463. * @param array $element
  464. * Form API element.
  465. *
  466. * @return
  467. * Processed language configuration element.
  468. */
  469. function content_translation_language_configuration_element_process(array $element, FormStateInterface $form_state, array &$form) {
  470. if (empty($element['#content_translation_skip_alter']) && \Drupal::currentUser()->hasPermission('administer content translation')) {
  471. $key = $element['#name'];
  472. $form_state->set(['content_translation', 'key'], $key);
  473. $context = $form_state->get(['language', $key]);
  474. $element['content_translation'] = [
  475. '#type' => 'checkbox',
  476. '#title' => t('Enable translation'),
  477. // For new bundle, we don't know the bundle name yet,
  478. // default to no translatability.
  479. '#default_value' => $context['bundle'] ? \Drupal::service('content_translation.manager')->isEnabled($context['entity_type'], $context['bundle']) : FALSE,
  480. '#element_validate' => ['content_translation_language_configuration_element_validate'],
  481. ];
  482. $submit_name = isset($form['actions']['save_continue']) ? 'save_continue' : 'submit';
  483. // Only add the submit handler on the submit button if the #submit property
  484. // is already available, otherwise this breaks the form submit function.
  485. if (isset($form['actions'][$submit_name]['#submit'])) {
  486. $form['actions'][$submit_name]['#submit'][] = 'content_translation_language_configuration_element_submit';
  487. }
  488. else {
  489. $form['#submit'][] = 'content_translation_language_configuration_element_submit';
  490. }
  491. }
  492. return $element;
  493. }
  494. /**
  495. * Form validation handler for element added with content_translation_language_configuration_element_process().
  496. *
  497. * Checks whether translation can be enabled: if language is set to one of the
  498. * special languages and language selector is not hidden, translation cannot be
  499. * enabled.
  500. *
  501. * @see content_translation_language_configuration_element_submit()
  502. */
  503. function content_translation_language_configuration_element_validate($element, FormStateInterface $form_state, array $form) {
  504. $key = $form_state->get(['content_translation', 'key']);
  505. $values = $form_state->getValue($key);
  506. if (!$values['language_alterable'] && $values['content_translation'] && \Drupal::languageManager()->isLanguageLocked($values['langcode'])) {
  507. foreach (\Drupal::languageManager()->getLanguages(LanguageInterface::STATE_LOCKED) as $language) {
  508. $locked_languages[] = $language->getName();
  509. }
  510. // @todo Set the correct form element name as soon as the element parents
  511. // are correctly set. We should be using NestedArray::getValue() but for
  512. // now we cannot.
  513. $form_state->setErrorByName('', t('"Show language selector" is not compatible with translating content that has default language: %choice. Either do not hide the language selector or pick a specific language.', ['%choice' => $locked_languages[$values['langcode']]]));
  514. }
  515. }
  516. /**
  517. * Form submission handler for element added with content_translation_language_configuration_element_process().
  518. *
  519. * Stores the content translation settings.
  520. *
  521. * @see content_translation_language_configuration_element_validate()
  522. */
  523. function content_translation_language_configuration_element_submit(array $form, FormStateInterface $form_state) {
  524. $key = $form_state->get(['content_translation', 'key']);
  525. $context = $form_state->get(['language', $key]);
  526. $enabled = $form_state->getValue([$key, 'content_translation']);
  527. if (\Drupal::service('content_translation.manager')->isEnabled($context['entity_type'], $context['bundle']) != $enabled) {
  528. \Drupal::service('content_translation.manager')->setEnabled($context['entity_type'], $context['bundle'], $enabled);
  529. \Drupal::entityManager()->clearCachedDefinitions();
  530. \Drupal::service('router.builder')->setRebuildNeeded();
  531. }
  532. }
  533. /**
  534. * Implements hook_form_FORM_ID_alter() for language_content_settings_form().
  535. */
  536. function content_translation_form_language_content_settings_form_alter(array &$form, FormStateInterface $form_state) {
  537. module_load_include('inc', 'content_translation', 'content_translation.admin');
  538. _content_translation_form_language_content_settings_form_alter($form, $form_state);
  539. }
  540. /**
  541. * Implements hook_preprocess_HOOK() for language-content-settings-table.html.twig.
  542. */
  543. function content_translation_preprocess_language_content_settings_table(&$variables) {
  544. module_load_include('inc', 'content_translation', 'content_translation.admin');
  545. _content_translation_preprocess_language_content_settings_table($variables);
  546. }
  547. /**
  548. * Implements hook_page_attachments().
  549. */
  550. function content_translation_page_attachments(&$page) {
  551. $route_match = \Drupal::routeMatch();
  552. // If the current route has no parameters, return.
  553. if (!($route = $route_match->getRouteObject()) || !($parameters = $route->getOption('parameters'))) {
  554. return;
  555. }
  556. // Determine if the current route represents an entity.
  557. foreach ($parameters as $name => $options) {
  558. if (!isset($options['type']) || strpos($options['type'], 'entity:') !== 0) {
  559. continue;
  560. }
  561. $entity = $route_match->getParameter($name);
  562. if ($entity instanceof ContentEntityInterface && $entity->hasLinkTemplate('canonical')) {
  563. // Current route represents a content entity. Build hreflang links.
  564. foreach ($entity->getTranslationLanguages() as $language) {
  565. $url = $entity->toUrl('canonical')
  566. ->setOption('language', $language)
  567. ->setAbsolute()
  568. ->toString();
  569. $page['#attached']['html_head_link'][] = [
  570. [
  571. 'rel' => 'alternate',
  572. 'hreflang' => $language->getId(),
  573. 'href' => $url,
  574. ],
  575. TRUE,
  576. ];
  577. }
  578. }
  579. // Since entity was found, no need to iterate further.
  580. return;
  581. }
  582. }