3 namespace Drupal\language\Tests;
6 use Drupal\language\Entity\ConfigurableLanguage;
7 use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationBrowser;
8 use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSelected;
9 use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSession;
10 use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl;
11 use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUser;
12 use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUserAdmin;
13 use Drupal\simpletest\WebTestBase;
14 use Drupal\Core\Language\Language;
15 use Drupal\Core\Language\LanguageInterface;
16 use Symfony\Component\HttpFoundation\Request;
17 use Drupal\language\LanguageNegotiatorInterface;
18 use Drupal\block\Entity\Block;
21 * Tests the language UI for language switching.
23 * The uses cases that get tested, are:
24 * - URL (path) > default: Test that the URL prefix setting gets precedence over
25 * the default language. The browser language preference does not have any
27 * - URL (path) > browser > default: Test that the URL prefix setting gets
28 * precedence over the browser language preference, which in turn gets
29 * precedence over the default language.
30 * - URL (domain) > default: Tests that the URL domain setting gets precedence
31 * over the default language.
33 * The paths that are used for each of these, are:
34 * - admin/config: Tests the UI using the precedence rules.
35 * - zh-hans/admin/config: Tests the UI in Chinese.
36 * - blah-blah/admin/config: Tests the 404 page.
40 class LanguageUILanguageNegotiationTest extends WebTestBase {
45 * We marginally use interface translation functionality here, so need to use
46 * the locale module instead of language only, but the 90% of the test is
47 * about the negotiation process which is solely in language module.
51 public static $modules = ['locale', 'language_test', 'block', 'user', 'content_translation'];
53 protected function setUp() {
56 $admin_user = $this->drupalCreateUser(['administer languages', 'translate interface', 'access administration pages', 'administer blocks']);
57 $this->drupalLogin($admin_user);
61 * Tests for language switching by URL path.
63 public function testUILanguageNegotiation() {
64 // A few languages to switch to.
65 // This one is unknown, should get the default lang version.
66 $langcode_unknown = 'blah-blah';
67 // For testing browser lang preference.
68 $langcode_browser_fallback = 'vi';
69 // For testing path prefix.
70 $langcode = 'zh-hans';
71 // For setting browser language preference to 'vi'.
72 $http_header_browser_fallback = ["Accept-Language: $langcode_browser_fallback;q=1"];
73 // For setting browser language preference to some unknown.
74 $http_header_blah = ["Accept-Language: blah;q=1"];
76 // Setup the site languages by installing two languages.
77 // Set the default language in order for the translated string to be registered
78 // into database when seen by t(). Without doing this, our target string
79 // is for some reason not found when doing translate search. This might
81 $default_language = \Drupal::languageManager()->getDefaultLanguage();
82 ConfigurableLanguage::createFromLangcode($langcode_browser_fallback)->save();
83 $this->config('system.site')->set('default_langcode', $langcode_browser_fallback)->save();
84 ConfigurableLanguage::createFromLangcode($langcode)->save();
86 // We will look for this string in the admin/config screen to see if the
87 // corresponding translated string is shown.
88 $default_string = 'Hide descriptions';
90 // First visit this page to make sure our target string is searchable.
91 $this->drupalGet('admin/config');
93 // Now the t()'ed string is in db so switch the language back to default.
94 // This will rebuild the container so we need to rebuild the container in
95 // the test environment.
96 $this->config('system.site')->set('default_langcode', $default_language->getId())->save();
97 $this->config('language.negotiation')->set('url.prefixes.en', '')->save();
98 $this->rebuildContainer();
100 // Translate the string.
101 $language_browser_fallback_string = "In $langcode_browser_fallback In $langcode_browser_fallback In $langcode_browser_fallback";
102 $language_string = "In $langcode In $langcode In $langcode";
103 // Do a translate search of our target string.
105 'string' => $default_string,
106 'langcode' => $langcode_browser_fallback,
108 $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
109 $textarea = current($this->xpath('//textarea'));
110 $lid = (string) $textarea[0]['name'];
112 $lid => $language_browser_fallback_string,
114 $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
117 'string' => $default_string,
118 'langcode' => $langcode,
120 $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
121 $textarea = current($this->xpath('//textarea'));
122 $lid = (string) $textarea[0]['name'];
124 $lid => $language_string,
126 $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
128 // Configure selected language negotiation to use zh-hans.
129 $edit = ['selected_langcode' => $langcode];
130 $this->drupalPostForm('admin/config/regional/language/detection/selected', $edit, t('Save configuration'));
132 'language_negotiation' => [LanguageNegotiationSelected::METHOD_ID],
133 'path' => 'admin/config',
134 'expect' => $language_string,
135 'expected_method_id' => LanguageNegotiationSelected::METHOD_ID,
136 'http_header' => $http_header_browser_fallback,
137 'message' => 'SELECTED: UI language is switched based on selected language.',
139 $this->doRunTest($test);
141 // An invalid language is selected.
142 $this->config('language.negotiation')->set('selected_langcode', NULL)->save();
144 'language_negotiation' => [LanguageNegotiationSelected::METHOD_ID],
145 'path' => 'admin/config',
146 'expect' => $default_string,
147 'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
148 'http_header' => $http_header_browser_fallback,
149 'message' => 'SELECTED > DEFAULT: UI language is switched based on selected language.',
151 $this->doRunTest($test);
153 // No selected language is available.
154 $this->config('language.negotiation')->set('selected_langcode', $langcode_unknown)->save();
156 'language_negotiation' => [LanguageNegotiationSelected::METHOD_ID],
157 'path' => 'admin/config',
158 'expect' => $default_string,
159 'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
160 'http_header' => $http_header_browser_fallback,
161 'message' => 'SELECTED > DEFAULT: UI language is switched based on selected language.',
163 $this->doRunTest($test);
166 // Default, browser preference should have no influence.
168 'language_negotiation' => [LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
169 'path' => 'admin/config',
170 'expect' => $default_string,
171 'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
172 'http_header' => $http_header_browser_fallback,
173 'message' => 'URL (PATH) > DEFAULT: no language prefix, UI language is default and the browser language preference setting is not used.',
177 'language_negotiation' => [LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
178 'path' => "$langcode/admin/config",
179 'expect' => $language_string,
180 'expected_method_id' => LanguageNegotiationUrl::METHOD_ID,
181 'http_header' => $http_header_browser_fallback,
182 'message' => 'URL (PATH) > DEFAULT: with language prefix, UI language is switched based on path prefix',
184 // Default, go by browser preference.
186 'language_negotiation' => [LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationBrowser::METHOD_ID],
187 'path' => 'admin/config',
188 'expect' => $language_browser_fallback_string,
189 'expected_method_id' => LanguageNegotiationBrowser::METHOD_ID,
190 'http_header' => $http_header_browser_fallback,
191 'message' => 'URL (PATH) > BROWSER: no language prefix, UI language is determined by browser language preference',
193 // Prefix, switch to the language.
195 'language_negotiation' => [LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationBrowser::METHOD_ID],
196 'path' => "$langcode/admin/config",
197 'expect' => $language_string,
198 'expected_method_id' => LanguageNegotiationUrl::METHOD_ID,
199 'http_header' => $http_header_browser_fallback,
200 'message' => 'URL (PATH) > BROWSER: with language prefix, UI language is based on path prefix',
202 // Default, browser language preference is not one of site's lang.
204 'language_negotiation' => [LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationBrowser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
205 'path' => 'admin/config',
206 'expect' => $default_string,
207 'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
208 'http_header' => $http_header_blah,
209 'message' => 'URL (PATH) > BROWSER > DEFAULT: no language prefix and browser language preference set to unknown language should use default language',
213 foreach ($tests as $test) {
214 $this->doRunTest($test);
217 // Unknown language prefix should return 404.
218 $definitions = \Drupal::languageManager()->getNegotiator()->getNegotiationMethods();
219 // Enable only methods, which are either not limited to a specific language
220 // type or are supporting the interface language type.
221 $language_interface_method_definitions = array_filter($definitions, function ($method_definition) {
222 return !isset($method_definition['types']) || (isset($method_definition['types']) && in_array(LanguageInterface::TYPE_INTERFACE, $method_definition['types']));
224 $this->config('language.types')
225 ->set('negotiation.' . LanguageInterface::TYPE_INTERFACE . '.enabled', array_flip(array_keys($language_interface_method_definitions)))
227 $this->drupalGet("$langcode_unknown/admin/config", [], $http_header_browser_fallback);
228 $this->assertResponse(404, "Unknown language path prefix should return 404");
230 // Set preferred langcode for user to NULL.
231 $account = $this->loggedInUser;
232 $account->preferred_langcode = NULL;
236 'language_negotiation' => [LanguageNegotiationUser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
237 'path' => 'admin/config',
238 'expect' => $default_string,
239 'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
241 'message' => 'USER > DEFAULT: no preferred user language setting, the UI language is default',
243 $this->doRunTest($test);
245 // Set preferred langcode for user to unknown language.
246 $account = $this->loggedInUser;
247 $account->preferred_langcode = $langcode_unknown;
251 'language_negotiation' => [LanguageNegotiationUser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
252 'path' => 'admin/config',
253 'expect' => $default_string,
254 'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
256 'message' => 'USER > DEFAULT: invalid preferred user language setting, the UI language is default',
258 $this->doRunTest($test);
260 // Set preferred langcode for user to non default.
261 $account->preferred_langcode = $langcode;
265 'language_negotiation' => [LanguageNegotiationUser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
266 'path' => 'admin/config',
267 'expect' => $language_string,
268 'expected_method_id' => LanguageNegotiationUser::METHOD_ID,
270 'message' => 'USER > DEFAULT: defined preferred user language setting, the UI language is based on user setting',
272 $this->doRunTest($test);
274 // Set preferred admin langcode for user to NULL.
275 $account->preferred_admin_langcode = NULL;
279 'language_negotiation' => [LanguageNegotiationUserAdmin::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
280 'path' => 'admin/config',
281 'expect' => $default_string,
282 'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
284 'message' => 'USER ADMIN > DEFAULT: no preferred user admin language setting, the UI language is default',
286 $this->doRunTest($test);
288 // Set preferred admin langcode for user to unknown language.
289 $account->preferred_admin_langcode = $langcode_unknown;
293 'language_negotiation' => [LanguageNegotiationUserAdmin::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
294 'path' => 'admin/config',
295 'expect' => $default_string,
296 'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
298 'message' => 'USER ADMIN > DEFAULT: invalid preferred user admin language setting, the UI language is default',
300 $this->doRunTest($test);
302 // Set preferred admin langcode for user to non default.
303 $account->preferred_admin_langcode = $langcode;
307 'language_negotiation' => [LanguageNegotiationUserAdmin::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
308 'path' => 'admin/config',
309 'expect' => $language_string,
310 'expected_method_id' => LanguageNegotiationUserAdmin::METHOD_ID,
312 'message' => 'USER ADMIN > DEFAULT: defined preferred user admin language setting, the UI language is based on user setting',
314 $this->doRunTest($test);
316 // Go by session preference.
317 $language_negotiation_session_param = $this->randomMachineName();
318 $edit = ['language_negotiation_session_param' => $language_negotiation_session_param];
319 $this->drupalPostForm('admin/config/regional/language/detection/session', $edit, t('Save configuration'));
322 'language_negotiation' => [LanguageNegotiationSession::METHOD_ID],
323 'path' => "admin/config",
324 'expect' => $default_string,
325 'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
326 'http_header' => $http_header_browser_fallback,
327 'message' => 'SESSION > DEFAULT: no language given, the UI language is default',
330 'language_negotiation' => [LanguageNegotiationSession::METHOD_ID],
331 'path' => 'admin/config',
332 'path_options' => ['query' => [$language_negotiation_session_param => $langcode]],
333 'expect' => $language_string,
334 'expected_method_id' => LanguageNegotiationSession::METHOD_ID,
335 'http_header' => $http_header_browser_fallback,
336 'message' => 'SESSION > DEFAULT: language given, UI language is determined by session language preference',
339 foreach ($tests as $test) {
340 $this->doRunTest($test);
344 protected function doRunTest($test) {
345 $test += ['path_options' => []];
346 if (!empty($test['language_negotiation'])) {
347 $method_weights = array_flip($test['language_negotiation']);
348 $this->container->get('language_negotiator')->saveConfiguration(LanguageInterface::TYPE_INTERFACE, $method_weights);
350 if (!empty($test['language_negotiation_url_part'])) {
351 $this->config('language.negotiation')
352 ->set('url.source', $test['language_negotiation_url_part'])
355 if (!empty($test['language_test_domain'])) {
356 \Drupal::state()->set('language_test.domain', $test['language_test_domain']);
358 $this->container->get('language_manager')->reset();
359 $this->drupalGet($test['path'], $test['path_options'], $test['http_header']);
360 $this->assertText($test['expect'], $test['message']);
361 $this->assertText(t('Language negotiation method: @name', ['@name' => $test['expected_method_id']]));
365 * Test URL language detection when the requested URL has no language.
367 public function testUrlLanguageFallback() {
368 // Add the Italian language.
369 $langcode_browser_fallback = 'it';
370 ConfigurableLanguage::createFromLangcode($langcode_browser_fallback)->save();
371 $languages = $this->container->get('language_manager')->getLanguages();
373 // Enable the path prefix for the default language: this way any unprefixed
374 // URL must have a valid fallback value.
375 $edit = ['prefix[en]' => 'en'];
376 $this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
378 // Enable browser and URL language detection.
380 'language_interface[enabled][language-browser]' => TRUE,
381 'language_interface[enabled][language-url]' => TRUE,
382 'language_interface[weight][language-browser]' => -8,
383 'language_interface[weight][language-url]' => -10,
385 $this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
386 $this->drupalGet('admin/config/regional/language/detection');
388 // Enable the language switcher block.
389 $this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_INTERFACE, ['id' => 'test_language_block']);
391 // Log out, because for anonymous users, the "active" class is set by PHP
392 // (which means we can easily test it here), whereas for authenticated users
393 // it is set by JavaScript.
394 $this->drupalLogout();
396 // Place a site branding block in the header region.
397 $this->drupalPlaceBlock('system_branding_block', ['region' => 'header']);
399 // Access the front page without specifying any valid URL language prefix
400 // and having as browser language preference a non-default language.
401 $http_header = ["Accept-Language: $langcode_browser_fallback;q=1"];
402 $language = new Language(['id' => '']);
403 $this->drupalGet('', ['language' => $language], $http_header);
405 // Check that the language switcher active link matches the given browser
407 $args = [':id' => 'block-test-language-block', ':url' => \Drupal::url('<front>') . $langcode_browser_fallback];
408 $fields = $this->xpath('//div[@id=:id]//a[@class="language-link is-active" and starts-with(@href, :url)]', $args);
409 $this->assertTrue($fields[0] == $languages[$langcode_browser_fallback]->getName(), 'The browser language is the URL active language');
411 // Check that URLs are rewritten using the given browser language.
412 $fields = $this->xpath('//div[@class="site-name"]/a[@rel="home" and @href=:url]', $args);
413 $this->assertTrue($fields[0] == 'Drupal', 'URLs are rewritten using the browser language.');
417 * Tests URL handling when separate domains are used for multiple languages.
419 public function testLanguageDomain() {
422 // Get the current host URI we're running on.
423 $base_url_host = parse_url($base_url, PHP_URL_HOST);
425 // Add the Italian language.
426 ConfigurableLanguage::createFromLangcode('it')->save();
428 $languages = $this->container->get('language_manager')->getLanguages();
430 // Enable browser and URL language detection.
432 'language_interface[enabled][language-url]' => TRUE,
433 'language_interface[weight][language-url]' => -10,
435 $this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
437 // Do not allow blank domain.
439 'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
442 $this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
443 $this->assertText('The domain may not be left blank for English', 'The form does not allow blank domains.');
444 $this->rebuildContainer();
446 // Change the domain for the Italian language.
448 'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
449 'domain[en]' => $base_url_host,
450 'domain[it]' => 'it.example.com',
452 $this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
453 $this->assertText('The configuration options have been saved', 'Domain configuration is saved.');
454 $this->rebuildContainer();
456 // Try to use an invalid domain.
458 'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
459 'domain[en]' => $base_url_host,
460 'domain[it]' => 'it.example.com/',
462 $this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
463 $this->assertRaw(t('The domain for %language may only contain the domain name, not a trailing slash, protocol and/or port.', ['%language' => 'Italian']));
465 // Build the link we're going to test.
466 $link = 'it.example.com' . rtrim(base_path(), '/') . '/admin';
468 // Test URL in another language: http://it.example.com/admin.
469 // Base path gives problems on the testbot, so $correct_link is hard-coded.
470 // @see UrlAlterFunctionalTest::assertUrlOutboundAlter (path.test).
471 $italian_url = Url::fromRoute('system.admin', [], ['language' => $languages['it']])->toString();
472 $url_scheme = \Drupal::request()->isSecure() ? 'https://' : 'http://';
473 $correct_link = $url_scheme . $link;
474 $this->assertEqual($italian_url, $correct_link, format_string('The right URL (@url) in accordance with the chosen language', ['@url' => $italian_url]));
476 // Test HTTPS via options.
477 $italian_url = Url::fromRoute('system.admin', [], ['https' => TRUE, 'language' => $languages['it']])->toString();
478 $correct_link = 'https://' . $link;
479 $this->assertTrue($italian_url == $correct_link, format_string('The right HTTPS URL (via options) (@url) in accordance with the chosen language', ['@url' => $italian_url]));
481 // Test HTTPS via current URL scheme.
482 $request = Request::create('', 'GET', [], [], [], ['HTTPS' => 'on']);
483 $this->container->get('request_stack')->push($request);
484 $italian_url = Url::fromRoute('system.admin', [], ['language' => $languages['it']])->toString();
485 $correct_link = 'https://' . $link;
486 $this->assertTrue($italian_url == $correct_link, format_string('The right URL (via current URL scheme) (@url) in accordance with the chosen language', ['@url' => $italian_url]));
490 * Tests persistence of negotiation settings for the content language type.
492 public function testContentCustomization() {
493 // Customize content language settings from their defaults.
495 'language_content[configurable]' => TRUE,
496 'language_content[enabled][language-url]' => FALSE,
497 'language_content[enabled][language-session]' => TRUE,
499 $this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
501 // Check if configurability persisted.
502 $config = $this->config('language.types');
503 $this->assertTrue(in_array('language_interface', $config->get('configurable')), 'Interface language is configurable.');
504 $this->assertTrue(in_array('language_content', $config->get('configurable')), 'Content language is configurable.');
506 // Ensure configuration was saved.
507 $this->assertFalse(array_key_exists('language-url', $config->get('negotiation.language_content.enabled')), 'URL negotiation is not enabled for content.');
508 $this->assertTrue(array_key_exists('language-session', $config->get('negotiation.language_content.enabled')), 'Session negotiation is enabled for content.');
512 * Tests if the language switcher block gets deleted when a language type has been made not configurable.
514 public function testDisableLanguageSwitcher() {
515 $block_id = 'test_language_block';
517 // Enable the language switcher block.
518 $this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_CONTENT, ['id' => $block_id]);
520 // Check if the language switcher block has been created.
521 $block = Block::load($block_id);
522 $this->assertTrue($block, 'Language switcher block was created.');
524 // Make sure language_content is not configurable.
526 'language_content[configurable]' => FALSE,
528 $this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
529 $this->assertResponse(200);
531 // Check if the language switcher block has been removed.
532 $block = Block::load($block_id);
533 $this->assertFalse($block, 'Language switcher block was removed.');