Security update for Core, with self-updated composer
[yaffs-website] / web / core / modules / config_translation / tests / src / Functional / ConfigTranslationUiTest.php
1 <?php
2
3 namespace Drupal\Tests\config_translation\Functional;
4
5 use Behat\Mink\Element\NodeElement;
6 use Drupal\Component\Utility\Html;
7 use Drupal\Component\Utility\SafeMarkup;
8 use Drupal\Component\Utility\Unicode;
9 use Drupal\Core\Language\Language;
10 use Drupal\Core\Language\LanguageInterface;
11 use Drupal\Core\Test\AssertMailTrait;
12 use Drupal\field\Entity\FieldConfig;
13 use Drupal\field\Entity\FieldStorageConfig;
14 use Drupal\filter\Entity\FilterFormat;
15 use Drupal\language\Entity\ConfigurableLanguage;
16 use Drupal\node\Entity\NodeType;
17 use Drupal\Tests\BrowserTestBase;
18
19 /**
20  * Translate settings and entities to various languages.
21  *
22  * @group config_translation
23  */
24 class ConfigTranslationUiTest extends BrowserTestBase {
25
26   use AssertMailTrait;
27
28   /**
29    * Modules to enable.
30    *
31    * @var array
32    */
33   public static $modules = [
34     'block',
35     'config_translation',
36     'config_translation_test',
37     'contact',
38     'contact_test',
39     'contextual',
40     'entity_test',
41     'field_test',
42     'field_ui',
43     'filter',
44     'filter_test',
45     'node',
46     'views',
47     'views_ui',
48   ];
49
50   /**
51    * Languages to enable.
52    *
53    * @var array
54    */
55   protected $langcodes = ['fr', 'ta'];
56
57   /**
58    * Administrator user for tests.
59    *
60    * @var \Drupal\user\UserInterface
61    */
62   protected $adminUser;
63
64   /**
65    * Translator user for tests.
66    *
67    * @var \Drupal\user\UserInterface
68    */
69   protected $translatorUser;
70
71   /**
72    * String translation storage object.
73    *
74    * @var \Drupal\locale\StringStorageInterface
75    */
76   protected $localeStorage;
77
78   protected function setUp() {
79     parent::setUp();
80     $translator_permissions = [
81       'translate configuration',
82     ];
83
84     /** @var \Drupal\filter\FilterFormatInterface $filter_test_format */
85     $filter_test_format = FilterFormat::load('filter_test');
86     /** @var \Drupal\filter\FilterFormatInterface $filtered_html_format */
87     $filtered_html_format = FilterFormat::load('filtered_html');
88     /** @var \Drupal\filter\FilterFormatInterface $full_html_format */
89     $full_html_format = FilterFormat::load('full_html');
90
91     $admin_permissions = array_merge(
92       $translator_permissions,
93       [
94         'administer languages',
95         'administer site configuration',
96         'link to any page',
97         'administer contact forms',
98         'administer filters',
99         $filtered_html_format->getPermissionName(),
100         $full_html_format->getPermissionName(),
101         $filter_test_format->getPermissionName(),
102         'access site-wide contact form',
103         'access contextual links',
104         'administer views',
105         'administer account settings',
106         'administer themes',
107         'bypass node access',
108         'administer content types',
109         'translate interface',
110       ]
111     );
112     // Create and log in user.
113     $this->translatorUser = $this->drupalCreateUser($translator_permissions);
114     $this->adminUser = $this->drupalCreateUser($admin_permissions);
115
116     // Add languages.
117     foreach ($this->langcodes as $langcode) {
118       ConfigurableLanguage::createFromLangcode($langcode)->save();
119     }
120     $this->localeStorage = $this->container->get('locale.storage');
121     $this->drupalPlaceBlock('local_tasks_block');
122     $this->drupalPlaceBlock('page_title_block');
123   }
124
125   /**
126    * Tests the site information translation interface.
127    */
128   public function testSiteInformationTranslationUi() {
129     $this->drupalLogin($this->adminUser);
130
131     $site_name = 'Name of the site for testing configuration translation';
132     $site_slogan = 'Site slogan for testing configuration translation';
133     $site_name_label = 'Site name';
134     $fr_site_name = 'Nom du site pour tester la configuration traduction';
135     $fr_site_slogan = 'Slogan du site pour tester la traduction de configuration';
136     $fr_site_name_label = 'LibellĂ© du champ "Nom du site"';
137     $translation_base_url = 'admin/config/system/site-information/translate';
138
139     // Set site name and slogan for default language.
140     $this->setSiteInformation($site_name, $site_slogan);
141
142     $this->drupalGet('admin/config/system/site-information');
143     // Check translation tab exist.
144     $this->assertLinkByHref($translation_base_url);
145
146     $this->drupalGet($translation_base_url);
147
148     // Check that the 'Edit' link in the source language links back to the
149     // original form.
150     $this->clickLink(t('Edit'));
151     // Also check that saving the form leads back to the translation overview.
152     $this->drupalPostForm(NULL, [], t('Save configuration'));
153     $this->assertUrl($translation_base_url);
154
155     // Check 'Add' link of French to visit add page.
156     $this->assertLinkByHref("$translation_base_url/fr/add");
157     $this->clickLink(t('Add'));
158
159     // Make sure original text is present on this page.
160     $this->assertRaw($site_name);
161     $this->assertRaw($site_slogan);
162
163     // Update site name and slogan for French.
164     $edit = [
165       'translation[config_names][system.site][name]' => $fr_site_name,
166       'translation[config_names][system.site][slogan]' => $fr_site_slogan,
167     ];
168
169     $this->drupalPostForm("$translation_base_url/fr/add", $edit, t('Save translation'));
170     $this->assertRaw(t('Successfully saved @language translation.', ['@language' => 'French']));
171
172     // Check for edit, delete links (and no 'add' link) for French language.
173     $this->assertNoLinkByHref("$translation_base_url/fr/add");
174     $this->assertLinkByHref("$translation_base_url/fr/edit");
175     $this->assertLinkByHref("$translation_base_url/fr/delete");
176
177     // Check translation saved proper.
178     $this->drupalGet("$translation_base_url/fr/edit");
179     $this->assertFieldByName('translation[config_names][system.site][name]', $fr_site_name);
180     $this->assertFieldByName('translation[config_names][system.site][slogan]', $fr_site_slogan);
181
182     // Place branding block with site name and slogan into header region.
183     $this->drupalPlaceBlock('system_branding_block', ['region' => 'header']);
184
185     // Check French translation of site name and slogan are in place.
186     $this->drupalGet('fr');
187     $this->assertRaw($fr_site_name);
188     $this->assertRaw($fr_site_slogan);
189
190     // Visit French site to ensure base language string present as source.
191     $this->drupalGet("fr/$translation_base_url/fr/edit");
192     $this->assertText($site_name);
193     $this->assertText($site_slogan);
194
195     // Translate 'Site name' label in French.
196     $search = [
197       'string' => $site_name_label,
198       'langcode' => 'fr',
199       'translation' => 'untranslated',
200     ];
201     $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
202
203     $textarea = current($this->xpath('//textarea'));
204     $lid = $textarea->getAttribute('name');
205     $edit = [
206       $lid => $fr_site_name_label,
207     ];
208     $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
209
210     // Ensure that the label is in French (and not in English).
211     $this->drupalGet("fr/$translation_base_url/fr/edit");
212     $this->assertText($fr_site_name_label);
213     $this->assertNoText($site_name_label);
214
215     // Ensure that the label is also in French (and not in English)
216     // when editing another language with the interface in French.
217     $this->drupalGet("fr/$translation_base_url/ta/edit");
218     $this->assertText($fr_site_name_label);
219     $this->assertNoText($site_name_label);
220
221     // Ensure that the label is not translated when the interface is in English.
222     $this->drupalGet("$translation_base_url/fr/edit");
223     $this->assertText($site_name_label);
224     $this->assertNoText($fr_site_name_label);
225   }
226
227   /**
228    * Tests the site information translation interface.
229    */
230   public function testSourceValueDuplicateSave() {
231     $this->drupalLogin($this->adminUser);
232
233     $site_name = 'Site name for testing configuration translation';
234     $site_slogan = 'Site slogan for testing configuration translation';
235     $translation_base_url = 'admin/config/system/site-information/translate';
236     $this->setSiteInformation($site_name, $site_slogan);
237
238     $this->drupalGet($translation_base_url);
239
240     // Case 1: Update new value for site slogan and site name.
241     $edit = [
242       'translation[config_names][system.site][name]' => 'FR ' . $site_name,
243       'translation[config_names][system.site][slogan]' => 'FR ' . $site_slogan,
244     ];
245     // First time, no overrides, so just Add link.
246     $this->drupalPostForm("$translation_base_url/fr/add", $edit, t('Save translation'));
247
248     // Read overridden file from active config.
249     $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'system.site');
250
251     // Expect both name and slogan in language specific file.
252     $expected = [
253       'name' => 'FR ' . $site_name,
254       'slogan' => 'FR ' . $site_slogan,
255     ];
256     $this->assertEqual($expected, $override->get());
257
258     // Case 2: Update new value for site slogan and default value for site name.
259     $this->drupalGet("$translation_base_url/fr/edit");
260     // Assert that the language configuration does not leak outside of the
261     // translation form into the actual site name and slogan.
262     $this->assertNoText('FR ' . $site_name);
263     $this->assertNoText('FR ' . $site_slogan);
264     $edit = [
265       'translation[config_names][system.site][name]' => $site_name,
266       'translation[config_names][system.site][slogan]' => 'FR ' . $site_slogan,
267     ];
268     $this->drupalPostForm(NULL, $edit, t('Save translation'));
269     $this->assertRaw(t('Successfully updated @language translation.', ['@language' => 'French']));
270     $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'system.site');
271
272     // Expect only slogan in language specific file.
273     $expected = 'FR ' . $site_slogan;
274     $this->assertEqual($expected, $override->get('slogan'));
275
276     // Case 3: Keep default value for site name and slogan.
277     $this->drupalGet("$translation_base_url/fr/edit");
278     $this->assertNoText('FR ' . $site_slogan);
279     $edit = [
280       'translation[config_names][system.site][name]' => $site_name,
281       'translation[config_names][system.site][slogan]' => $site_slogan,
282     ];
283     $this->drupalPostForm(NULL, $edit, t('Save translation'));
284     $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'system.site');
285
286     // Expect no language specific file.
287     $this->assertTrue($override->isNew());
288
289     // Check configuration page with translator user. Should have no access.
290     $this->drupalLogout();
291     $this->drupalLogin($this->translatorUser);
292     $this->drupalGet('admin/config/system/site-information');
293     $this->assertResponse(403);
294
295     // While translator can access the translation page, the edit link is not
296     // present due to lack of permissions.
297     $this->drupalGet($translation_base_url);
298     $this->assertNoLink(t('Edit'));
299
300     // Check 'Add' link for French.
301     $this->assertLinkByHref("$translation_base_url/fr/add");
302   }
303
304   /**
305    * Tests the contact form translation.
306    */
307   public function testContactConfigEntityTranslation() {
308     $this->drupalLogin($this->adminUser);
309
310     $this->drupalGet('admin/structure/contact');
311
312     // Check for default contact form configuration entity from Contact module.
313     $this->assertLinkByHref('admin/structure/contact/manage/feedback');
314
315     // Save default language configuration.
316     $label = 'Send your feedback';
317     $edit = [
318       'label' => $label,
319       'recipients' => 'sales@example.com,support@example.com',
320       'reply' => 'Thank you for your mail',
321     ];
322     $this->drupalPostForm('admin/structure/contact/manage/feedback', $edit, t('Save'));
323
324     // Ensure translation link is present.
325     $translation_base_url = 'admin/structure/contact/manage/feedback/translate';
326     $this->assertLinkByHref($translation_base_url);
327
328     // Make sure translate tab is present.
329     $this->drupalGet('admin/structure/contact/manage/feedback');
330     $this->assertLink(t('Translate @type', ['@type' => 'contact form']));
331
332     // Visit the form to confirm the changes.
333     $this->drupalGet('contact/feedback');
334     $this->assertText($label);
335
336     foreach ($this->langcodes as $langcode) {
337       $this->drupalGet($translation_base_url);
338       $this->assertLink(t('Translate @type', ['@type' => 'contact form']));
339
340       // 'Add' link should be present for $langcode translation.
341       $translation_page_url = "$translation_base_url/$langcode/add";
342       $this->assertLinkByHref($translation_page_url);
343
344       // Make sure original text is present on this page.
345       $this->drupalGet($translation_page_url);
346       $this->assertText($label);
347
348       // Update translatable fields.
349       $edit = [
350         'translation[config_names][contact.form.feedback][label]' => 'Website feedback - ' . $langcode,
351         'translation[config_names][contact.form.feedback][reply]' => 'Thank you for your mail - ' . $langcode,
352       ];
353
354       // Save language specific version of form.
355       $this->drupalPostForm($translation_page_url, $edit, t('Save translation'));
356
357       // Expect translated values in language specific file.
358       $override = \Drupal::languageManager()->getLanguageConfigOverride($langcode, 'contact.form.feedback');
359       $expected = [
360         'label' => 'Website feedback - ' . $langcode,
361         'reply' => 'Thank you for your mail - ' . $langcode,
362       ];
363       $this->assertEqual($expected, $override->get());
364
365       // Check for edit, delete links (and no 'add' link) for $langcode.
366       $this->assertNoLinkByHref("$translation_base_url/$langcode/add");
367       $this->assertLinkByHref("$translation_base_url/$langcode/edit");
368       $this->assertLinkByHref("$translation_base_url/$langcode/delete");
369
370       // Visit language specific version of form to check label.
371       $this->drupalGet($langcode . '/contact/feedback');
372       $this->assertText('Website feedback - ' . $langcode);
373
374       // Submit feedback.
375       $edit = [
376         'subject[0][value]' => 'Test subject',
377         'message[0][value]' => 'Test message',
378       ];
379       $this->drupalPostForm(NULL, $edit, t('Send message'));
380     }
381
382     // Now that all language translations are present, check translation and
383     // original text all appear in any translated page on the translation
384     // forms.
385     foreach ($this->langcodes as $langcode) {
386       $langcode_prefixes = array_merge([''], $this->langcodes);
387       foreach ($langcode_prefixes as $langcode_prefix) {
388         $this->drupalGet(ltrim("$langcode_prefix/$translation_base_url/$langcode/edit", '/'));
389         $this->assertFieldByName('translation[config_names][contact.form.feedback][label]', 'Website feedback - ' . $langcode);
390         $this->assertText($label);
391       }
392     }
393
394     // We get all emails so no need to check inside the loop.
395     $captured_emails = $this->getMails();
396
397     // Check language specific auto reply text in email body.
398     foreach ($captured_emails as $email) {
399       if ($email['id'] == 'contact_page_autoreply') {
400         // Trim because we get an added newline for the body.
401         $this->assertEqual(trim($email['body']), 'Thank you for your mail - ' . $email['langcode']);
402       }
403     }
404
405     // Test that delete links work and operations perform properly.
406     foreach ($this->langcodes as $langcode) {
407       $replacements = ['%label' => t('@label @entity_type', ['@label' => $label, '@entity_type' => Unicode::strtolower(t('Contact form'))]), '@language' => \Drupal::languageManager()->getLanguage($langcode)->getName()];
408
409       $this->drupalGet("$translation_base_url/$langcode/delete");
410       $this->assertRaw(t('Are you sure you want to delete the @language translation of %label?', $replacements));
411       // Assert link back to list page to cancel delete is present.
412       $this->assertLinkByHref($translation_base_url);
413
414       $this->drupalPostForm(NULL, [], t('Delete'));
415       $this->assertRaw(t('@language translation of %label was deleted', $replacements));
416       $this->assertLinkByHref("$translation_base_url/$langcode/add");
417       $this->assertNoLinkByHref("translation_base_url/$langcode/edit");
418       $this->assertNoLinkByHref("$translation_base_url/$langcode/delete");
419
420       // Expect no language specific file present anymore.
421       $override = \Drupal::languageManager()->getLanguageConfigOverride($langcode, 'contact.form.feedback');
422       $this->assertTrue($override->isNew());
423     }
424
425     // Check configuration page with translator user. Should have no access.
426     $this->drupalLogout();
427     $this->drupalLogin($this->translatorUser);
428     $this->drupalGet('admin/structure/contact/manage/feedback');
429     $this->assertResponse(403);
430
431     // While translator can access the translation page, the edit link is not
432     // present due to lack of permissions.
433     $this->drupalGet($translation_base_url);
434     $this->assertNoLink(t('Edit'));
435
436     // Check 'Add' link for French.
437     $this->assertLinkByHref("$translation_base_url/fr/add");
438   }
439
440   /**
441    * Tests date format translation.
442    */
443   public function testDateFormatTranslation() {
444     $this->drupalLogin($this->adminUser);
445
446     $this->drupalGet('admin/config/regional/date-time');
447
448     // Check for medium format.
449     $this->assertLinkByHref('admin/config/regional/date-time/formats/manage/medium');
450
451     // Save default language configuration for a new format.
452     $edit = [
453       'label' => 'Custom medium date',
454       'id' => 'custom_medium',
455       'date_format_pattern' => 'Y. m. d. H:i',
456     ];
457     $this->drupalPostForm('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
458
459     // Test translating a default shipped format and our custom format.
460     $formats = [
461       'medium' => 'Default medium date',
462       'custom_medium' => 'Custom medium date',
463     ];
464     foreach ($formats as $id => $label) {
465       $translation_base_url = 'admin/config/regional/date-time/formats/manage/' . $id . '/translate';
466
467       $this->drupalGet($translation_base_url);
468
469       // 'Add' link should be present for French translation.
470       $translation_page_url = "$translation_base_url/fr/add";
471       $this->assertLinkByHref($translation_page_url);
472
473       // Make sure original text is present on this page.
474       $this->drupalGet($translation_page_url);
475       $this->assertText($label);
476
477       // Make sure that the date library is added.
478       $this->assertRaw('core/modules/system/js/system.date.js');
479
480       // Update translatable fields.
481       $edit = [
482         'translation[config_names][core.date_format.' . $id . '][label]' => $id . ' - FR',
483         'translation[config_names][core.date_format.' . $id . '][pattern]' => 'D',
484       ];
485
486       // Save language specific version of form.
487       $this->drupalPostForm($translation_page_url, $edit, t('Save translation'));
488
489       // Get translation and check we've got the right value.
490       $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'core.date_format.' . $id);
491       $expected = [
492         'label' => $id . ' - FR',
493         'pattern' => 'D',
494       ];
495       $this->assertEqual($expected, $override->get());
496
497       // Formatting the date 8 / 27 / 1985 @ 13:37 EST with pattern D should
498       // display "Tue".
499       $formatted_date = format_date(494015820, $id, NULL, 'America/New_York', 'fr');
500       $this->assertEqual($formatted_date, 'Tue', 'Got the right formatted date using the date format translation pattern.');
501     }
502   }
503
504   /**
505    * Tests the account settings translation interface.
506    *
507    * This is the only special case so far where we have multiple configuration
508    * names involved building up one configuration translation form. Test that
509    * the translations are saved for all configuration names properly.
510    */
511   public function testAccountSettingsConfigurationTranslation() {
512     $this->drupalLogin($this->adminUser);
513
514     $this->drupalGet('admin/config/people/accounts');
515     $this->assertLink(t('Translate @type', ['@type' => 'account settings']));
516
517     $this->drupalGet('admin/config/people/accounts/translate');
518     $this->assertLink(t('Translate @type', ['@type' => 'account settings']));
519     $this->assertLinkByHref('admin/config/people/accounts/translate/fr/add');
520
521     // Update account settings fields for French.
522     $edit = [
523       'translation[config_names][user.settings][anonymous]' => 'Anonyme',
524       'translation[config_names][user.mail][status_blocked][subject]' => 'Testing, your account is blocked.',
525       'translation[config_names][user.mail][status_blocked][body]' => 'Testing account blocked body.',
526     ];
527
528     $this->drupalPostForm('admin/config/people/accounts/translate/fr/add', $edit, t('Save translation'));
529
530     // Make sure the changes are saved and loaded back properly.
531     $this->drupalGet('admin/config/people/accounts/translate/fr/edit');
532     foreach ($edit as $key => $value) {
533       // Check the translations appear in the right field type as well.
534       $xpath = '//' . (strpos($key, '[body]') ? 'textarea' : 'input') . '[@name="' . $key . '"]';
535       $this->assertFieldByXPath($xpath, $value);
536     }
537     // Check that labels for email settings appear.
538     $this->assertText(t('Account cancellation confirmation'));
539     $this->assertText(t('Password recovery'));
540   }
541
542   /**
543    * Tests source and target language edge cases.
544    */
545   public function testSourceAndTargetLanguage() {
546     $this->drupalLogin($this->adminUser);
547
548     // Loading translation page for not-specified language (und)
549     // should return 403.
550     $this->drupalGet('admin/config/system/site-information/translate/und/add');
551     $this->assertResponse(403);
552
553     // Check the source language doesn't have 'Add' or 'Delete' link and
554     // make sure source language edit goes to original configuration page
555     // not the translation specific edit page.
556     $this->drupalGet('admin/config/system/site-information/translate');
557     $this->assertNoLinkByHref('admin/config/system/site-information/translate/en/edit');
558     $this->assertNoLinkByHref('admin/config/system/site-information/translate/en/add');
559     $this->assertNoLinkByHref('admin/config/system/site-information/translate/en/delete');
560     $this->assertLinkByHref('admin/config/system/site-information');
561
562     // Translation addition to source language should return 403.
563     $this->drupalGet('admin/config/system/site-information/translate/en/add');
564     $this->assertResponse(403);
565
566     // Translation editing in source language should return 403.
567     $this->drupalGet('admin/config/system/site-information/translate/en/edit');
568     $this->assertResponse(403);
569
570     // Translation deletion in source language should return 403.
571     $this->drupalGet('admin/config/system/site-information/translate/en/delete');
572     $this->assertResponse(403);
573
574     // Set default language of site information to not-specified language (und).
575     $this->config('system.site')
576       ->set('langcode', LanguageInterface::LANGCODE_NOT_SPECIFIED)
577       ->save();
578
579     // Make sure translation tab does not exist on the configuration page.
580     $this->drupalGet('admin/config/system/site-information');
581     $this->assertNoLinkByHref('admin/config/system/site-information/translate');
582
583     // If source language is not specified, translation page should be 403.
584     $this->drupalGet('admin/config/system/site-information/translate');
585     $this->assertResponse(403);
586   }
587
588   /**
589    * Tests the views translation interface.
590    */
591   public function testViewsTranslationUI() {
592     $this->drupalLogin($this->adminUser);
593
594     $description = 'All content promoted to the front page.';
595     $human_readable_name = 'Frontpage';
596     $display_settings_master = 'Master';
597     $display_options_master = '(Empty)';
598     $translation_base_url = 'admin/structure/views/view/frontpage/translate';
599
600     $this->drupalGet($translation_base_url);
601
602     // Check 'Add' link of French to visit add page.
603     $this->assertLinkByHref("$translation_base_url/fr/add");
604     $this->clickLink(t('Add'));
605
606     // Make sure original text is present on this page.
607     $this->assertRaw($description);
608     $this->assertRaw($human_readable_name);
609
610     // Update Views Fields for French.
611     $edit = [
612       'translation[config_names][views.view.frontpage][description]' => $description . " FR",
613       'translation[config_names][views.view.frontpage][label]' => $human_readable_name . " FR",
614       'translation[config_names][views.view.frontpage][display][default][display_title]' => $display_settings_master . " FR",
615       'translation[config_names][views.view.frontpage][display][default][display_options][title]' => $display_options_master . " FR",
616     ];
617     $this->drupalPostForm("$translation_base_url/fr/add", $edit, t('Save translation'));
618     $this->assertRaw(t('Successfully saved @language translation.', ['@language' => 'French']));
619
620     // Check for edit, delete links (and no 'add' link) for French language.
621     $this->assertNoLinkByHref("$translation_base_url/fr/add");
622     $this->assertLinkByHref("$translation_base_url/fr/edit");
623     $this->assertLinkByHref("$translation_base_url/fr/delete");
624
625     // Check translation saved proper.
626     $this->drupalGet("$translation_base_url/fr/edit");
627     $this->assertFieldByName('translation[config_names][views.view.frontpage][description]', $description . " FR");
628     $this->assertFieldByName('translation[config_names][views.view.frontpage][label]', $human_readable_name . " FR");
629     $this->assertFieldByName('translation[config_names][views.view.frontpage][display][default][display_title]', $display_settings_master . " FR");
630     $this->assertFieldByName('translation[config_names][views.view.frontpage][display][default][display_options][title]', $display_options_master . " FR");
631   }
632
633   /**
634    * Test the number of source elements for plural strings in config translation forms.
635    */
636   public function testPluralConfigStringsSourceElements() {
637     $this->drupalLogin($this->adminUser);
638
639     // Languages to test, with various number of plural forms.
640     $languages = [
641       'vi' => ['plurals' => 1, 'expected' => [TRUE, FALSE, FALSE, FALSE]],
642       'fr' => ['plurals' => 2, 'expected' => [TRUE, TRUE, FALSE, FALSE]],
643       'sl' => ['plurals' => 4, 'expected' => [TRUE, TRUE, TRUE, TRUE]],
644     ];
645
646     foreach ($languages as $langcode => $data) {
647       // Import a .po file to add a new language with a given number of plural forms
648       $name = \Drupal::service('file_system')->tempnam('temporary://', $langcode . '_') . '.po';
649       file_put_contents($name, $this->getPoFile($data['plurals']));
650       $this->drupalPostForm('admin/config/regional/translate/import', [
651         'langcode' => $langcode,
652         'files[file]' => $name,
653       ], t('Import'));
654
655       // Change the config langcode of the 'files' view.
656       $config = \Drupal::service('config.factory')->getEditable('views.view.files');
657       $config->set('langcode', $langcode);
658       $config->save();
659
660       // Go to the translation page of the 'files' view.
661       $translation_url = 'admin/structure/views/view/files/translate/en/add';
662       $this->drupalGet($translation_url);
663
664       // Check if the expected number of source elements are present.
665       foreach ($data['expected'] as $index => $expected) {
666         if ($expected) {
667           $this->assertRaw('edit-source-config-names-viewsviewfiles-display-default-display-options-fields-count-format-plural-string-' . $index);
668         }
669         else {
670           $this->assertNoRaw('edit-source-config-names-viewsviewfiles-display-default-display-options-fields-count-format-plural-string-' . $index);
671         }
672       }
673     }
674   }
675
676   /**
677    * Test translation of plural strings with multiple plural forms in config.
678    */
679   public function testPluralConfigStrings() {
680     $this->drupalLogin($this->adminUser);
681
682     // First import a .po file with multiple plural forms.
683     // This will also automatically add the 'sl' language.
684     $name = \Drupal::service('file_system')->tempnam('temporary://', "sl_") . '.po';
685     file_put_contents($name, $this->getPoFile(4));
686     $this->drupalPostForm('admin/config/regional/translate/import', [
687       'langcode' => 'sl',
688       'files[file]' => $name,
689     ], t('Import'));
690
691     // Translate the files view, as this one uses numeric formatters.
692     $description = 'Singular form';
693     $field_value = '1 place';
694     $field_value_plural = '@count places';
695     $translation_url = 'admin/structure/views/view/files/translate/sl/add';
696     $this->drupalGet($translation_url);
697
698     // Make sure original text is present on this page, in addition to 2 new
699     // empty fields.
700     $this->assertRaw($description);
701     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][0]', $field_value);
702     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][1]', $field_value_plural);
703     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][2]', '');
704     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][3]', '');
705
706     // Then make sure it also works.
707     $edit = [
708       'translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][0]' => $field_value . ' SL',
709       'translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][1]' => $field_value_plural . ' 1 SL',
710       'translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][2]' => $field_value_plural . ' 2 SL',
711       'translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][3]' => $field_value_plural . ' 3 SL',
712     ];
713     $this->drupalPostForm($translation_url, $edit, t('Save translation'));
714
715     // Make sure the values have changed.
716     $this->drupalGet($translation_url);
717     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][0]', "$field_value SL");
718     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][1]', "$field_value_plural 1 SL");
719     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][2]', "$field_value_plural 2 SL");
720     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][3]', "$field_value_plural 3 SL");
721   }
722
723   /**
724    * Tests the translation of field and field storage configuration.
725    */
726   public function testFieldConfigTranslation() {
727     // Add a test field which has a translatable field setting and a
728     // translatable field storage setting.
729     $field_name = strtolower($this->randomMachineName());
730     $field_storage = FieldStorageConfig::create([
731       'field_name' => $field_name,
732       'entity_type' => 'entity_test',
733       'type' => 'test_field',
734     ]);
735
736     $translatable_storage_setting = $this->randomString();
737     $field_storage->setSetting('translatable_storage_setting', $translatable_storage_setting);
738     $field_storage->save();
739
740     $bundle = strtolower($this->randomMachineName());
741     entity_test_create_bundle($bundle);
742     $field = FieldConfig::create([
743       'field_name' => $field_name,
744       'entity_type' => 'entity_test',
745       'bundle' => $bundle,
746     ]);
747
748     $translatable_field_setting = $this->randomString();
749     $field->setSetting('translatable_field_setting', $translatable_field_setting);
750     $field->save();
751
752     $this->drupalLogin($this->translatorUser);
753
754     $this->drupalGet("/entity_test/structure/$bundle/fields/entity_test.$bundle.$field_name/translate");
755     $this->clickLink('Add');
756
757     $this->assertText('Translatable field setting');
758     $this->assertEscaped($translatable_field_setting);
759     $this->assertText('Translatable storage setting');
760     $this->assertEscaped($translatable_storage_setting);
761   }
762
763   /**
764    * Tests the translation of a boolean field settings.
765    */
766   public function testBooleanFieldConfigTranslation() {
767     // Add a test boolean field.
768     $field_name = strtolower($this->randomMachineName());
769     FieldStorageConfig::create([
770       'field_name' => $field_name,
771       'entity_type' => 'entity_test',
772       'type' => 'boolean',
773     ])->save();
774
775     $bundle = strtolower($this->randomMachineName());
776     entity_test_create_bundle($bundle);
777     $field = FieldConfig::create([
778       'field_name' => $field_name,
779       'entity_type' => 'entity_test',
780       'bundle' => $bundle,
781     ]);
782
783     $on_label = 'On label (with <em>HTML</em> & things)';
784     $field->setSetting('on_label', $on_label);
785     $off_label = 'Off label (with <em>HTML</em> & things)';
786     $field->setSetting('off_label', $off_label);
787     $field->save();
788
789     $this->drupalLogin($this->translatorUser);
790
791     $this->drupalGet("/entity_test/structure/$bundle/fields/entity_test.$bundle.$field_name/translate");
792     $this->clickLink('Add');
793
794     // Checks the text of details summary element that surrounds the translation
795     // options.
796     $this->assertText(Html::escape(strip_tags($on_label)) . ' Boolean settings');
797
798     // Checks that the correct on and off labels appear on the form.
799     $this->assertEscaped($on_label);
800     $this->assertEscaped($off_label);
801   }
802
803   /**
804    * Test translation storage in locale storage.
805    */
806   public function testLocaleDBStorage() {
807     // Enable import of translations. By default this is disabled for automated
808     // tests.
809     $this->config('locale.settings')
810       ->set('translation.import_enabled', TRUE)
811       ->save();
812
813     $this->drupalLogin($this->adminUser);
814
815     $langcode = 'xx';
816     $name = $this->randomMachineName(16);
817     $edit = [
818       'predefined_langcode' => 'custom',
819       'langcode' => $langcode,
820       'label' => $name,
821       'direction' => Language::DIRECTION_LTR,
822     ];
823     $this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
824
825     // Make sure there is no translation stored in locale storage before edit.
826     $translation = $this->getTranslation('user.settings', 'anonymous', 'fr');
827     $this->assertTrue(empty($translation));
828
829     // Add custom translation.
830     $edit = [
831       'translation[config_names][user.settings][anonymous]' => 'Anonyme',
832     ];
833     $this->drupalPostForm('admin/config/people/accounts/translate/fr/add', $edit, t('Save translation'));
834
835     // Make sure translation stored in locale storage after saved language
836     // specific configuration translation.
837     $translation = $this->getTranslation('user.settings', 'anonymous', 'fr');
838     $this->assertEqual('Anonyme', $translation->getString());
839
840     // revert custom translations to base translation.
841     $edit = [
842       'translation[config_names][user.settings][anonymous]' => 'Anonymous',
843     ];
844     $this->drupalPostForm('admin/config/people/accounts/translate/fr/edit', $edit, t('Save translation'));
845
846     // Make sure there is no translation stored in locale storage after revert.
847     $translation = $this->getTranslation('user.settings', 'anonymous', 'fr');
848     $this->assertEqual('Anonymous', $translation->getString());
849   }
850
851   /**
852    * Tests the single language existing.
853    */
854   public function testSingleLanguageUI() {
855     $this->drupalLogin($this->adminUser);
856
857     // Delete French language
858     $this->drupalPostForm('admin/config/regional/language/delete/fr', [], t('Delete'));
859     $this->assertRaw(t('The %language (%langcode) language has been removed.', ['%language' => 'French', '%langcode' => 'fr']));
860
861     // Change default language to Tamil.
862     $edit = [
863       'site_default_language' => 'ta',
864     ];
865     $this->drupalPostForm('admin/config/regional/language', $edit, t('Save configuration'));
866     $this->assertRaw(t('Configuration saved.'));
867
868     // Delete English language
869     $this->drupalPostForm('admin/config/regional/language/delete/en', [], t('Delete'));
870     $this->assertRaw(t('The %language (%langcode) language has been removed.', ['%language' => 'English', '%langcode' => 'en']));
871
872     // Visit account setting translation page, this should not
873     // throw any notices.
874     $this->drupalGet('admin/config/people/accounts/translate');
875     $this->assertResponse(200);
876   }
877
878   /**
879    * Tests the config_translation_info_alter() hook.
880    */
881   public function testAlterInfo() {
882     $this->drupalLogin($this->adminUser);
883
884     $this->container->get('state')->set('config_translation_test_config_translation_info_alter', TRUE);
885     $this->container->get('plugin.manager.config_translation.mapper')->clearCachedDefinitions();
886
887     // Check out if the translation page has the altered in settings.
888     $this->drupalGet('admin/config/system/site-information/translate/fr/add');
889     $this->assertText(t('Feed channel'));
890     $this->assertText(t('Feed description'));
891
892     // Check if the translation page does not have the altered out settings.
893     $this->drupalGet('admin/config/people/accounts/translate/fr/add');
894     $this->assertText(t('Name'));
895     $this->assertNoText(t('Account cancellation confirmation'));
896     $this->assertNoText(t('Password recovery'));
897   }
898
899   /**
900    * Tests the sequence data type translation.
901    */
902   public function testSequenceTranslation() {
903     $this->drupalLogin($this->adminUser);
904     /** @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory */
905     $config_factory = $this->container->get('config.factory');
906
907     $expected = [
908       'kitten',
909       'llama',
910       'elephant'
911     ];
912     $actual = $config_factory
913       ->getEditable('config_translation_test.content')
914       ->get('animals');
915     $this->assertEqual($expected, $actual);
916
917     $edit = [
918       'translation[config_names][config_translation_test.content][content][value]' => '<p><strong>Hello World</strong> - FR</p>',
919       'translation[config_names][config_translation_test.content][animals][0]' => 'kitten - FR',
920       'translation[config_names][config_translation_test.content][animals][1]' => 'llama - FR',
921       'translation[config_names][config_translation_test.content][animals][2]' => 'elephant - FR',
922     ];
923     $this->drupalPostForm('admin/config/media/file-system/translate/fr/add', $edit, t('Save translation'));
924
925     $this->container->get('language.config_factory_override')
926       ->setLanguage(new Language(['id' => 'fr']));
927
928     $expected = [
929       'kitten - FR',
930       'llama - FR',
931       'elephant - FR',
932     ];
933     $actual = $config_factory
934       ->get('config_translation_test.content')
935       ->get('animals');
936     $this->assertEqual($expected, $actual);
937   }
938
939   /**
940    * Test text_format translation.
941    */
942   public function testTextFormatTranslation() {
943     $this->drupalLogin($this->adminUser);
944     /** @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory */
945     $config_factory = $this->container->get('config.factory');
946
947     $expected = [
948       'value' => '<p><strong>Hello World</strong></p>',
949       'format' => 'plain_text',
950     ];
951     $actual = $config_factory
952       ->get('config_translation_test.content')
953       ->getOriginal('content', FALSE);
954     $this->assertEqual($expected, $actual);
955
956     $translation_base_url = 'admin/config/media/file-system/translate';
957     $this->drupalGet($translation_base_url);
958
959     // 'Add' link should be present for French translation.
960     $translation_page_url = "$translation_base_url/fr/add";
961     $this->assertLinkByHref($translation_page_url);
962
963     $this->drupalGet($translation_page_url);
964
965     // Assert that changing the text format is not possible, even for an
966     // administrator.
967     $this->assertNoFieldByName('translation[config_names][config_translation_test.content][content][format]');
968
969     // Update translatable fields.
970     $edit = [
971       'translation[config_names][config_translation_test.content][content][value]' => '<p><strong>Hello World</strong> - FR</p>',
972     ];
973
974     // Save language specific version of form.
975     $this->drupalPostForm($translation_page_url, $edit, t('Save translation'));
976
977     // Get translation and check we've got the right value.
978     $expected = [
979       'value' => '<p><strong>Hello World</strong> - FR</p>',
980       'format' => 'plain_text',
981     ];
982     $this->container->get('language.config_factory_override')
983       ->setLanguage(new Language(['id' => 'fr']));
984     $actual = $config_factory
985       ->get('config_translation_test.content')
986       ->get('content');
987     $this->assertEqual($expected, $actual);
988
989     // Change the text format of the source configuration and verify that the
990     // text format of the translation does not change because that could lead to
991     // security vulnerabilities.
992     $config_factory
993       ->getEditable('config_translation_test.content')
994       ->set('content.format', 'full_html')
995       ->save();
996
997     $actual = $config_factory
998       ->get('config_translation_test.content')
999       ->get('content');
1000     // The translation should not have changed, so re-use $expected.
1001     $this->assertEqual($expected, $actual);
1002
1003     // Because the text is now in a text format that the translator does not
1004     // have access to, the translator should not be able to translate it.
1005     $translation_page_url = "$translation_base_url/fr/edit";
1006     $this->drupalLogin($this->translatorUser);
1007     $this->drupalGet($translation_page_url);
1008     $this->assertDisabledTextarea('edit-translation-config-names-config-translation-testcontent-content-value');
1009     $this->drupalPostForm(NULL, [], t('Save translation'));
1010     // Check that submitting the form did not update the text format of the
1011     // translation.
1012     $actual = $config_factory
1013       ->get('config_translation_test.content')
1014       ->get('content');
1015     $this->assertEqual($expected, $actual);
1016
1017     // The administrator must explicitly change the text format.
1018     $this->drupalLogin($this->adminUser);
1019     $edit = [
1020       'translation[config_names][config_translation_test.content][content][format]' => 'full_html',
1021     ];
1022     $this->drupalPostForm($translation_page_url, $edit, t('Save translation'));
1023     $expected = [
1024       'value' => '<p><strong>Hello World</strong> - FR</p>',
1025       'format' => 'full_html',
1026     ];
1027     $actual = $config_factory
1028       ->get('config_translation_test.content')
1029       ->get('content');
1030     $this->assertEqual($expected, $actual);
1031   }
1032
1033   /**
1034    * Tests field translation for node fields.
1035    */
1036   public function testNodeFieldTranslation() {
1037     NodeType::create(['type' => 'article', 'name' => 'Article'])->save();
1038
1039     $field_name = 'translatable_field';
1040     $field_storage = FieldStorageConfig::create([
1041       'field_name' => $field_name,
1042       'entity_type' => 'node',
1043       'type' => 'text',
1044     ]);
1045
1046     $field_storage->setSetting('translatable_storage_setting', 'translatable_storage_setting');
1047     $field_storage->save();
1048     $field = FieldConfig::create([
1049       'field_name' => $field_name,
1050       'entity_type' => 'node',
1051       'bundle' => 'article',
1052     ]);
1053     $field->save();
1054
1055     $this->drupalLogin($this->translatorUser);
1056
1057     $this->drupalGet("/entity_test/structure/article/fields/node.article.$field_name/translate");
1058     $this->clickLink('Add');
1059
1060     $form_values = [
1061       'translation[config_names][field.field.node.article.translatable_field][description]' => 'FR Help text.',
1062       'translation[config_names][field.field.node.article.translatable_field][label]' => 'FR label',
1063     ];
1064     $this->drupalPostForm(NULL, $form_values, 'Save translation');
1065     $this->assertText('Successfully saved French translation.');
1066
1067     // Check that the translations are saved.
1068     $this->clickLink('Add');
1069     $this->assertRaw('FR label');
1070   }
1071
1072   /**
1073    * Gets translation from locale storage.
1074    *
1075    * @param $config_name
1076    *   Configuration object.
1077    * @param $key
1078    *   Translation configuration field key.
1079    * @param $langcode
1080    *   String language code to load translation.
1081    *
1082    * @return bool|mixed
1083    *   Returns translation if exists, FALSE otherwise.
1084    */
1085   protected function getTranslation($config_name, $key, $langcode) {
1086     $settings_locations = $this->localeStorage->getLocations(['type' => 'configuration', 'name' => $config_name]);
1087     $this->assertTrue(!empty($settings_locations), format_string('Configuration locations found for %config_name.', ['%config_name' => $config_name]));
1088
1089     if (!empty($settings_locations)) {
1090       $source = $this->container->get('config.factory')->get($config_name)->get($key);
1091       $source_string = $this->localeStorage->findString(['source' => $source, 'type' => 'configuration']);
1092       $this->assertTrue(!empty($source_string), format_string('Found string for %config_name.%key.', ['%config_name' => $config_name, '%key' => $key]));
1093
1094       if (!empty($source_string)) {
1095         $conditions = [
1096           'lid' => $source_string->lid,
1097           'language' => $langcode,
1098         ];
1099         $translations = $this->localeStorage->getTranslations($conditions + ['translated' => TRUE]);
1100         return reset($translations);
1101       }
1102     }
1103     return FALSE;
1104   }
1105
1106   /**
1107    * Sets site name and slogan for default language, helps in tests.
1108    *
1109    * @param string $site_name
1110    * @param string $site_slogan
1111    */
1112   protected function setSiteInformation($site_name, $site_slogan) {
1113     $edit = [
1114       'site_name' => $site_name,
1115       'site_slogan' => $site_slogan,
1116     ];
1117     $this->drupalPostForm('admin/config/system/site-information', $edit, t('Save configuration'));
1118     $this->assertRaw(t('The configuration options have been saved.'));
1119   }
1120
1121   /**
1122    * Get server-rendered contextual links for the given contextual link ids.
1123    *
1124    * @param array $ids
1125    *   An array of contextual link ids.
1126    * @param string $current_path
1127    *   The Drupal path for the page for which the contextual links are rendered.
1128    *
1129    * @return string
1130    *   The response body.
1131    */
1132   protected function renderContextualLinks($ids, $current_path) {
1133     $post = [];
1134     for ($i = 0; $i < count($ids); $i++) {
1135       $post['ids[' . $i . ']'] = $ids[$i];
1136     }
1137     return $this->drupalPostWithFormat('contextual/render', 'json', $post, ['query' => ['destination' => $current_path]]);
1138   }
1139
1140   /**
1141    * Asserts that a textarea with a given ID has been disabled from editing.
1142    *
1143    * @param string $id
1144    *   The HTML ID of the textarea.
1145    *
1146    * @return bool
1147    *   TRUE if the assertion passed; FALSE otherwise.
1148    */
1149   protected function assertDisabledTextarea($id) {
1150     $textarea = $this->xpath('//textarea[@id=:id and contains(@disabled, "disabled")]', [
1151       ':id' => $id,
1152     ]);
1153     $textarea = reset($textarea);
1154     $this->assertTrue($textarea instanceof NodeElement, SafeMarkup::format('Disabled field @id exists.', [
1155       '@id' => $id,
1156     ]));
1157     $expected = 'This field has been disabled because you do not have sufficient permissions to edit it.';
1158     $this->assertEqual($textarea->getText(), $expected, SafeMarkup::format('Disabled textarea @id hides text in an inaccessible text format.', [
1159       '@id' => $id,
1160     ]));
1161     // Make sure the text format select is not shown.
1162     $select_id = str_replace('value', 'format--2', $id);
1163     $select = $this->xpath('//select[@id=:id]', [':id' => $select_id]);
1164     return $this->assertFalse($select, SafeMarkup::format('Field @id does not exist.', [
1165       '@id' => $id,
1166     ]));
1167   }
1168
1169   /**
1170    * Helper function that returns a .po file with a given number of plural forms.
1171    */
1172   public function getPoFile($plurals) {
1173     $po_file = [];
1174
1175     $po_file[1] = <<< EOF
1176 msgid ""
1177 msgstr ""
1178 "Project-Id-Version: Drupal 8\\n"
1179 "MIME-Version: 1.0\\n"
1180 "Content-Type: text/plain; charset=UTF-8\\n"
1181 "Content-Transfer-Encoding: 8bit\\n"
1182 "Plural-Forms: nplurals=1; plural=0;\\n"
1183 EOF;
1184
1185     $po_file[2] = <<< EOF
1186 msgid ""
1187 msgstr ""
1188 "Project-Id-Version: Drupal 8\\n"
1189 "MIME-Version: 1.0\\n"
1190 "Content-Type: text/plain; charset=UTF-8\\n"
1191 "Content-Transfer-Encoding: 8bit\\n"
1192 "Plural-Forms: nplurals=2; plural=(n>1);\\n"
1193 EOF;
1194
1195     $po_file[4] = <<< EOF
1196 msgid ""
1197 msgstr ""
1198 "Project-Id-Version: Drupal 8\\n"
1199 "MIME-Version: 1.0\\n"
1200 "Content-Type: text/plain; charset=UTF-8\\n"
1201 "Content-Transfer-Encoding: 8bit\\n"
1202 "Plural-Forms: nplurals=4; plural=(((n%100)==1)?(0):(((n%100)==2)?(1):((((n%100)==3)||((n%100)==4))?(2):3)));\\n"
1203 EOF;
1204
1205     return $po_file[$plurals];
1206   }
1207
1208 }