language.module 26.8 KB
Newer Older
1 2 3 4 5 6 7
<?php

/**
 * @file
 * Add language handling functionality to Drupal.
 */

8
use Drupal\Core\Access\AccessResult;
9 10
use Drupal\Core\Entity\ContentEntityFormInterface;
use Drupal\Core\Entity\EntityFormInterface;
11 12
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
13
use Drupal\Core\Form\FormStateInterface;
14
use Drupal\Core\Language\LanguageInterface;
15
use Drupal\Core\Routing\RouteMatchInterface;
16
use Drupal\Core\Session\AccountInterface;
17
use Drupal\language\ConfigurableLanguageInterface;
18
use Drupal\language\Entity\ContentLanguageSettings;
19 20 21
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUI;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrlFallback;
22

23 24 25
/**
 * Implements hook_help().
 */
26
function language_help($route_name, RouteMatchInterface $route_match) {
27 28
  switch ($route_name) {
    case 'help.page.language':
29 30
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
31
      $output .= '<p>' . t('The Language module allows you to configure the languages used on your site, and provides information for the for <a href="!content">Content Translation</a>, <a href="!interface">Interface Translation</a>, and <a href="!configuration">Configuration Translation</a> modules, if they are enabled. For more information, see <a href="!doc_url">the online documentation for the Language module</a>.', array('!doc_url' => 'https://drupal.org/documentation/modules/language', '!content' => (\Drupal::moduleHandler()->moduleExists('content_translation')) ? \Drupal::url('help.page', array('name' => 'content_translation')) : '#', '!interface' => (\Drupal::moduleHandler()->moduleExists('locale')) ? \Drupal::url('help.page', array('name' => 'locale')) : '#', '!configuration' => (\Drupal::moduleHandler()->moduleExists('config_translation')) ? \Drupal::url('help.page', array('name' => 'config_translation')) : '#')) . '</p>';
32 33
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
      $output .= '<dt>' . t('Adding languages') . '</dt>';
      $output .= '<dd>' . t('You can add languages on the <a href="!language_list">Languages</a> page by selecting <em>Add language</em> and choosing a language from the drop-down menu. This language is then displayed in the languages list, where it can be configured further. If the <a href="!interface">Interface translation module</a> is enabled, and the <em>translation server</em> is set as a translation source, then the interface translation for this language is automatically downloaded as well.' , array('!language_list' => \Drupal::url('language.admin_overview'), '!interface' => (\Drupal::moduleHandler()->moduleExists('locale')) ? \Drupal::url('help.page', array('name' => 'locale')) : '#')) . '</dd>';
      $output .= '<dt>' . t('Adding custom languages') . '</dt>';
      $output .= '<dd>' . t('You can add a language that is not provided in the drop-down list by choosing <em>Custom language</em> at the end of the list. You then have to configure its language code, name, and direction in the form provided.') . '</dd>';
      $output .= '<dt>' . t('Configuring content languages') . '</dt>';
      $output .= '<dd>' . t('By default, content is created in the site\'s default language and no language selector is displayed on content creation pages. On the <a href="!content_language">Content language</a> page you can customize the language configuration for any supported content entity on your site (for example for content types or menu links). After choosing an entity, you are provided with a drop-down menu to set the default language and a check-box to display language selectors.', array('!content_language' => \Drupal::url('language.content_settings_page'))) . '</dd>';
      $output .= '<dt>' . t('Adding a language switcher block') . '</dt>';
      $output .= '<dd>' . t('If the Block module is enabled, then you can add a language switcher block on the <a href="!blocks">Block layout</a> page to allow users to switch between languages.', array('!blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#')) . '</dd>';
      $output .= '<dt>' . t('Making a block visible per language') . '</dt>';
      $output .= '<dd>' . t('If the Block module is enabled, then the Language module allows you to set the visibility of a block based on selected languages on the <a href="!blocks">Block layout</a> page.', array('!blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#')) . '</dd>';
      $output .= '<dt>' . t('Choosing user languages') . '</dt>';
      $output .= '<dd>' . t('Users can choose a <em>Site language</em> on their profile page. This language is used for email messages, and can be used by modules to determine a user\'s language. It can also be used for interface text, if the <em>User</em> method is enabled as a <em>Detection and selection</em> method (see below). Administrative users can choose a separate <em>Administration pages language</em> for the interface text on administration pages. This configuration is only available on the user\'s profile page if the <em>Account administration pages</em> method is enabled (see below).') . '</dd>';
      $output .= '<dt>' . t('Language detection and selection') . '</dt>';
      $output .= '<dd>' . t('The <a href="!detection">Detection and selection</a> page provides several methods for deciding which language is used for displaying interface text. When a method detects and selects an interface language, then the following methods in the list are not applied. You can order them by importance, with your preferred method at the top of the list, followed by one or several fall-back methods.', array('!detection' => \Drupal::url('language.negotiation')));
      $output .= '<ul><li>' . t('<em>URL</em> sets the interface language based on a path prefix or domain (for example specifying <em>de</em> for German would result in URLs like <em>example.com/de/contact</em>). The default language does not require a path prefix, but can have one assigned as well. If the language detection is done by domain name, a domain needs to be specified for each language.') . '</li>';
      $output .= '<li>' . t('<em>Session</em> determines the interface language from a request or session parameter (for example <em>example.com?language=de</em> would set the interface language to German based on the use of <em>de</em> as the <em>language</em> parameter).') . '</li>';
      $output .= '<li>' . t('<em>User</em> follows the language configuration set on the user\'s profile page.') . '</li>';
      $output .= '<li>' . t('<em>Browser</em> sets the interface language based on the browser\'s language settings. Since browsers use different language codes to refer to the same languages, you can add and edit languages codes to map the browser language codes to the <a href="!language_list">language codes</a> used on your site.',  array('!language_list' => \Drupal::url('language.admin_overview'))) . '</li>';
      $output .= '<li>' . t('<em>Account administration pages</em> follows the configuration set as <em>Administration pages language</em> on the profile page of an administrative user. This method is similar to the <em>User</em> method, but only sets the interface text language on administration pages, independent of the interface text language on other pages.') . '</li>';
      $output .= '<li>' . t('<em>Selected language</em> allows you to specify the site\'s default language or a specific language as the fall-back language. This method should be listed last.') . '</li></ul></dd>';
54 55 56
      $output .= '</dl>';
      return $output;

57
    case 'language.admin_overview':
58
      return '<p>' . t('Reorder the added languages to set their order in the language switcher block and, when editing content, in the list of selectable languages. This ordering does not impact <a href="@detection">detection and selection</a>.', array('@detection' => \Drupal::url('language.negotiation'))) . '</p>';
59

60
    case 'language.add':
61
      return '<p>' . t('Add a language to be supported by your site. If your desired language is not available, pick <em>Custom language...</em> at the end and provide a language code and other details manually.') . '</p>';
62

63
    case 'language.negotiation':
64
      $output = '<p>' . t('Define how to decide which language is used to display page elements (primarily text provided by modules, such as field labels and help text). This decision is made by evaluating a series of detection methods for languages; the first detection method that gets a result will determine which language is used for that type of text. Be aware that some language negotiation methods are unreliable under certain conditions, such as browser detection when page-caching is enabled and a user is not currently logged in. Define the order of evaluation of language detection methods on this page. The default language can be changed at the <a href="!region-settings">Regional settings</a> page.', array('!region-settings' => \Drupal::url('system.regional_settings'))) . '</p>';
65 66
      return $output;

67
    case 'language.negotiation_session':
68 69 70
      $output = '<p>' . t('Determine the language from a request/session parameter. Example: "http://example.com?language=de" sets language to German based on the use of "de" within the "language" parameter.') . '</p>';
      return $output;

71
    case 'language.negotiation_browser':
72
      $output = '<p>' . t('Browsers use different language codes to refer to the same languages. Internally, a best effort is made to determine the correct language based on the code that the browser sends. You can add and edit additional mappings from browser language codes to <a href="!configure-languages">site languages</a>.', array('!configure-languages' => \Drupal::url('language.admin_overview'))) . '</p>';
73 74
      return $output;

75
    case 'language.negotiation_selected':
76
      $output = '<p>' . t('Changing the selected language here (and leaving this option as the last among the detection and selection options) is the easiest way to change the fallback language for the website, if you need to change how your site works by default (e.g., when using an empty path prefix or using the default domain). <a href="!admin-change-language">Changing the site\'s default language</a> itself might have other undesired side effects.', array('!admin-change-language' => \Drupal::url('language.admin_overview'))) . '</p>';
77 78
      return $output;

79
    case 'entity.block.edit_form':
80
      if (($block = $route_match->getParameter('block')) && $block->get('plugin') == 'language_block:language_interface') {
81
        return '<p>' . t('With multiple languages added, registered users can select their preferred language and authors can assign a specific language to content.') . '</p>';
82 83
      }
      break;
84

85
    case 'block.admin_add':
86
      if ($route_match->getParameter('plugin_id') == 'language_block:language_interface') {
87 88 89 90 91
        return '<p>' . t('With multiple languages added, registered users can select their preferred language and authors can assign a specific language to content.') . '</p>';
      }
      break;

    case 'language.content_settings_page':
92
      return t('Change language settings for <em>content types</em>, <em>taxonomy vocabularies</em>, <em>user profiles</em>, or any other supported element on your site. By default, language settings hide the language selector and the language is the site\'s default language.');
93 94 95 96 97 98 99 100
  }
}

