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