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