/**
 * Implements hook_theme().
 */
function language_theme() {
  return array(
101 102
    'language_negotiation_configure_form' => array(
      'render element' => 'form',
103
      'file' => 'language.admin.inc',
104
    ),
105 106 107
    'language_negotiation_configure_browser_form_table' => array(
      'render element' => 'form',
      'file' => 'language.admin.inc',
108
      'function' => 'theme_language_negotiation_configure_browser_form_table',
109
    ),
110 111 112
    'language_content_settings_table' => array(
      'render element' => 'element',
      'file' => 'language.admin.inc',
113
      'function' => 'theme_language_content_settings_table',
114
    ),
115 116 117
  );
}

118 119 120 121 122 123 124 125 126 127 128 129 130
/**
 * Implements hook_element_info_alter().
 */
function language_element_info_alter(&$type) {
  // Alter the language_select element so that it will be rendered like a select
  // field.
  if (isset($type['language_select'])) {
    if (!isset($type['language_select']['#process'])) {
      $type['language_select']['#process'] = array();
    }
    if (!isset($type['language_select']['#theme_wrappers'])) {
      $type['language_select']['#theme_wrappers'] = array();
    }
131 132 133 134 135
    $type['language_select']['#process'] = array_merge($type['language_select']['#process'], array(
      'language_process_language_select',
      array('Drupal\Core\Render\Element\Select', 'processSelect'),
      array('Drupal\Core\Render\Element\RenderElement', 'processAjaxForm'),
    ));
136 137
    $type['language_select']['#theme'] = 'select';
    $type['language_select']['#theme_wrappers'] = array_merge($type['language_select']['#theme_wrappers'], array('form_element'));
138
    $type['language_select']['#languages'] = LanguageInterface::STATE_CONFIGURABLE;
139 140 141 142 143 144 145 146 147 148 149 150 151 152
    $type['language_select']['#multiple'] = FALSE;
  }
}

