Updated Drupal to 8.6. This goes with the following updates because it's possible...
[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\Render\FormattableMarkup;
8 use Drupal\Core\Language\Language;
9 use Drupal\Core\Language\LanguageInterface;
10 use Drupal\Core\Test\AssertMailTrait;
11 use Drupal\field\Entity\FieldConfig;
12 use Drupal\field\Entity\FieldStorageConfig;
13 use Drupal\filter\Entity\FilterFormat;
14 use Drupal\language\Entity\ConfigurableLanguage;
15 use Drupal\node\Entity\NodeType;
16 use Drupal\Tests\BrowserTestBase;
17
18 /**
19  * Translate settings and entities to various languages.
20  *
21  * @group config_translation
22  */
23 class ConfigTranslationUiTest extends BrowserTestBase {
24
25   use AssertMailTrait;
26
27   /**
28    * Modules to enable.
29    *
30    * @var array
31    */
32   public static $modules = [
33     'block',
34     'config_translation',
35     'config_translation_test',
36     'contact',
37     'contact_test',
38     'contextual',
39     'entity_test',
40     'field_test',
41     'field_ui',
42     'filter',
43     'filter_test',
44     'node',
45     'views',
46     'views_ui',
47   ];
48
49   /**
50    * Languages to enable.
51    *
52    * @var array
53    */
54   protected $langcodes = ['fr', 'ta'];
55
56   /**
57    * Administrator user for tests.
58    *
59    * @var \Drupal\user\UserInterface
60    */
61   protected $adminUser;
62
63   /**
64    * Translator user for tests.
65    *
66    * @var \Drupal\user\UserInterface
67    */
68   protected $translatorUser;
69
70   /**
71    * String translation storage object.
72    *
73    * @var \Drupal\locale\StringStorageInterface
74    */
75   protected $localeStorage;
76
77   protected function setUp() {
78     parent::setUp();
79     $translator_permissions = [
80       'translate configuration',
81     ];
82
83     /** @var \Drupal\filter\FilterFormatInterface $filter_test_format */
84     $filter_test_format = FilterFormat::load('filter_test');
85     /** @var \Drupal\filter\FilterFormatInterface $filtered_html_format */
86     $filtered_html_format = FilterFormat::load('filtered_html');
87     /** @var \Drupal\filter\FilterFormatInterface $full_html_format */
88     $full_html_format = FilterFormat::load('full_html');
89
90     $admin_permissions = array_merge(
91       $translator_permissions,
92       [
93         'administer languages',
94         'administer site configuration',
95         'link to any page',
96         'administer contact forms',
97         'administer filters',
98         $filtered_html_format->getPermissionName(),
99         $full_html_format->getPermissionName(),
100         $filter_test_format->getPermissionName(),
101         'access site-wide contact form',
102         'access contextual links',
103         'administer views',
104         'administer account settings',
105         'administer themes',
106         'bypass node access',
107         'administer content types',
108         'translate interface',
109       ]
110     );
111     // Create and log in user.
112     $this->translatorUser = $this->drupalCreateUser($translator_permissions);
113     $this->adminUser = $this->drupalCreateUser($admin_permissions);
114
115     // Add languages.
116     foreach ($this->langcodes as $langcode) {
117       ConfigurableLanguage::createFromLangcode($langcode)->save();
118     }
119     $this->localeStorage = $this->container->get('locale.storage');
120     $this->drupalPlaceBlock('local_tasks_block');
121     $this->drupalPlaceBlock('page_title_block');
122   }
123
124   /**
125    * Tests the site information translation interface.
126    */
127   public function testSiteInformationTranslationUi() {
128     $this->drupalLogin($this->adminUser);
129
130     $site_name = 'Name of the site for testing configuration translation';
131     $site_slogan = 'Site slogan for testing configuration translation';
132     $site_name_label = 'Site name';
133     $fr_site_name = 'Nom du site pour tester la configuration traduction';
134     $fr_site_slogan = 'Slogan du site pour tester la traduction de configuration';
135     $fr_site_name_label = 'LibellĂ© du champ "Nom du site"';
136     $translation_base_url = 'admin/config/system/site-information/translate';
137
138     // Set site name and slogan for default language.
139     $this->setSiteInformation($site_name, $site_slogan);
140
141     $this->drupalGet('admin/config/system/site-information');
142     // Check translation tab exist.
143     $this->assertLinkByHref($translation_base_url);
144
145     $this->drupalGet($translation_base_url);
146
147     // Check that the 'Edit' link in the source language links back to the
148     // original form.
149     $this->clickLink(t('Edit'));
150     // Also check that saving the form leads back to the translation overview.
151     $this->drupalPostForm(NULL, [], t('Save configuration'));
152     $this->assertUrl($translation_base_url);
153
154     // Check 'Add' link of French to visit add page.
155     $this->assertLinkByHref("$translation_base_url/fr/add");
156     $this->clickLink(t('Add'));
157
158     // Make sure original text is present on this page.
159     $this->assertRaw($site_name);
160     $this->assertRaw($site_slogan);
161
162     // Update site name and slogan for French.
163     $edit = [
164       'translation[config_names][system.site][name]' => $fr_site_name,
165       'translation[config_names][system.site][slogan]' => $fr_site_slogan,
166     ];
167
168     $this->drupalPostForm("$translation_base_url/fr/add", $edit, t('Save translation'));
169     $this->assertRaw(t('Successfully saved @language translation.', ['@language' => 'French']));
170
171     // Check for edit, delete links (and no 'add' link) for French language.
172     $this->assertNoLinkByHref("$translation_base_url/fr/add");
173     $this->assertLinkByHref("$translation_base_url/fr/edit");
174     $this->assertLinkByHref("$translation_base_url/fr/delete");
175
176     // Check translation saved proper.
177     $this->drupalGet("$translation_base_url/fr/edit");
178     $this->assertFieldByName('translation[config_names][system.site][name]', $fr_site_name);
179     $this->assertFieldByName('translation[config_names][system.site][slogan]', $fr_site_slogan);
180
181     // Place branding block with site name and slogan into header region.
182     $this->drupalPlaceBlock('system_branding_block', ['region' => 'header']);
183
184     // Check French translation of site name and slogan are in place.
185     $this->drupalGet('fr');
186     $this->assertRaw($fr_site_name);
187     $this->assertRaw($fr_site_slogan);
188
189     // Visit French site to ensure base language string present as source.
190     $this->drupalGet("fr/$translation_base_url/fr/edit");
191     $this->assertText($site_name);
192     $this->assertText($site_slogan);
193
194     // Translate 'Site name' label in French.
195     $search = [
196       'string' => $site_name_label,
197       'langcode' => 'fr',
198       'translation' => 'untranslated',
199     ];
200     $this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
201
202     $textarea = current($this->xpath('//textarea'));
203     $lid = $textarea->getAttribute('name');
204     $edit = [
205       $lid => $fr_site_name_label,
206     ];
207     $this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
208
209     // Ensure that the label is in French (and not in English).
210     $this->drupalGet("fr/$translation_base_url/fr/edit");
211     $this->assertText($fr_site_name_label);
212     $this->assertNoText($site_name_label);
213
214     // Ensure that the label is also in French (and not in English)
215     // when editing another language with the interface in French.
216     $this->drupalGet("fr/$translation_base_url/ta/edit");
217     $this->assertText($fr_site_name_label);
218     $this->assertNoText($site_name_label);
219
220     // Ensure that the label is not translated when the interface is in English.
221     $this->drupalGet("$translation_base_url/fr/edit");
222     $this->assertText($site_name_label);
223     $this->assertNoText($fr_site_name_label);
224   }
225
226   /**
227    * Tests the site information translation interface.
228    */
229   public function testSourceValueDuplicateSave() {
230     $this->drupalLogin($this->adminUser);
231
232     $site_name = 'Site name for testing configuration translation';
233     $site_slogan = 'Site slogan for testing configuration translation';
234     $translation_base_url = 'admin/config/system/site-information/translate';
235     $this->setSiteInformation($site_name, $site_slogan);
236
237     $this->drupalGet($translation_base_url);
238
239     // Case 1: Update new value for site slogan and site name.
240     $edit = [
241       'translation[config_names][system.site][name]' => 'FR ' . $site_name,
242       'translation[config_names][system.site][slogan]' => 'FR ' . $site_slogan,
243     ];
244     // First time, no overrides, so just Add link.
245     $this->drupalPostForm("$translation_base_url/fr/add", $edit, t('Save translation'));
246
247     // Read overridden file from active config.
248     $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'system.site');
249
250     // Expect both name and slogan in language specific file.
251     $expected = [
252       'name' => 'FR ' . $site_name,
253       'slogan' => 'FR ' . $site_slogan,
254     ];
255     $this->assertEqual($expected, $override->get());
256
257     // Case 2: Update new value for site slogan and default value for site name.
258     $this->drupalGet("$translation_base_url/fr/edit");
259     // Assert that the language configuration does not leak outside of the
260     // translation form into the actual site name and slogan.
261     $this->assertNoText('FR ' . $site_name);
262     $this->assertNoText('FR ' . $site_slogan);
263     $edit = [
264       'translation[config_names][system.site][name]' => $site_name,
265       'translation[config_names][system.site][slogan]' => 'FR ' . $site_slogan,
266     ];
267     $this->drupalPostForm(NULL, $edit, t('Save translation'));
268     $this->assertRaw(t('Successfully updated @language translation.', ['@language' => 'French']));
269     $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'system.site');
270
271     // Expect only slogan in language specific file.
272     $expected = 'FR ' . $site_slogan;
273     $this->assertEqual($expected, $override->get('slogan'));
274
275     // Case 3: Keep default value for site name and slogan.
276     $this->drupalGet("$translation_base_url/fr/edit");
277     $this->assertNoText('FR ' . $site_slogan);
278     $edit = [
279       'translation[config_names][system.site][name]' => $site_name,
280       'translation[config_names][system.site][slogan]' => $site_slogan,
281     ];
282     $this->drupalPostForm(NULL, $edit, t('Save translation'));
283     $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'system.site');
284
285     // Expect no language specific file.
286     $this->assertTrue($override->isNew());
287
288     // Check configuration page with translator user. Should have no access.
289     $this->drupalLogout();
290     $this->drupalLogin($this->translatorUser);
291     $this->drupalGet('admin/config/system/site-information');
292     $this->assertResponse(403);
293
294     // While translator can access the translation page, the edit link is not
295     // present due to lack of permissions.
296     $this->drupalGet($translation_base_url);
297     $this->assertNoLink(t('Edit'));
298
299     // Check 'Add' link for French.
300     $this->assertLinkByHref("$translation_base_url/fr/add");
301   }
302
303   /**
304    * Tests the contact form translation.
305    */
306   public function testContactConfigEntityTranslation() {
307     $this->drupalLogin($this->adminUser);
308
309     $this->drupalGet('admin/structure/contact');
310
311     // Check for default contact form configuration entity from Contact module.
312     $this->assertLinkByHref('admin/structure/contact/manage/feedback');
313
314     // Save default language configuration.
315     $label = 'Send your feedback';
316     $edit = [
317       'label' => $label,
318       'recipients' => 'sales@example.com,support@example.com',
319       'reply' => 'Thank you for your mail',
320     ];
321     $this->drupalPostForm('admin/structure/contact/manage/feedback', $edit, t('Save'));
322
323     // Ensure translation link is present.
324     $translation_base_url = 'admin/structure/contact/manage/feedback/translate';
325     $this->assertLinkByHref($translation_base_url);
326
327     // Make sure translate tab is present.
328     $this->drupalGet('admin/structure/contact/manage/feedback');
329     $this->assertLink(t('Translate @type', ['@type' => 'contact form']));
330
331     // Visit the form to confirm the changes.
332     $this->drupalGet('contact/feedback');
333     $this->assertText($label);
334
335     foreach ($this->langcodes as $langcode) {
336       $this->drupalGet($translation_base_url);
337       $this->assertLink(t('Translate @type', ['@type' => 'contact form']));
338
339       // 'Add' link should be present for $langcode translation.
340       $translation_page_url = "$translation_base_url/$langcode/add";
341       $this->assertLinkByHref($translation_page_url);
342
343       // Make sure original text is present on this page.
344       $this->drupalGet($translation_page_url);
345       $this->assertText($label);
346
347       // Update translatable fields.
348       $edit = [
349         'translation[config_names][contact.form.feedback][label]' => 'Website feedback - ' . $langcode,
350         'translation[config_names][contact.form.feedback][reply]' => 'Thank you for your mail - ' . $langcode,
351       ];
352
353       // Save language specific version of form.
354       $this->drupalPostForm($translation_page_url, $edit, t('Save translation'));
355
356       // Expect translated values in language specific file.
357       $override = \Drupal::languageManager()->getLanguageConfigOverride($langcode, 'contact.form.feedback');
358       $expected = [
359         'label' => 'Website feedback - ' . $langcode,
360         'reply' => 'Thank you for your mail - ' . $langcode,
361       ];
362       $this->assertEqual($expected, $override->get());
363
364       // Check for edit, delete links (and no 'add' link) for $langcode.
365       $this->assertNoLinkByHref("$translation_base_url/$langcode/add");
366       $this->assertLinkByHref("$translation_base_url/$langcode/edit");
367       $this->assertLinkByHref("$translation_base_url/$langcode/delete");
368
369       // Visit language specific version of form to check label.
370       $this->drupalGet($langcode . '/contact/feedback');
371       $this->assertText('Website feedback - ' . $langcode);
372
373       // Submit feedback.
374       $edit = [
375         'subject[0][value]' => 'Test subject',
376         'message[0][value]' => 'Test message',
377       ];
378       $this->drupalPostForm(NULL, $edit, t('Send message'));
379     }
380
381     // Now that all language translations are present, check translation and
382     // original text all appear in any translated page on the translation
383     // forms.
384     foreach ($this->langcodes as $langcode) {
385       $langcode_prefixes = array_merge([''], $this->langcodes);
386       foreach ($langcode_prefixes as $langcode_prefix) {
387         $this->drupalGet(ltrim("$langcode_prefix/$translation_base_url/$langcode/edit", '/'));
388         $this->assertFieldByName('translation[config_names][contact.form.feedback][label]', 'Website feedback - ' . $langcode);
389         $this->assertText($label);
390       }
391     }
392
393     // We get all emails so no need to check inside the loop.
394     $captured_emails = $this->getMails();
395
396     // Check language specific auto reply text in email body.
397     foreach ($captured_emails as $email) {
398       if ($email['id'] == 'contact_page_autoreply') {
399         // Trim because we get an added newline for the body.
400         $this->assertEqual(trim($email['body']), 'Thank you for your mail - ' . $email['langcode']);
401       }
402     }
403
404     // Test that delete links work and operations perform properly.
405     foreach ($this->langcodes as $langcode) {
406       $replacements = ['%label' => t('@label @entity_type', ['@label' => $label, '@entity_type' => mb_strtolower(t('Contact form'))]), '@language' => \Drupal::languageManager()->getLanguage($langcode)->getName()];
407
408       $this->drupalGet("$translation_base_url/$langcode/delete");
409       $this->assertRaw(t('Are you sure you want to delete the @language translation of %label?', $replacements));
410       // Assert link back to list page to cancel delete is present.
411       $this->assertLinkByHref($translation_base_url);
412
413       $this->drupalPostForm(NULL, [], t('Delete'));
414       $this->assertRaw(t('@language translation of %label was deleted', $replacements));
415       $this->assertLinkByHref("$translation_base_url/$langcode/add");
416       $this->assertNoLinkByHref("translation_base_url/$langcode/edit");
417       $this->assertNoLinkByHref("$translation_base_url/$langcode/delete");
418
419       // Expect no language specific file present anymore.
420       $override = \Drupal::languageManager()->getLanguageConfigOverride($langcode, 'contact.form.feedback');
421       $this->assertTrue($override->isNew());
422     }
423
424     // Check configuration page with translator user. Should have no access.
425     $this->drupalLogout();
426     $this->drupalLogin($this->translatorUser);
427     $this->drupalGet('admin/structure/contact/manage/feedback');
428     $this->assertResponse(403);
429
430     // While translator can access the translation page, the edit link is not
431     // present due to lack of permissions.
432     $this->drupalGet($translation_base_url);
433     $this->assertNoLink(t('Edit'));
434
435     // Check 'Add' link for French.
436     $this->assertLinkByHref("$translation_base_url/fr/add");
437   }
438
439   /**
440    * Tests date format translation.
441    */
442   public function testDateFormatTranslation() {
443     $this->drupalLogin($this->adminUser);
444
445     $this->drupalGet('admin/config/regional/date-time');
446
447     // Check for medium format.
448     $this->assertLinkByHref('admin/config/regional/date-time/formats/manage/medium');
449
450     // Save default language configuration for a new format.
451     $edit = [
452       'label' => 'Custom medium date',
453       'id' => 'custom_medium',
454       'date_format_pattern' => 'Y. m. d. H:i',
455     ];
456     $this->drupalPostForm('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
457
458     // Test translating a default shipped format and our custom format.
459     $formats = [
460       'medium' => 'Default medium date',
461       'custom_medium' => 'Custom medium date',
462     ];
463     foreach ($formats as $id => $label) {
464       $translation_base_url = 'admin/config/regional/date-time/formats/manage/' . $id . '/translate';
465
466       $this->drupalGet($translation_base_url);
467
468       // 'Add' link should be present for French translation.
469       $translation_page_url = "$translation_base_url/fr/add";
470       $this->assertLinkByHref($translation_page_url);
471
472       // Make sure original text is present on this page.
473       $this->drupalGet($translation_page_url);
474       $this->assertText($label);
475
476       // Make sure that the date library is added.
477       $this->assertRaw('core/modules/system/js/system.date.js');
478
479       // Update translatable fields.
480       $edit = [
481         'translation[config_names][core.date_format.' . $id . '][label]' => $id . ' - FR',
482         'translation[config_names][core.date_format.' . $id . '][pattern]' => 'D',
483       ];
484
485       // Save language specific version of form.
486       $this->drupalPostForm($translation_page_url, $edit, t('Save translation'));
487
488       // Get translation and check we've got the right value.
489       $override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'core.date_format.' . $id);
490       $expected = [
491         'label' => $id . ' - FR',
492         'pattern' => 'D',
493       ];
494       $this->assertEqual($expected, $override->get());
495
496       // Formatting the date 8 / 27 / 1985 @ 13:37 EST with pattern D should
497       // display "Tue".
498       $formatted_date = format_date(494015820, $id, NULL, 'America/New_York', 'fr');
499       $this->assertEqual($formatted_date, 'Tue', 'Got the right formatted date using the date format translation pattern.');
500     }
501   }
502
503   /**
504    * Tests the account settings translation interface.
505    *
506    * This is the only special case so far where we have multiple configuration
507    * names involved building up one configuration translation form. Test that
508    * the translations are saved for all configuration names properly.
509    */
510   public function testAccountSettingsConfigurationTranslation() {
511     $this->drupalLogin($this->adminUser);
512
513     $this->drupalGet('admin/config/people/accounts');
514     $this->assertLink(t('Translate @type', ['@type' => 'account settings']));
515
516     $this->drupalGet('admin/config/people/accounts/translate');
517     $this->assertLink(t('Translate @type', ['@type' => 'account settings']));
518     $this->assertLinkByHref('admin/config/people/accounts/translate/fr/add');
519
520     // Update account settings fields for French.
521     $edit = [
522       'translation[config_names][user.settings][anonymous]' => 'Anonyme',
523       'translation[config_names][user.mail][status_blocked][subject]' => 'Testing, your account is blocked.',
524       'translation[config_names][user.mail][status_blocked][body]' => 'Testing account blocked body.',
525     ];
526
527     $this->drupalPostForm('admin/config/people/accounts/translate/fr/add', $edit, t('Save translation'));
528
529     // Make sure the changes are saved and loaded back properly.
530     $this->drupalGet('admin/config/people/accounts/translate/fr/edit');
531     foreach ($edit as $key => $value) {
532       // Check the translations appear in the right field type as well.
533       $xpath = '//' . (strpos($key, '[body]') ? 'textarea' : 'input') . '[@name="' . $key . '"]';
534       $this->assertFieldByXPath($xpath, $value);
535     }
536     // Check that labels for email settings appear.
537     $this->assertText(t('Account cancellation confirmation'));
538     $this->assertText(t('Password recovery'));
539   }
540
541   /**
542    * Tests source and target language edge cases.
543    */
544   public function testSourceAndTargetLanguage() {
545     $this->drupalLogin($this->adminUser);
546
547     // Loading translation page for not-specified language (und)
548     // should return 403.
549     $this->drupalGet('admin/config/system/site-information/translate/und/add');
550     $this->assertResponse(403);
551
552     // Check the source language doesn't have 'Add' or 'Delete' link and
553     // make sure source language edit goes to original configuration page
554     // not the translation specific edit page.
555     $this->drupalGet('admin/config/system/site-information/translate');
556     $this->assertNoLinkByHref('admin/config/system/site-information/translate/en/edit');
557     $this->assertNoLinkByHref('admin/config/system/site-information/translate/en/add');
558     $this->assertNoLinkByHref('admin/config/system/site-information/translate/en/delete');
559     $this->assertLinkByHref('admin/config/system/site-information');
560
561     // Translation addition to source language should return 403.
562     $this->drupalGet('admin/config/system/site-information/translate/en/add');
563     $this->assertResponse(403);
564
565     // Translation editing in source language should return 403.
566     $this->drupalGet('admin/config/system/site-information/translate/en/edit');
567     $this->assertResponse(403);
568
569     // Translation deletion in source language should return 403.
570     $this->drupalGet('admin/config/system/site-information/translate/en/delete');
571     $this->assertResponse(403);
572
573     // Set default language of site information to not-specified language (und).
574     $this->config('system.site')
575       ->set('langcode', LanguageInterface::LANGCODE_NOT_SPECIFIED)
576       ->save();
577
578     // Make sure translation tab does not exist on the configuration page.
579     $this->drupalGet('admin/config/system/site-information');
580     $this->assertNoLinkByHref('admin/config/system/site-information/translate');
581
582     // If source language is not specified, translation page should be 403.
583     $this->drupalGet('admin/config/system/site-information/translate');
584     $this->assertResponse(403);
585   }
586
587   /**
588    * Tests the views translation interface.
589    */
590   public function testViewsTranslationUI() {
591     $this->drupalLogin($this->adminUser);
592
593     $description = 'All content promoted to the front page.';
594     $human_readable_name = 'Frontpage';
595     $display_settings_master = 'Master';
596     $display_options_master = '(Empty)';
597     $translation_base_url = 'admin/structure/views/view/frontpage/translate';
598
599     $this->drupalGet($translation_base_url);
600
601     // Check 'Add' link of French to visit add page.
602     $this->assertLinkByHref("$translation_base_url/fr/add");
603     $this->clickLink(t('Add'));
604
605     // Make sure original text is present on this page.
606     $this->assertRaw($description);
607     $this->assertRaw($human_readable_name);
608
609     // Update Views Fields for French.
610     $edit = [
611       'translation[config_names][views.view.frontpage][description]' => $description . " FR",
612       'translation[config_names][views.view.frontpage][label]' => $human_readable_name . " FR",
613       'translation[config_names][views.view.frontpage][display][default][display_title]' => $display_settings_master . " FR",
614       'translation[config_names][views.view.frontpage][display][default][display_options][title]' => $display_options_master . " FR",
615     ];
616     $this->drupalPostForm("$translation_base_url/fr/add", $edit, t('Save translation'));
617     $this->assertRaw(t('Successfully saved @language translation.', ['@language' => 'French']));
618
619     // Check for edit, delete links (and no 'add' link) for French language.
620     $this->assertNoLinkByHref("$translation_base_url/fr/add");
621     $this->assertLinkByHref("$translation_base_url/fr/edit");
622     $this->assertLinkByHref("$translation_base_url/fr/delete");
623
624     // Check translation saved proper.
625     $this->drupalGet("$translation_base_url/fr/edit");
626     $this->assertFieldByName('translation[config_names][views.view.frontpage][description]', $description . " FR");
627     $this->assertFieldByName('translation[config_names][views.view.frontpage][label]', $human_readable_name . " FR");
628     $this->assertFieldByName('translation[config_names][views.view.frontpage][display][default][display_title]', $display_settings_master . " FR");
629     $this->assertFieldByName('translation[config_names][views.view.frontpage][display][default][display_options][title]', $display_options_master . " FR");
630   }
631
632   /**
633    * Test the number of source elements for plural strings in config translation forms.
634    */
635   public function testPluralConfigStringsSourceElements() {
636     $this->drupalLogin($this->adminUser);
637
638     // Languages to test, with various number of plural forms.
639     $languages = [
640       'vi' => ['plurals' => 1, 'expected' => [TRUE, FALSE, FALSE, FALSE]],
641       'fr' => ['plurals' => 2, 'expected' => [TRUE, TRUE, FALSE, FALSE]],
642       'sl' => ['plurals' => 4, 'expected' => [TRUE, TRUE, TRUE, TRUE]],
643     ];
644
645     foreach ($languages as $langcode => $data) {
646       // Import a .po file to add a new language with a given number of plural forms
647       $name = \Drupal::service('file_system')->tempnam('temporary://', $langcode . '_') . '.po';
648       file_put_contents($name, $this->getPoFile($data['plurals']));
649       $this->drupalPostForm('admin/config/regional/translate/import', [
650         'langcode' => $langcode,
651         'files[file]' => $name,
652       ], t('Import'));
653
654       // Change the config langcode of the 'files' view.
655       $config = \Drupal::service('config.factory')->getEditable('views.view.files');
656       $config->set('langcode', $langcode);
657       $config->save();
658
659       // Go to the translation page of the 'files' view.
660       $translation_url = 'admin/structure/views/view/files/translate/en/add';
661       $this->drupalGet($translation_url);
662
663       // Check if the expected number of source elements are present.
664       foreach ($data['expected'] as $index => $expected) {
665         if ($expected) {
666           $this->assertRaw('edit-source-config-names-viewsviewfiles-display-default-display-options-fields-count-format-plural-string-' . $index);
667         }
668         else {
669           $this->assertNoRaw('edit-source-config-names-viewsviewfiles-display-default-display-options-fields-count-format-plural-string-' . $index);
670         }
671       }
672     }
673   }
674
675   /**
676    * Test translation of plural strings with multiple plural forms in config.
677    */
678   public function testPluralConfigStrings() {
679     $this->drupalLogin($this->adminUser);
680
681     // First import a .po file with multiple plural forms.
682     // This will also automatically add the 'sl' language.
683     $name = \Drupal::service('file_system')->tempnam('temporary://', "sl_") . '.po';
684     file_put_contents($name, $this->getPoFile(4));
685     $this->drupalPostForm('admin/config/regional/translate/import', [
686       'langcode' => 'sl',
687       'files[file]' => $name,
688     ], t('Import'));
689
690     // Translate the files view, as this one uses numeric formatters.
691     $description = 'Singular form';
692     $field_value = '1 place';
693     $field_value_plural = '@count places';
694     $translation_url = 'admin/structure/views/view/files/translate/sl/add';
695     $this->drupalGet($translation_url);
696
697     // Make sure original text is present on this page, in addition to 2 new
698     // empty fields.
699     $this->assertRaw($description);
700     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][0]', $field_value);
701     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][1]', $field_value_plural);
702     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][2]', '');
703     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][3]', '');
704
705     // Then make sure it also works.
706     $edit = [
707       'translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][0]' => $field_value . ' SL',
708       'translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][1]' => $field_value_plural . ' 1 SL',
709       'translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][2]' => $field_value_plural . ' 2 SL',
710       'translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][3]' => $field_value_plural . ' 3 SL',
711     ];
712     $this->drupalPostForm($translation_url, $edit, t('Save translation'));
713
714     // Make sure the values have changed.
715     $this->drupalGet($translation_url);
716     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][0]', "$field_value SL");
717     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][1]', "$field_value_plural 1 SL");
718     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][2]', "$field_value_plural 2 SL");
719     $this->assertFieldByName('translation[config_names][views.view.files][display][default][display_options][fields][count][format_plural_string][3]', "$field_value_plural 3 SL");
720   }
721
722   /**
723    * Tests the translation of field and field storage configuration.
724    */
725   public function testFieldConfigTranslation() {
726     // Add a test field which has a translatable field setting and a
727     // translatable field storage setting.
728     $field_name = strtolower($this->randomMachineName());
729     $field_storage = FieldStorageConfig::create([
730       'field_name' => $field_name,
731       'entity_type' => 'entity_test',
732       'type' => 'test_field',
733     ]);
734
735     $translatable_storage_setting = $this->randomString();
736     $field_storage->setSetting('translatable_storage_setting', $translatable_storage_setting);
737     $field_storage->save();
738
739     $bundle = strtolower($this->randomMachineName());
740     entity_test_create_bundle($bundle);
741     $field = FieldConfig::create([
742       'field_name' => $field_name,
743       'entity_type' => 'entity_test',
744       'bundle' => $bundle,
745     ]);
746
747     $translatable_field_setting = $this->randomString();
748     $field->setSetting('translatable_field_setting', $translatable_field_setting);
749     $field->save();
750
751     $this->drupalLogin($this->translatorUser);
752
753     $this->drupalGet("/entity_test/structure/$bundle/fields/entity_test.$bundle.$field_name/translate");
754     $this->clickLink('Add');
755
756     $this->assertText('Translatable field setting');
757     $this->assertEscaped($translatable_field_setting);
758     $this->assertText('Translatable storage setting');
759     $this->assertEscaped($translatable_storage_setting);
760   }
761
762   /**
763    * Tests the translation of a boolean field settings.
764    */
765   public function testBooleanFieldConfigTranslation() {
766     // Add a test boolean field.
767     $field_name = strtolower($this->randomMachineName());
768     FieldStorageConfig::create([
769       'field_name' => $field_name,
770       'entity_type' => 'entity_test',
771       'type' => 'boolean',
772     ])->save();
773
774     $bundle = strtolower($this->randomMachineName());
775     entity_test_create_bundle($bundle);
776     $field = FieldConfig::create([
777       'field_name' => $field_name,
778       'entity_type' => 'entity_test',
779       'bundle' => $bundle,
780     ]);
781
782     $on_label = 'On label (with <em>HTML</em> & things)';
783     $field->setSetting('on_label', $on_label);
784     $off_label = 'Off label (with <em>HTML</em> & things)';
785     $field->setSetting('off_label', $off_label);
786     $field->save();
787
788     $this->drupalLogin($this->translatorUser);
789
790     $this->drupalGet("/entity_test/structure/$bundle/fields/entity_test.$bundle.$field_name/translate");
791     $this->clickLink('Add');
792
793     // Checks the text of details summary element that surrounds the translation
794     // options.
795     $this->assertText(Html::escape(strip_tags($on_label)) . ' Boolean settings');
796
797     // Checks that the correct on and off labels appear on the form.
798     $this->assertEscaped($on_label);
799     $this->assertEscaped($off_label);
800   }
801
802   /**
803    * Test translation storage in locale storage.
804    */
805   public function testLocaleDBStorage() {
806     // Enable import of translations. By default this is disabled for automated
807     // tests.
808     $this->config('locale.settings')
809       ->set('translation.import_enabled', TRUE)
810       ->set('translation.use_source', LOCALE_TRANSLATION_USE_SOURCE_LOCAL)
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, new FormattableMarkup('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, new FormattableMarkup('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, new FormattableMarkup('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 }