Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / modules / content_translation / content_translation.admin.inc
1 <?php
2
3 /**
4  * @file
5  * The content translation administration forms.
6  */
7
8 use Drupal\content_translation\BundleTranslationSettingsInterface;
9 use Drupal\content_translation\ContentTranslationManager;
10 use Drupal\Core\Config\Entity\ThirdPartySettingsInterface;
11 use Drupal\Core\Entity\ContentEntityTypeInterface;
12 use Drupal\Core\Entity\EntityTypeInterface;
13 use Drupal\Core\Field\FieldDefinitionInterface;
14 use Drupal\Core\Field\FieldStorageDefinitionInterface;
15 use Drupal\Core\Form\FormStateInterface;
16 use Drupal\Core\Language\LanguageInterface;
17 use Drupal\Core\Render\Element;
18
19 /**
20  * Returns a form element to configure field synchronization.
21  *
22  * @param \Drupal\Core\Field\FieldDefinitionInterface $field
23  *   A field definition object.
24  * @param string $element_name
25  *   (optional) The element name, which is added to drupalSettings so that
26  *   javascript can manipulate the form element.
27  *
28  * @return array
29  *   A form element to configure field synchronization.
30  */
31 function content_translation_field_sync_widget(FieldDefinitionInterface $field, $element_name = 'third_party_settings[content_translation][translation_sync]') {
32   // No way to store field sync information on this field.
33   if (!($field instanceof ThirdPartySettingsInterface)) {
34     return [];
35   }
36
37   $element = [];
38   $definition = \Drupal::service('plugin.manager.field.field_type')->getDefinition($field->getType());
39   $column_groups = $definition['column_groups'];
40   if (!empty($column_groups) && count($column_groups) > 1) {
41     $options = [];
42     $default = [];
43     $require_all_groups_for_translation = [];
44
45     foreach ($column_groups as $group => $info) {
46       $options[$group] = $info['label'];
47       $default[$group] = !empty($info['translatable']) ? $group : FALSE;
48       if (!empty($info['require_all_groups_for_translation'])) {
49         $require_all_groups_for_translation[] = $group;
50       }
51     }
52
53     $default = $field->getThirdPartySetting('content_translation', 'translation_sync', $default);
54
55     $element = [
56       '#type' => 'checkboxes',
57       '#title' => t('Translatable elements'),
58       '#options' => $options,
59       '#default_value' => $default,
60     ];
61
62     if ($require_all_groups_for_translation) {
63       // The actual checkboxes are sometimes rendered separately and the parent
64       // element is ignored. Attach to the first option to ensure that this
65       // does not get lost.
66       $element[key($options)]['#attached']['drupalSettings']['contentTranslationDependentOptions'] = [
67         'dependent_selectors' => [
68           $element_name => $require_all_groups_for_translation
69         ],
70       ];
71       $element[key($options)]['#attached']['library'][] = 'content_translation/drupal.content_translation.admin';
72     }
73   }
74
75   return $element;
76 }
77
78 /**
79  * (proxied) Implements hook_form_FORM_ID_alter().
80  */
81 function _content_translation_form_language_content_settings_form_alter(array &$form, FormStateInterface $form_state) {
82   // Inject into the content language settings the translation settings if the
83   // user has the required permission.
84   if (!\Drupal::currentUser()->hasPermission('administer content translation')) {
85     return;
86   }
87
88   /** @var \Drupal\content_translation\ContentTranslationManagerInterface $content_translation_manager */
89   $content_translation_manager = \Drupal::service('content_translation.manager');
90   $default = $form['entity_types']['#default_value'];
91   foreach ($default as $entity_type_id => $enabled) {
92     $default[$entity_type_id] = $enabled || $content_translation_manager->isEnabled($entity_type_id) ? $entity_type_id : FALSE;
93   }
94   $form['entity_types']['#default_value'] = $default;
95
96   $form['#attached']['library'][] = 'content_translation/drupal.content_translation.admin';
97
98   $entity_manager = Drupal::entityManager();
99   $bundle_info_service = \Drupal::service('entity_type.bundle.info');
100   foreach ($form['#labels'] as $entity_type_id => $label) {
101     $entity_type = $entity_manager->getDefinition($entity_type_id);
102     $storage_definitions = $entity_type instanceof ContentEntityTypeInterface ? $entity_manager->getFieldStorageDefinitions($entity_type_id) : [];
103
104     $entity_type_translatable = $content_translation_manager->isSupported($entity_type_id);
105     foreach ($bundle_info_service->getBundleInfo($entity_type_id) as $bundle => $bundle_info) {
106       // Here we do not want the widget to be altered and hold also the "Enable
107       // translation" checkbox, which would be redundant. Hence we add this key
108       // to be able to skip alterations. Alter the title and display the message
109       // about UI integration.
110       $form['settings'][$entity_type_id][$bundle]['settings']['language']['#content_translation_skip_alter'] = TRUE;
111       if (!$entity_type_translatable) {
112         $form['settings'][$entity_type_id]['#title'] = t('@label (Translation is not supported).', ['@label' => $entity_type->getLabel()]);
113         continue;
114       }
115
116       // Displayed the "shared fields widgets" toggle.
117       if ($content_translation_manager instanceof BundleTranslationSettingsInterface) {
118         $settings = $content_translation_manager->getBundleTranslationSettings($entity_type_id, $bundle);
119         $force_hidden = ContentTranslationManager::isPendingRevisionSupportEnabled($entity_type_id, $bundle);
120         $form['settings'][$entity_type_id][$bundle]['settings']['content_translation']['untranslatable_fields_hide'] = [
121           '#type' => 'checkbox',
122           '#title' => t('Hide non translatable fields on translation forms'),
123           '#default_value' => $force_hidden || !empty($settings['untranslatable_fields_hide']),
124           '#disabled' => $force_hidden,
125           '#description' => $force_hidden ? t('Moderated content requires non-translatable fields to be edited in the original language form.') : '',
126           '#states' => [
127             'visible' => [
128               ':input[name="settings[' . $entity_type_id . '][' . $bundle . '][translatable]"]' => [
129                 'checked' => TRUE,
130               ],
131             ],
132           ],
133         ];
134       }
135
136       $fields = $entity_manager->getFieldDefinitions($entity_type_id, $bundle);
137       if ($fields) {
138         foreach ($fields as $field_name => $definition) {
139           if ($definition->isComputed() || (!empty($storage_definitions[$field_name]) && _content_translation_is_field_translatability_configurable($entity_type, $storage_definitions[$field_name]))) {
140             $form['settings'][$entity_type_id][$bundle]['fields'][$field_name] = [
141               '#label' => $definition->getLabel(),
142               '#type' => 'checkbox',
143               '#default_value' => $definition->isTranslatable(),
144             ];
145             // Display the column translatability configuration widget.
146             $column_element = content_translation_field_sync_widget($definition, "settings[{$entity_type_id}][{$bundle}][columns][{$field_name}]");
147             if ($column_element) {
148               $form['settings'][$entity_type_id][$bundle]['columns'][$field_name] = $column_element;
149             }
150           }
151         }
152         if (!empty($form['settings'][$entity_type_id][$bundle]['fields'])) {
153           // Only show the checkbox to enable translation if the bundles in the
154           // entity might have fields and if there are fields to translate.
155           $form['settings'][$entity_type_id][$bundle]['translatable'] = [
156             '#type' => 'checkbox',
157             '#default_value' => $content_translation_manager->isEnabled($entity_type_id, $bundle),
158           ];
159         }
160       }
161     }
162   }
163
164   $form['#validate'][] = 'content_translation_form_language_content_settings_validate';
165   $form['#submit'][] = 'content_translation_form_language_content_settings_submit';
166 }
167 /**
168  * Checks whether translatability should be configurable for a field.
169  *
170  * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
171  *   The entity type definition.
172  * @param \Drupal\Core\Field\FieldStorageDefinitionInterface $definition
173  *   The field storage definition.
174  *
175  * @return bool
176  *   TRUE if field translatability can be configured, FALSE otherwise.
177  *
178  * @internal
179  */
180 function _content_translation_is_field_translatability_configurable(EntityTypeInterface $entity_type, FieldStorageDefinitionInterface $definition) {
181   // Allow to configure only fields supporting multilingual storage. We skip our
182   // own fields as they are always translatable. Additionally we skip a set of
183   // well-known fields implementing entity system business logic.
184   return
185     $definition->isTranslatable() &&
186     $definition->getProvider() != 'content_translation' &&
187     !in_array($definition->getName(), [$entity_type->getKey('langcode'), $entity_type->getKey('default_langcode'), 'revision_translation_affected']);
188 }
189
190 /**
191  * (proxied) Implements hook_preprocess_HOOK();
192  */
193 function _content_translation_preprocess_language_content_settings_table(&$variables) {
194   // Alter the 'build' variable injecting the translation settings if the user
195   // has the required permission.
196   if (!\Drupal::currentUser()->hasPermission('administer content translation')) {
197     return;
198   }
199
200   $element = $variables['element'];
201   $build = &$variables['build'];
202
203   array_unshift($build['#header'], ['data' => t('Translatable'), 'class' => ['translatable']]);
204   $rows = [];
205
206   foreach (Element::children($element) as $bundle) {
207     $field_names = !empty($element[$bundle]['fields']) ? Element::children($element[$bundle]['fields']) : [];
208     if (!empty($element[$bundle]['translatable'])) {
209       $checkbox_id = $element[$bundle]['translatable']['#id'];
210     }
211     $rows[$bundle] = $build['#rows'][$bundle];
212
213     if (!empty($element[$bundle]['translatable'])) {
214       $translatable = [
215         'data' => $element[$bundle]['translatable'],
216         'class' => ['translatable'],
217       ];
218       array_unshift($rows[$bundle]['data'], $translatable);
219
220       $rows[$bundle]['data'][1]['data']['#prefix'] = '<label for="' . $checkbox_id . '">';
221     }
222     else {
223       $translatable = [
224         'data' => t('N/A'),
225         'class' => ['untranslatable'],
226       ];
227       array_unshift($rows[$bundle]['data'], $translatable);
228     }
229
230     foreach ($field_names as $field_name) {
231       $field_element = &$element[$bundle]['fields'][$field_name];
232       $rows[] = [
233         'data' => [
234           [
235             'data' => \Drupal::service('renderer')->render($field_element),
236             'class' => ['translatable'],
237           ],
238           [
239             'data' => [
240               '#prefix' => '<label for="' . $field_element['#id'] . '">',
241               '#suffix' => '</label>',
242               'bundle' => [
243                 '#prefix' => '<span class="visually-hidden">',
244                 '#suffix' => '</span> ',
245                 '#plain_text' => $element[$bundle]['settings']['#label'],
246               ],
247               'field' => [
248                 '#plain_text' => $field_element['#label'],
249               ],
250             ],
251             'class' => ['field'],
252           ],
253           [
254             'data' => '',
255             'class' => ['operations'],
256           ],
257         ],
258         'class' => ['field-settings'],
259       ];
260
261       if (!empty($element[$bundle]['columns'][$field_name])) {
262         $column_element = &$element[$bundle]['columns'][$field_name];
263         foreach (Element::children($column_element) as $key) {
264           $column_label = $column_element[$key]['#title'];
265           unset($column_element[$key]['#title']);
266           $rows[] = [
267             'data' => [
268               [
269                 'data' => \Drupal::service('renderer')->render($column_element[$key]),
270                 'class' => ['translatable'],
271               ],
272               [
273                 'data' => [
274                   '#prefix' => '<label for="' . $column_element[$key]['#id'] . '">',
275                   '#suffix' => '</label>',
276                   'bundle' => [
277                     '#prefix' => '<span class="visually-hidden">',
278                     '#suffix' => '</span> ',
279                     '#plain_text' => $element[$bundle]['settings']['#label'],
280                   ],
281                   'field' => [
282                     '#prefix' => '<span class="visually-hidden">',
283                     '#suffix' => '</span> ',
284                     '#plain_text' => $field_element['#label'],
285                   ],
286                   'columns' => [
287                     '#plain_text' => $column_label,
288                   ],
289                 ],
290                 'class' => ['column'],
291               ],
292               [
293                 'data' => '',
294                 'class' => ['operations'],
295               ],
296             ],
297             'class' => ['column-settings'],
298           ];
299         }
300       }
301     }
302   }
303
304   $build['#rows'] = $rows;
305 }
306
307 /**
308  * Form validation handler for content_translation_admin_settings_form().
309  *
310  * @see content_translation_admin_settings_form_submit()
311  */
312 function content_translation_form_language_content_settings_validate(array $form, FormStateInterface $form_state) {
313   $settings = &$form_state->getValue('settings');
314   foreach ($settings as $entity_type => $entity_settings) {
315     foreach ($entity_settings as $bundle => $bundle_settings) {
316       if (!empty($bundle_settings['translatable'])) {
317         $name = "settings][$entity_type][$bundle][translatable";
318
319         $translatable_fields = isset($settings[$entity_type][$bundle]['fields']) ? array_filter($settings[$entity_type][$bundle]['fields']) : FALSE;
320         if (empty($translatable_fields)) {
321           $t_args = ['%bundle' => $form['settings'][$entity_type][$bundle]['settings']['#label']];
322           $form_state->setErrorByName($name, t('At least one field needs to be translatable to enable %bundle for translation.', $t_args));
323         }
324
325         $values = $bundle_settings['settings']['language'];
326         if (empty($values['language_alterable']) && \Drupal::languageManager()->isLanguageLocked($values['langcode'])) {
327           foreach (\Drupal::languageManager()->getLanguages(LanguageInterface::STATE_LOCKED) as $language) {
328             $locked_languages[] = $language->getName();
329           }
330           $form_state->setErrorByName($name, t('Translation is not supported if language is always one of: @locked_languages', ['@locked_languages' => implode(', ', $locked_languages)]));
331         }
332       }
333     }
334   }
335 }
336
337 /**
338  * Form submission handler for content_translation_admin_settings_form().
339  *
340  * @see content_translation_admin_settings_form_validate()
341  */
342 function content_translation_form_language_content_settings_submit(array $form, FormStateInterface $form_state) {
343   /** @var \Drupal\content_translation\ContentTranslationManagerInterface $content_translation_manager */
344   $content_translation_manager = \Drupal::service('content_translation.manager');
345   $entity_types = $form_state->getValue('entity_types');
346   $settings = &$form_state->getValue('settings');
347
348   // If an entity type is not translatable all its bundles and fields must be
349   // marked as non-translatable. Similarly, if a bundle is made non-translatable
350   // all of its fields will be not translatable.
351   foreach ($settings as $entity_type_id => &$entity_settings) {
352     foreach ($entity_settings as $bundle => &$bundle_settings) {
353       $fields = \Drupal::entityManager()->getFieldDefinitions($entity_type_id, $bundle);
354       if (!empty($bundle_settings['translatable'])) {
355         $bundle_settings['translatable'] = $bundle_settings['translatable'] && $entity_types[$entity_type_id];
356       }
357       if (!empty($bundle_settings['fields'])) {
358         foreach ($bundle_settings['fields'] as $field_name => $translatable) {
359           $translatable = $translatable && $bundle_settings['translatable'];
360           // If we have column settings and no column is translatable, no point
361           // in making the field translatable.
362           if (isset($bundle_settings['columns'][$field_name]) && !array_filter($bundle_settings['columns'][$field_name])) {
363             $translatable = FALSE;
364           }
365           $field_config = $fields[$field_name]->getConfig($bundle);
366           if ($field_config->isTranslatable() != $translatable) {
367             $field_config
368               ->setTranslatable($translatable)
369               ->save();
370           }
371         }
372       }
373       if (isset($bundle_settings['translatable'])) {
374         // Store whether a bundle has translation enabled or not.
375         $content_translation_manager->setEnabled($entity_type_id, $bundle, $bundle_settings['translatable']);
376
377         // Store any other bundle settings.
378         if ($content_translation_manager instanceof BundleTranslationSettingsInterface) {
379           $content_translation_manager->setBundleTranslationSettings($entity_type_id, $bundle, $bundle_settings['settings']['content_translation']);
380         }
381
382         // Save translation_sync settings.
383         if (!empty($bundle_settings['columns'])) {
384           foreach ($bundle_settings['columns'] as $field_name => $column_settings) {
385             $field_config = $fields[$field_name]->getConfig($bundle);
386             if ($field_config->isTranslatable()) {
387               $field_config->setThirdPartySetting('content_translation', 'translation_sync', $column_settings);
388             }
389             // If the field does not have translatable enabled we need to reset
390             // the sync settings to their defaults.
391             else {
392               $field_config->unsetThirdPartySetting('content_translation', 'translation_sync');
393             }
394             $field_config->save();
395           }
396         }
397       }
398     }
399   }
400
401   // Ensure entity and menu router information are correctly rebuilt.
402   \Drupal::entityManager()->clearCachedDefinitions();
403   \Drupal::service('router.builder')->setRebuildNeeded();
404 }