/**
 * Processes a language select list form element.
 *
 * @param array $element
 *   The form element to process.
 *
 * @return array $element
 *   The processed form element.
 */
function language_process_language_select($element) {
153
  // Don't set the options if another module (translation for example) already
154 155 156
  // set the options.
  if (!isset($element['#options'])) {
    $element['#options'] = array();
157
    foreach (\Drupal::languageManager()->getLanguages($element['#languages']) as $langcode => $language) {
158
      $element['#options'][$langcode] = $language->isLocked() ? t('- @name -', array('@name' => $language->getName())) : $language->getName();
159 160
    }
  }
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
  // Add "Built-in English" language to the select when the default value is
  // set to English but it does not exist in the options list.
  //
  // Drupal core includes configuration shipped in English, including default
  // views, content types, user roles, filter formats, etc. To keep the Drupal
  // software update-able, as well as translations update-able, we keep these
  // configuration files in English even when installed in a foreign language.
  // However, administrators can remove English, in which case editing such a
  // configuration would lead to the language settings being changed on it. We
  // avoid that by including this option and letting administrators keep it
  // in English.
  if (isset($element['#default_value']) && $element['#default_value'] == 'en' && !isset($element['#options']['en'])) {
    // Prepend the default language at the beginning of the list.
    $element['#options'] = array('en' => t('Built-in English')) + $element['#options'];
  }
176 177 178
  return $element;
}

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
/**
 * Implements hook_entity_base_field_info_alter().
 */
