annotate core/modules/content_translation/content_translation.module @ 19:fa3358dc1485 tip

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