content_translation.module 34 KB

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