function language_entity_base_field_info_alter(&$fields) {
  foreach ($fields as $definition) {
    // Set configurable form display for language fields with display options.
    if ($definition->getType() == 'language') {
      foreach (array('form', 'view') as $type)  {
        if ($definition->getDisplayOptions($type)) {
          // The related configurations will be purged manually on Language
          // module uninstallation. @see language_modules_uninstalled().
          $definition->setDisplayConfigurable($type, TRUE);
        }
      }
    }
  }
}

197 198 199
/**
 * Submit handler for the forms that have a language_configuration element.
 */
200
function language_configuration_element_submit(&$form, FormStateInterface $form_state) {
201 202
  // Iterate through all the language_configuration elements and save their
  // values.
203 204
  // In case we are editing a bundle, we must check the new bundle name,
  // because e.g. hook_ENTITY_update fired before.
205 206
  if ($language = $form_state->get('language')) {
    foreach ($language as $element_name => $values) {
207 208 209 210 211 212 213 214 215 216 217 218 219 220
      $entity_type_id = $values['entity_type'];
      $bundle = $values['bundle'];
      $form_object = $form_state->getFormObject();
      if ($form_object instanceof EntityFormInterface && !$form_object->getEntity()->isNew() && in_array($form_object->getOperation(), ['default', 'edit'])) {
        /** @var EntityFormInterface $form_object */
        $entity = $form_object->getEntity();
        if ($entity->getEntityType()->getBundleOf()) {
          $bundle = $entity->id();
        }
      }
      $config = ContentLanguageSettings::loadByEntityTypeBundle($entity_type_id, $bundle);
      $config->setDefaultLangcode($form_state->getValue(array($element_name, 'langcode')));
      $config->setLanguageAlterable($form_state->getValue(array($element_name, 'language_alterable')));
      $config->save();
221 222 223 224 225
    }
  }
}

/**
226
 * Implements hook_entity_bundle_rename().
227
 */
228 229 230 231
function language_entity_bundle_rename($entity_type_id, $bundle_old, $bundle_new) {
  ContentLanguageSettings::loadByEntityTypeBundle($entity_type_id, $bundle_old)
    ->setTargetBundle($bundle_new)
    ->save();
232 233 234 235 236 237 238 239 240 241 242 243 244 245
}

/**
 * Returns the default language code assigned to an entity type and a bundle.
 *
 * @param string $entity_type
 *   The entity type.
 * @param string $bundle
 *   The bundle name.
 *
 * @return string
 *   The language code.
 */
