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