annotate core/modules/content_translation/content_translation.module @ 0:c75dbcec494b

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