function language_get_default_langcode($entity_type, $bundle) {
246
  $configuration = ContentLanguageSettings::loadByEntityTypeBundle($entity_type, $bundle);
247 248

  $default_value = NULL;
249
  $language_interface = \Drupal::languageManager()->getCurrentLanguage();
250
  switch ($configuration->getDefaultLangcode()) {
251
    case LanguageInterface::LANGCODE_SITE_DEFAULT:
252
      $default_value = \Drupal::languageManager()->getDefaultLanguage()->getId();
253 254 255
      break;

    case 'current_interface':
256
      $default_value = $language_interface->getId();
257 258 259
      break;

    case 'authors_default':
260
      $user = \Drupal::currentUser();
261 262 263
      $language_code = $user->getPreferredLangcode();
      if (!empty($language_code)) {
        $default_value = $language_code;
264 265
      }
      else {
266
        $default_value = $language_interface->getId();
267 268 269 270 271 272 273 274 275
      }
      break;
  }
  if ($default_value) {
    return $default_value;
  }

  // If we still do not have a default value, just return the value stored in
  // the configuration; it has to be an actual language code.
276
  return $configuration->getDefaultLangcode();
277 278
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
/**
 * Implements hook_language_types_info().
 *
 * Defines the three core language types:
 * - Interface language is the only configurable language type in core. It is
 *   used by t() as the default language if none is specified.
 * - Content language is by default non-configurable and inherits the interface
 *   language negotiated value. It is used by the Field API to determine the
 *   display language for fields if no explicit value is specified.
 * - URL language is by default non-configurable and is determined through the
 *   URL language negotiation method or the URL fallback language negotiation
 *   method if no language can be detected. It is used by l() as the default
 *   language if none is specified.
 */
function language_language_types_info() {
  return array(
295
    LanguageInterface::TYPE_INTERFACE => array(
296 297
      'name' => t('User interface text'),
      'description' => t('Order of language detection methods for user interface text. If a translation of user interface text is available in the detected language, it will be displayed.'),
298
      'locked' => TRUE,
299
    ),
300
    LanguageInterface::TYPE_CONTENT => array(
301 302
      'name' => t('Content'),
      'description' => t('Order of language detection methods for content. If a version of content is available in the detected language, it will be displayed.'),
303
      'fixed' => array(LanguageNegotiationUI::METHOD_ID),
304
      'locked' => TRUE,
305
    ),
306
    LanguageInterface::TYPE_URL => array(
307
      'fixed' => array(LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationUrlFallback::METHOD_ID),
308
      'locked' => TRUE,
309 310 311 312 313
    ),
  );
}

/**
314
 * Reads language prefixes and uses the langcode if no prefix is set.
315
 */
316 317 318
function language_negotiation_url_prefixes() {
  return \Drupal::config('language.negotiation')->get('url.prefixes');
}
319

320 321 322 323 324
/**
 * Update the list of prefixes from the installed languages.
 */
function language_negotiation_url_prefixes_update() {
  $prefixes = language_negotiation_url_prefixes();
325
  foreach (\Drupal::languageManager()->getLanguages() as $language) {
326 327
    // The prefix for this language should be updated if it's not assigned yet
    // or the prefix is set to the empty string.
328
    if (empty($prefixes[$language->getId()])) {
329 330
      // For the default language, set the prefix to the empty string,
      // otherwise use the langcode.
331
      $prefixes[$language->getId()] = $language->isDefault() ? '' : $language->getId();
332 333 334 335 336
    }
    // Otherwise we keep the configured prefix.
  }
  language_negotiation_url_prefixes_save($prefixes);
}
337

338 339 340 341 342 343 344 345
/**
 * Saves language prefix settings.
 */
function language_negotiation_url_prefixes_save(array $prefixes) {
  \Drupal::config('language.negotiation')
  ->set('url.prefixes', $prefixes)
  ->save();
}
346

347 348 349 350 351
/**
 * Reads language domains.
 */
function language_negotiation_url_domains() {
  return \Drupal::config('language.negotiation')->get('url.domains');
352 353 354
}

/**
355
 * Saves the language domain settings.
356
 */
357 358 359 360
function language_negotiation_url_domains_save(array $domains) {
  \Drupal::config('language.negotiation')
  ->set('url.domains', $domains)
  ->save();
361 362 363
}

/**
364
 * Implements hook_modules_installed().
365
 */
366
function language_modules_installed($modules) {
367 368 369 370 371
  if (!in_array('language', $modules)) {
    $negotiator = \Drupal::service('language_negotiator');
    $negotiator->updateConfiguration(array());
    $negotiator->purgeConfiguration();
  }
372 373 374 375 376 377 378 379 380 381 382 383 384
  else {
    // In language_entity_base_field_info_alter() we are altering view/form
    // display definitions to make language fields display configurable. Since
    // this is not a hard dependency, and thus is not detected by the config
    // system, we have to clean up the related values manually.
    foreach (array('entity_view_display', 'entity_form_display') as $key) {
      $displays = \Drupal::entityManager()->getStorage($key)->loadMultiple();
      /** @var \Drupal\Core\Entity\Display\EntityDisplayInterface $display */
      foreach ($displays as $display) {
        $display->save();
      }
    }
  }
385 386 387
}

/**
388
 * Implements hook_modules_uninstalled().
389
 */
390 391
function language_modules_uninstalled($modules) {
  language_modules_installed($modules);
392 393 394
}

/**
395
 * Implements hook_ENTITY_TYPE_insert() for 'configurable_language'.
396
 */
397
function language_configurable_language_insert(ConfigurableLanguageInterface $language) {
398
  if ($language->isLocked()) {
399 400 401
    return;
  }

402 403
  // Add language to the list of language domains.
  $domains = language_negotiation_url_domains();
404
  $domains[$language->id()] = '';
405 406 407 408
  language_negotiation_url_domains_save($domains);
}

/**
409
 * Implements hook_ENTITY_TYPE_delete() for 'configurable_language'.
410
 */
411
function language_configurable_language_delete(ConfigurableLanguageInterface $language) {
412 413
  // Remove language from language prefix list.
  $prefixes = language_negotiation_url_prefixes();
414
  unset($prefixes[$language->id()]);
415 416 417 418
  language_negotiation_url_prefixes_save($prefixes);

  // Remove language from language domain list.
  $domains = language_negotiation_url_domains();
419
  unset($domains[$language->id()]);
420 421 422 423
  language_negotiation_url_domains_save($domains);
}

/**
424
 * Implements hook_preprocess_HOOK() for block templates.
425 426
 */
function language_preprocess_block(&$variables) {
427
  if ($variables['configuration']['provider'] == 'language') {
428
    $variables['attributes']['role'] = 'navigation';
429 430 431
  }
}

432 433 434 435 436 437 438 439
/**
 * Returns language mappings between browser and Drupal language codes.
 *
 * @return array
 *   An array containing browser language codes as keys with corresponding
 *   Drupal language codes as values.
 */
function language_get_browser_drupal_langcode_mappings() {
440
  $config = \Drupal::config('language.mappings');
441 442 443 444 445 446
  if ($config->isNew()) {
    return array();
  }
  return $config->get();
}

447 448 449 450 451
/**
 * Implements hook_form_FORM_ID_alter for system_regional_settings().
 *
 * @see language_system_regional_settings_form_submit()
 */
452
function language_form_system_regional_settings_alter(&$form, FormStateInterface $form_state) {
453 454
  $languages = \Drupal::languageManager()->getLanguages();
  $default = \Drupal::languageManager()->getDefaultLanguage();
455
  foreach ($languages as $key => $language) {
456
    $language_options[$key] = $language->getName();
457 458 459 460
  }
  $form['locale']['site_default_language'] = array(
    '#type' => 'select',
    '#title' => t('Default language'),
461
    '#default_value' => $default->getId(),
462
    '#options' => $language_options,
463
    '#description' => t('It is not recommended to change the default language on a working site. <a href="@language-detection">Configure the Selected language</a> setting on the detection and selection page to change the fallback language for language selection.', array('@language-detection' => \Drupal::url('language.negotiation'))),
464 465 466 467 468 469
    '#weight' => -1,
  );
  // Add submit handler to save default language.
  $form['#submit'][] = 'language_system_regional_settings_form_submit';
}

470 471 472
/**
 * Implements hook_form_alter().
 */
473
function language_form_alter(&$form, FormStateInterface $form_state) {
474 475 476
  // Content entity forms may have added a langcode field. But content language
  // configuration should decide if it should be exposed or not in the forms.
  $form_object = $form_state->getFormObject();
477
  if ($form_object instanceof ContentEntityFormInterface) {
478
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
479 480 481 482 483 484
    $entity = $form_object->getEntity();
    $entity_type = $entity->getEntityType();
    $langcode_key = $entity_type->getKey('langcode');
    if (isset($form[$langcode_key]) && $entity_type->isTranslatable()) {
      $language_configuration = ContentLanguageSettings::loadByEntityTypeBundle($entity->getEntityTypeId(), $entity->bundle());
      $form[$langcode_key]['#access'] = $language_configuration->isLanguageAlterable();
485 486 487 488
    }
  }
}

489 490 491 492 493
/**
 * Form submission handler for system_regional_settings().
 *
 * @see language_form_system_regional_settings_alter()
 */
494
function language_system_regional_settings_form_submit($form, FormStateInterface $form_state) {
495
  \Drupal::config('system.site')->set('langcode', $form_state->getValue('site_default_language'))->save();
496
}
497 498 499 500 501 502 503 504

/**
 * Implements hook_field_info_alter().
 */
function language_field_info_alter(&$info) {
  // Change the default behavior of language field.
  $info['language']['class'] = '\Drupal\language\DefaultLanguageItem';
}
505 506 507 508 509

/**
 * Implements hook_entity_field_access()
 */
function language_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, FieldItemListInterface $items = NULL) {
510 511
  $langcode_key = $items->getEntity()->getEntityType()->getKey('langcode');
  if ($field_definition->getName() == $langcode_key) {
512 513 514 515 516 517
    $entity = $items->getEntity();
    $config = ContentLanguageSettings::loadByEntityTypeBundle($entity->getEntityTypeId(), $entity->bundle());
    return AccessResult::forbiddenIf(!$config->isLanguageAlterable());
  }
  return AccessResult::neutral();
}